Skip to content

πŸ“„ Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

update api4cpp .

mayong82184c106850
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 25b0a1b..a1b946d 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -2,16 +2,41 @@ cmake_minimum_required(VERSION 3.10)
project(BaiPiaoOCR)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/cpp/BaiPiaoOcrOnnx/include)
-include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/onnxruntime/core/session)
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/onnxruntime/)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/)
+
+
if(WIN32)
add_definitions(-D_BPOCR_EXPORT_API)
-
+ link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib/win/x64/)
+ IF(CMAKE_BUILD_TYPE STREQUAL Debug) #debug
+ link_libraries(opencv_world3413d.lib onnxruntime.lib)
+ else()
+ link_libraries(opencv_world3413.lib onnxruntime.lib)
+ endif()
+
elseif(UNIX)
include_directories(/usr/include/opencv4/)
+ FIND_PACKAGE(OpenCV REQUIRED)
+ if(OPENCV_FOUND)
+ message("OPenCV FOUND")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenCV_C_FLAGS}")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenCV_CXX_FLAGS}")
+ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenCV_EXE_LINKER_FLAGS}")
+ message(${CMAKE_EXE_LINKER_FLAGS})
+ endif()
+endif()
+# openmp
+FIND_PACKAGE( OpenMP REQUIRED)
+if(OPENMP_FOUND)
+message("OPENMP FOUND")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
+message(${CMAKE_EXE_LINKER_FLAGS})
endif()
add_definitions(-D__OPENMP__)
@@ -34,7 +59,8 @@ set(OPENCV_LIB opencv_core opencv_imgproc opencv_imgcodecs)
if(WIN32)
target_link_directories(bpocrapi PUBLIC lib/win)
-
+target_link_libraries(bpocrtest bpocrapi)
+#INSTALL_NUGET(bpocrapi Microsoft.ML.OnnxRuntime 1.6.0)
elseif(UNIX)
message(STATUS ${CMAKE_CURRENT_SOURCE_DIR}/lib/linux)
diff --git a/api4cpp/baipiaoocr_api.cpp b/api4cpp/baipiaoocr_api.cpp
index 42b0543..fe59a6b 100755
--- a/api4cpp/baipiaoocr_api.cpp
+++ b/api4cpp/baipiaoocr_api.cpp
@@ -4,16 +4,22 @@ extern "C"
{
#endif
+ typedef struct
+ {
+ OcrLite OcrObj;
+ std::string strRes;
+ }OCR_OBJ;
+
_QM_OCR_API BPHANDLE BPOcrInit(const char* szDetModel, const char* szClsModel, const char* szRecModel,const char *szKeyPath, int nThreads)
{
omp_set_num_threads(nThreads);
- OcrLite * pOcrObj=new OcrLite;
+ OCR_OBJ* pOcrObj=new OCR_OBJ;
if(pOcrObj)
{
- pOcrObj->setNumThread(nThreads);
+ pOcrObj->OcrObj.setNumThread(nThreads);
- pOcrObj->initModels(szDetModel, szClsModel, szRecModel, szKeyPath);
+ pOcrObj->OcrObj.initModels(szDetModel, szClsModel, szRecModel, szKeyPath);
return pOcrObj;
}
@@ -25,12 +31,12 @@ extern "C"
}
- _QM_OCR_API const char* BPOcrDoOcr(BPHANDLE handle, const char* szImgPath, BOOL bAutoParam,BOOL bLongPic,BPOCR_PARAM *pParam)
+ _QM_OCR_API BOOL BPOcrDoOcr(BPHANDLE handle, const char* szImgPath, BOOL bAutoParam,BOOL bLongPic,BPOCR_PARAM *pParam)
{
- OcrLite * pOcrObj=( OcrLite *)handle;
+ OCR_OBJ* pOcrObj=(OCR_OBJ*)handle;
if(!pOcrObj)
- return NULL;
+ return FALSE;
BPOCR_PARAM Param = *pParam;
if(bAutoParam)
@@ -74,19 +80,48 @@ extern "C"
}
std::string imgPath,imgDir,imgName;
imgPath=szImgPath;
- imgDir.assign(imgPath.substr(0, imgPath.find_last_of('/') + 1));
- imgName.assign(imgPath.substr(imgPath.find_last_of('/') + 1));
- OcrResult result=pOcrObj->detect(imgDir.c_str(),imgName.c_str(),Param.padding,Param.maxSideLen,Param.boxScoreThresh,Param.boxThresh,Param.unClipRatio,Param.flagDoAngle?true:false,Param.flagMostAngle?true:false);
- if(result.strRes.length()>0)
- return result.strRes.c_str();
+ imgDir.assign(imgPath.substr(0, imgPath.find_last_of('\\') + 1));
+ imgName.assign(imgPath.substr(imgPath.find_last_of('\\') + 1));
+ OcrResult result=pOcrObj->OcrObj.detect(imgDir.c_str(),imgName.c_str(),Param.padding,Param.maxSideLen,Param.boxScoreThresh,Param.boxThresh,Param.unClipRatio,Param.flagDoAngle?true:false,Param.flagMostAngle?true:false);
+ if (result.strRes.length() > 0)
+ {
+
+ pOcrObj->strRes = result.strRes;
+ return TRUE;
+ }
else
- return "";
+ return FALSE;
+ }
+
+
+ _QM_OCR_API int BPOcrGetLen(BPHANDLE handle)
+ {
+ OCR_OBJ* pOcrObj = (OCR_OBJ*)handle;
+ if (!pOcrObj)
+ return 0;
+ return pOcrObj->strRes.size()+1;
+ }
+
+ _QM_OCR_API BOOL BPOcrGetResult(BPHANDLE handle, char* szBuf, int nLen)
+ {
+
+ OCR_OBJ* pOcrObj = (OCR_OBJ*)handle;
+ if (!pOcrObj)
+ return FALSE;
+
+ if (nLen > pOcrObj->strRes.size())
+ {
+ strncpy(szBuf, pOcrObj->strRes.c_str(), pOcrObj->strRes.size());
+ szBuf[pOcrObj->strRes.size() - 1] = 0;
+ }
+
+ return pOcrObj->strRes.size();
}
_QM_OCR_API void BPOcrDeinit(BPHANDLE handle)
{
- OcrLite * pOcrObj=( OcrLite *)handle;
+ OCR_OBJ* pOcrObj=(OCR_OBJ*)handle;
if(pOcrObj)
delete pOcrObj;
diff --git a/api4cpp/bpocrapitest.cpp b/api4cpp/bpocrapitest.cpp
index ccf4923..f53ba0c 100755
--- a/api4cpp/bpocrapitest.cpp
+++ b/api4cpp/bpocrapitest.cpp
@@ -5,17 +5,23 @@
#include <string>
#include "../include/baipiaoocr_api.h"
-#define BPOCR_DET_MODEL "/ch_ppocr_mobile_v2.0_det_infer.onnx"
-#define BPOCR_CLS_MODEL "/ch_ppocr_mobile_v2.0_cls_infer.onnx"
-#define BPOCR_REC_MODEL "/ch_ppocr_mobile_v2.0_rec_infer.onnx"
-#define BPOCR_KEY_PATH "/ppocr_keys_v1.txt"
+#define BPOCR_DET_MODEL "ch_ppocr_mobile_v2.0_det_infer.onnx"
+#define BPOCR_CLS_MODEL "ch_ppocr_mobile_v2.0_cls_infer.onnx"
+#define BPOCR_REC_MODEL "ch_ppocr_mobile_v2.0_rec_infer.onnx"
+#define BPOCR_KEY_PATH "ppocr_keys_v1.txt"
#define THREAD_NUM 3
#define MAX_PATH 260
+#ifdef WIN32
+const char* DEFAULT_MODEL_DIR = "E:\\bai-piao-ocr\\cpp\\BaiPiaoOcrOnnx\\models\\";
+
+const char* DEFAULT_TEST_IMG = "E:\\bai-piao-ocr\\cpp\\BaiPiaoOcrOnnx\\images\\1.jpg";
+#else
const char * DEFAULT_MODEL_DIR ="/data/workprj/BaiPiaoOCR/models";
const char * DEFAULT_TEST_IMG ="/data/workprj/BaiPiaoOCR/images/1.jpg";
+#endif
int main(int argc, char * argv[])
{
@@ -63,8 +69,24 @@ const char *szImagePath=NULL;
}
BPOCR_PARAM Param={0};
- const char * strResult =BPOcrDoOcr(Handle,szImagePath,false,false,&Param);
- printf("%s",strResult);
+ BOOL bRet =BPOcrDoOcr(Handle,szImagePath,false,false,&Param);
+ if (bRet)
+ {
+ int nLen = BPOcrGetLen(Handle);
+ if (nLen > 0)
+ {
+ char* szInfo =(char* )malloc(nLen);
+ if (szInfo)
+ {
+ if (BPOcrGetResult(Handle, szInfo, nLen))
+ {
+ printf(szInfo);
+ }
+ }
+
+
+ }
+ }
if(Handle)
{
diff --git a/cpp/BaiPiaoOcrOnnx/src/CrnnNet.cpp b/cpp/BaiPiaoOcrOnnx/src/CrnnNet.cpp
index a3a910f..0f9eb14 100755
--- a/cpp/BaiPiaoOcrOnnx/src/CrnnNet.cpp
+++ b/cpp/BaiPiaoOcrOnnx/src/CrnnNet.cpp
@@ -75,11 +75,11 @@ TextLine CrnnNet::scoreToTextLine(const std::vector<float> &outputData, int h, i
float maxValue;
for (int i = 0; i < h; i++) {
- maxIndex = int(argmax(&outputData[i * w], &outputData[(i + 1) * w]));
- maxValue = float(*std::max_element(&outputData[i * w], &outputData[(i + 1) * w]));
+ maxIndex = int(argmax(&outputData[i * w], &outputData[(i+1) * w-1]));
+ maxValue = float(*std::max_element(&outputData[i * w], &outputData[(i + 1) * w-1]));
if (maxIndex > 0 && maxIndex < keySize && (!(i > 0 && maxIndex == lastIndex))) {
- scores.emplace_back(maxValue);
+ scores.push_back(maxValue);
strRes.append(keys[maxIndex]);
}
lastIndex = maxIndex;
diff --git a/include/baipiaoocr_api.h b/include/baipiaoocr_api.h
index 81b3ca4..6b86071 100755
--- a/include/baipiaoocr_api.h
+++ b/include/baipiaoocr_api.h
@@ -45,7 +45,11 @@ By default, nThreads should be the number of threads
*/
_QM_OCR_API BPHANDLE BPOcrInit(const char * szDetModel, const char * szClsModel, const char * szRecModel,const char *szKeyPath,int nThreads);
-_QM_OCR_API const char* BPOcrDoOcr(BPHANDLE handle, const char* szImgPath, BOOL bAutoParam,BOOL bLongPic, BPOCR_PARAM *pParam);
+_QM_OCR_API BOOL BPOcrDoOcr(BPHANDLE handle, const char* szImgPath, BOOL bAutoParam,BOOL bLongPic, BPOCR_PARAM *pParam);
+
+_QM_OCR_API int BPOcrGetLen(BPHANDLE handle);
+
+_QM_OCR_API BOOL BPOcrGetResult(BPHANDLE handle, char* szBuf, int nLen);
_QM_OCR_API void BPOcrDeinit(BPHANDLE handle);
diff --git a/include/onnxruntime/core/common/code_location.h b/include/onnxruntime/core/common/code_location.h
deleted file mode 100755
index ff6506c..0000000
--- a/include/onnxruntime/core/common/code_location.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <sstream>
-#include <string>
-#include <vector>
-
-namespace onnxruntime {
-/**
- CodeLocation captures information on where in the source code a message came from.
-*/
-struct CodeLocation {
- /**
- @param file_path Usually the value of __FILE__
- @param line Usually the value of __LINE__
- @param func Usually the value of __PRETTY_FUNCTION__ or __FUNCTION__
- */
- CodeLocation(const char* file_path, const int line, const char* func)
- : file_and_path{file_path}, line_num{line}, function{func} {
- }
-
- /**
- @param file_path Usually the value of __FILE__
- @param line Usually the value of __LINE__
- @param func Usually the value of __PRETTY_FUNCTION__ or __FUNCTION__
- @param stacktrace Stacktrace from source of message.
- */
- CodeLocation(const char* file_path, const int line, const char* func, const std::vector<std::string>& stacktrace)
- : file_and_path{file_path}, line_num{line}, function{func}, stacktrace(stacktrace) {
- }
-
- std::string FileNoPath() const {
- // assuming we always have work to do, so not trying to avoid creating a new string if
- // no path was removed.
- return file_and_path.substr(file_and_path.find_last_of("/\\") + 1);
- }
-
- enum Format {
- kFilename,
- kFilenameAndPath
- };
-
- std::string ToString(Format format = Format::kFilename) const {
- std::ostringstream out;
- out << (format == Format::kFilename ? FileNoPath() : file_and_path) << ":" << line_num << " " << function;
- return out.str();
- }
-
- const std::string file_and_path;
- const int line_num;
- const std::string function;
- const std::vector<std::string> stacktrace;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/common.h b/include/onnxruntime/core/common/common.h
deleted file mode 100755
index 2d9dc34..0000000
--- a/include/onnxruntime/core/common/common.h
+++ /dev/null
@@ -1,289 +0,0 @@
-/**
- * Copyright (c) 2016-present, Facebook, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// Portions Copyright (c) Microsoft Corporation
-
-#pragma once
-
-#include <algorithm>
-#include <cstring>
-#include <climits>
-#include <functional>
-#include <memory>
-#include <numeric>
-#include <set>
-#include <sstream>
-#include <string>
-#include <type_traits>
-#include <unordered_map>
-#include <vector>
-#include <chrono>
-
-#include "core/common/code_location.h"
-#include "core/common/exceptions.h"
-#include "core/common/make_string.h"
-#include "core/common/make_unique.h"
-#include "core/common/status.h"
-
-#ifdef USE_MIMALLOC_ARENA_ALLOCATOR
-#include <mimalloc.h>
-#endif
-
-#ifdef ORT_NO_EXCEPTIONS
-#include <iostream>
-#endif
-
-namespace onnxruntime {
-
-using TimePoint = std::chrono::high_resolution_clock::time_point;
-
-// Using statements for common classes that we refer to in ONNXRuntime very often.
-// TODO(Task:137) Remove 'using' statements from header files
-using common::Status;
-
-#ifdef _WIN32
-#define ORT_UNUSED_PARAMETER(x) (x)
-#else
-#define ORT_UNUSED_PARAMETER(x) (void)(x)
-#endif
-
-#ifndef ORT_HAVE_ATTRIBUTE
-#ifdef __has_attribute
-#define ORT_HAVE_ATTRIBUTE(x) __has_attribute(x)
-#else
-#define ORT_HAVE_ATTRIBUTE(x) 0
-#endif
-#endif
-
-// ORT_ATTRIBUTE_UNUSED
-//
-// Prevents the compiler from complaining about or optimizing away variables
-// that appear unused on Linux
-#if ORT_HAVE_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__))
-#undef ORT_ATTRIBUTE_UNUSED
-#define ORT_ATTRIBUTE_UNUSED __attribute__((__unused__))
-#else
-#define ORT_ATTRIBUTE_UNUSED
-#endif
-
-// macro to explicitly ignore the return value from a function call so Code Analysis doesn't complain
-#define ORT_IGNORE_RETURN_VALUE(fn) \
- static_cast<void>(fn)
-
-std::vector<std::string> GetStackTrace();
-// these is a helper function that gets defined by platform/Telemetry
-void LogRuntimeError(uint32_t session_id, const common::Status& status, const char* file,
- const char* function, uint32_t line);
-
-// __PRETTY_FUNCTION__ isn't a macro on gcc, so use a check for _MSC_VER
-// so we only define it as one for MSVC
-#if (_MSC_VER && !defined(__PRETTY_FUNCTION__))
-#define __PRETTY_FUNCTION__ __FUNCTION__
-#endif
-
-// Capture where a message is coming from. Use __FUNCTION__ rather than the much longer __PRETTY_FUNCTION__
-#define ORT_WHERE \
- ::onnxruntime::CodeLocation(__FILE__, __LINE__, __FUNCTION__)
-
-#define ORT_WHERE_WITH_STACK \
- ::onnxruntime::CodeLocation(__FILE__, __LINE__, __PRETTY_FUNCTION__, ::onnxruntime::GetStackTrace())
-
-#ifdef ORT_NO_EXCEPTIONS
-
-#define ORT_TRY if (true)
-#define ORT_CATCH(x) else if (false)
-#define ORT_RETHROW
-
-// In order to ignore the catch statement when a specific exception (not ... ) is caught and referred
-// in the body of the catch statements, it is necessary to wrap the body of the catch statement into
-// a lambda function. otherwise the exception referred will be undefined and cause build break
-#define ORT_HANDLE_EXCEPTION(func)
-
-// TODO, consider changing the output of the error message from std::cerr to logging when the
-// exceptions are disabled, since using std::cerr might increase binary size, and std::cerr output
-// might not be easily accesible on some systems such as mobile
-
-// Throw an exception with optional message.
-// NOTE: The arguments get streamed into a string via ostringstream::operator<<
-// DO NOT use a printf format string, as that will not work as you expect.
-#define ORT_THROW(...) \
- do { \
- std::cerr << ::onnxruntime::OnnxRuntimeException(ORT_WHERE_WITH_STACK, \
- ::onnxruntime::MakeString(__VA_ARGS__)) \
- .what() \
- << std::endl; \
- abort(); \
- } while (false)
-
-// Just in order to mark things as not implemented. Do not use in final code.
-#define ORT_NOT_IMPLEMENTED(...) \
- do { \
- std::cerr << ::onnxruntime::NotImplementedException(::onnxruntime::MakeString(__VA_ARGS__)) \
- .what() \
- << std::endl; \
- abort(); \
- } while (false)
-
-// Check condition.
-// NOTE: The arguments get streamed into a string via ostringstream::operator<<
-// DO NOT use a printf format string, as that will not work as you expect.
-#define ORT_ENFORCE(condition, ...) \
- do { \
- if (!(condition)) { \
- std::cerr << ::onnxruntime::OnnxRuntimeException(ORT_WHERE_WITH_STACK, #condition, \
- ::onnxruntime::MakeString(__VA_ARGS__)) \
- .what() \
- << std::endl; \
- abort(); \
- } \
- } while (false)
-
-#define ORT_THROW_EX(ex, ...) \
- do { \
- std::cerr << #ex << "(" << ::onnxruntime::MakeString(__VA_ARGS__) << ")" << std::endl; \
- abort(); \
- } while (false)
-
-#else
-
-#define ORT_TRY try
-#define ORT_CATCH(x) catch (x)
-#define ORT_RETHROW throw;
-
-#define ORT_HANDLE_EXCEPTION(func) func()
-
-// Throw an exception with optional message.
-// NOTE: The arguments get streamed into a string via ostringstream::operator<<
-// DO NOT use a printf format string, as that will not work as you expect.
-#define ORT_THROW(...) \
- throw ::onnxruntime::OnnxRuntimeException(ORT_WHERE_WITH_STACK, ::onnxruntime::MakeString(__VA_ARGS__))
-
-// Just in order to mark things as not implemented. Do not use in final code.
-#define ORT_NOT_IMPLEMENTED(...) \
- throw ::onnxruntime::NotImplementedException(::onnxruntime::MakeString(__VA_ARGS__))
-
-// Check condition.
-// NOTE: The arguments get streamed into a string via ostringstream::operator<<
-// DO NOT use a printf format string, as that will not work as you expect.
-#define ORT_ENFORCE(condition, ...) \
- if (!(condition)) \
- throw ::onnxruntime::OnnxRuntimeException(ORT_WHERE_WITH_STACK, #condition, \
- ::onnxruntime::MakeString(__VA_ARGS__))
-
-#define ORT_THROW_EX(ex, ...) \
- throw ex(__VA_ARGS__)
-
-#endif
-
-#define ORT_MAKE_STATUS(category, code, ...) \
- ::onnxruntime::common::Status(::onnxruntime::common::category, \
- ::onnxruntime::common::code, \
- ::onnxruntime::MakeString(__VA_ARGS__))
-
-// Check condition. if met, return status.
-#define ORT_RETURN_IF(condition, ...) \
- if (condition) { \
- return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, \
- "Satisfied, but should not be: " #condition "\n", \
- ORT_WHERE.ToString(), ::onnxruntime::MakeString(__VA_ARGS__)); \
- }
-
-// Check condition. if not met, return status.
-#define ORT_RETURN_IF_NOT(condition, ...) \
- if (!(condition)) { \
- return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Not satisfied: " #condition "\n", \
- ORT_WHERE.ToString(), ::onnxruntime::MakeString(__VA_ARGS__)); \
- }
-
-// Macros to disable the copy and/or move ctor and assignment methods
-// These are usually placed in the private: declarations for a class.
-
-#define ORT_DISALLOW_COPY(TypeName) TypeName(const TypeName&) = delete
-
-#define ORT_DISALLOW_ASSIGNMENT(TypeName) TypeName& operator=(const TypeName&) = delete
-
-#define ORT_DISALLOW_COPY_AND_ASSIGNMENT(TypeName) \
- ORT_DISALLOW_COPY(TypeName); \
- ORT_DISALLOW_ASSIGNMENT(TypeName)
-
-#define ORT_DISALLOW_MOVE(TypeName) \
- TypeName(TypeName&&) = delete; \
- TypeName& operator=(TypeName&&) = delete
-
-#define ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(TypeName) \
- ORT_DISALLOW_COPY_AND_ASSIGNMENT(TypeName); \
- ORT_DISALLOW_MOVE(TypeName)
-
-#define ORT_RETURN_IF_ERROR_SESSIONID(expr, session_id) \
- do { \
- auto _status = (expr); \
- if ((!_status.IsOK())) { \
- ::onnxruntime::LogRuntimeError(session_id, _status, __FILE__, __FUNCTION__, __LINE__); \
- return _status; \
- } \
- } while (0)
-
-#define ORT_RETURN_IF_ERROR_SESSIONID_(expr) ORT_RETURN_IF_ERROR_SESSIONID(expr, session_id_)
-#define ORT_RETURN_IF_ERROR(expr) ORT_RETURN_IF_ERROR_SESSIONID(expr, 0)
-
-#define ORT_THROW_IF_ERROR(expr) \
- do { \
- auto _status = (expr); \
- if ((!_status.IsOK())) { \
- ::onnxruntime::LogRuntimeError(0, _status, __FILE__, __FUNCTION__, __LINE__); \
- ORT_THROW(_status); \
- } \
- } while (0)
-
-// use this macro when cannot early return
-#define ORT_CHECK_AND_SET_RETVAL(expr) \
- do { \
- if (retval.IsOK()) { \
- retval = (expr); \
- } \
- } while (0)
-
-// C++ Core Guideline check suppression.
-#if defined(_MSC_VER) && !defined(__NVCC__)
-#define GSL_SUPPRESS(tag) [[gsl::suppress(tag)]]
-#else
-#define GSL_SUPPRESS(tag)
-#endif
-
-inline long long TimeDiffMicroSeconds(TimePoint start_time) {
- auto end_time = std::chrono::high_resolution_clock::now();
- return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
-}
-
-inline long long TimeDiffMicroSeconds(TimePoint start_time, TimePoint end_time) {
- return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
-}
-
-struct null_type {};
-inline std::string ToMBString(const std::string& s) { return s; }
-#ifdef _WIN32
-/**
- * Convert a wide character string into a narrow one, with local ANSI code page(like CP936)
- * DO NOT assume the result string is encoded in UTF-8
- */
-std::string ToMBString(const std::wstring& s);
-
-std::wstring ToWideString(const std::string& s);
-inline std::wstring ToWideString(const std::wstring& s) { return s; }
-#else
-inline std::string ToWideString(const std::string& s) { return s; }
-#endif
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/const_pointer_container.h b/include/onnxruntime/core/common/const_pointer_container.h
deleted file mode 100755
index 1d821ba..0000000
--- a/include/onnxruntime/core/common/const_pointer_container.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <type_traits>
-
-namespace onnxruntime {
-/**
- Container has T* entries. e.g. std::vector<T*>, and this class provides const access to those
- via iterators and direct access, as the standard behavior only makes the pointer constant,
- and not what is pointed too. i.e. you get a const pointer to T not a pointer to const T without this wrapper.
- See https://stackoverflow.com/questions/8017036/understanding-const-iterator-with-pointers
-*/
-template <typename Container>
-class ConstPointerContainer {
- public:
- using T = typename std::remove_pointer<typename Container::value_type>::type;
-
- class ConstIterator {
- public:
- using const_iterator = typename Container::const_iterator;
- using iterator_category = std::input_iterator_tag;
- using value_type = T*;
- using difference_type = std::ptrdiff_t;
- using pointer = T**;
- using reference = T*&;
-
- /** Construct iterator for container that will return const T* entries.*/
- explicit ConstIterator(const_iterator position) noexcept : current_{position}, item_{nullptr} {}
- ConstIterator(const ConstIterator& other) = default;
- ConstIterator& operator=(const ConstIterator& other) = default;
-
- bool operator==(const ConstIterator& other) const noexcept { return current_ == other.current_; }
- bool operator!=(const ConstIterator& other) const noexcept { return current_ != other.current_; }
-
- ConstIterator& operator++() {
- ++current_;
- return *this;
- }
-
- ConstIterator operator++(int) {
- ConstIterator tmp{*this};
- ++(*this);
- return tmp;
- }
-
- const T*& operator*() const {
- item_ = *current_;
- return item_;
- }
-
- const T** operator->() const { return &(operator*()); };
-
- private:
- const_iterator current_;
- mutable const T* item_;
- };
-
- /**
- Construct wrapper class that will provide const access to the pointers in a container of non-const pointers.
- @param data Container with non-const pointers. e.g. std::vector<T*>
- */
- explicit ConstPointerContainer(const Container& data) noexcept : data_(data) {}
-
- size_t size() const noexcept { return data_.size(); }
- bool empty() const noexcept { return data_.empty(); }
-
- ConstIterator cbegin() const noexcept { return ConstIterator(data_.cbegin()); }
- ConstIterator cend() const noexcept { return ConstIterator(data_.cend()); }
-
- ConstIterator begin() const noexcept { return ConstIterator(data_.cbegin()); }
- ConstIterator end() const noexcept { return ConstIterator(data_.cend()); }
-
- const T* operator[](size_t index) const { return data_[index]; }
-
- const T* at(size_t index) const {
- ORT_ENFORCE(index < data_.size());
- return data_[index];
- }
-
- private:
- const Container& data_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/denormal.h b/include/onnxruntime/core/common/denormal.h
deleted file mode 100755
index baac109..0000000
--- a/include/onnxruntime/core/common/denormal.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-
-// Set or unset flush-to-zero and denormal=as-zero if SSE3 instructions are supported.
-// Return true if SSE3 instruction is supported, otherwise return false.
-bool SetDenormalAsZero(bool on);
-
-#ifdef _OPENMP
-// Set flush-to-zero and denormal-as-zero on OpenMP threads when on is true.
-void InitializeWithDenormalAsZero(bool on);
-#endif
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/eigen_common_wrapper.h b/include/onnxruntime/core/common/eigen_common_wrapper.h
deleted file mode 100755
index fa15399..0000000
--- a/include/onnxruntime/core/common/eigen_common_wrapper.h
+++ /dev/null
@@ -1,41 +0,0 @@
-//-----------------------------------------------------------------------------
-//
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-//
-//-----------------------------------------------------------------------------
-#pragma once
-#include "onnxruntime_config.h"
-// build/external/eigen/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h:162:71:
-// error: ignoring attributes on template argument "Eigen::PacketType<const float, Eigen::DefaultDevice>::type {aka __vector(4) float}" [-Werror=ignored-attributes]
-#if defined(__GNUC__)
-#pragma GCC diagnostic push
-#if __GNUC__ >= 6
-#pragma GCC diagnostic ignored "-Wignored-attributes"
-#endif
-#pragma GCC diagnostic ignored "-Wunused-parameter"
-#ifdef HAS_DEPRECATED_COPY
-#pragma GCC diagnostic ignored "-Wdeprecated-copy"
-#endif
-#elif defined(_MSC_VER)
-// build\windows\debug\external\eigen3\unsupported\eigen\cxx11\src/Tensor/Tensor.h(76):
-// warning C4554: '&': check operator precedence for possible error; use parentheses to clarify precedence
-
-// unsupported\eigen\cxx11\src\Tensor\TensorUInt128.h(150,0): Warning C4245: 'initializing': conversion from '__int64'
-// to 'uint64_t', signed/unsigned mismatch
-#pragma warning(push)
-#pragma warning(disable : 4554)
-#pragma warning(disable : 4245)
-#pragma warning(disable : 4127)
-#pragma warning(disable : 4805)
-#pragma warning(disable : 6313)
-#pragma warning(disable : 6294)
-#endif
-
-#include "unsupported/Eigen/CXX11/Tensor"
-
-#if defined(__GNUC__)
-#pragma GCC diagnostic pop
-#elif defined(_MSC_VER)
-#pragma warning(pop)
-#endif
diff --git a/include/onnxruntime/core/common/exceptions.h b/include/onnxruntime/core/common/exceptions.h
deleted file mode 100755
index cbebc88..0000000
--- a/include/onnxruntime/core/common/exceptions.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <algorithm>
-#include <exception>
-#include <iterator>
-#include <stdexcept>
-#include <string>
-#include <vector>
-
-#include "core/common/common.h"
-#include "core/common/code_location.h"
-
-namespace onnxruntime {
-
-class NotImplementedException : public std::logic_error {
- public:
- explicit NotImplementedException(const char* _Message = "Function not yet implemented") noexcept : std::logic_error(_Message){};
- explicit NotImplementedException(const std::string& _Message = "Function not yet implemented") noexcept : std::logic_error(_Message){};
-};
-
-class TypeMismatchException : public std::logic_error {
- public:
- TypeMismatchException() noexcept : logic_error("Type mismatch"){};
-};
-
-class OnnxRuntimeException : public std::exception {
- public:
- OnnxRuntimeException(const CodeLocation& location, const std::string& msg) noexcept
- : OnnxRuntimeException(location, nullptr, msg) {
- }
-
- /**
- Create a new exception that captures the location it was thrown from.
- @param location Location in the source code the exception is being thrown from
- @param failed_condition Optional string containing the condition that failed.
- e.g. "tensor.Size() == input.Size()". May be nullptr.
- @param msg Message containing additional information about the exception cause.
- */
- OnnxRuntimeException(const CodeLocation& location, const char* failed_condition, const std::string& msg)
- : location_{location} {
- std::ostringstream ss;
-
- ss << location.ToString(CodeLocation::kFilenameAndPath); // output full path in case just the filename is ambiguous
- if (failed_condition != nullptr) {
- ss << " " << failed_condition << " was false.";
- }
-
- ss << " " << msg << "\n";
- if (!location.stacktrace.empty()) {
- ss << "Stacktrace:\n";
- // skip the first entry in the stacktrace as we have that information from location.ToString()
- std::copy(++location.stacktrace.begin(), location.stacktrace.end(), std::ostream_iterator<std::string>(ss, "\n"));
- }
-
- what_ = ss.str();
- }
-
- const char* what() const noexcept override {
- return what_.c_str();
- }
-
- private:
- const CodeLocation location_;
- const std::vector<std::string> stacktrace_;
- std::string what_;
-};
-
-} // namespace onnxruntime
\ No newline at end of file
diff --git a/include/onnxruntime/core/common/logging/capture.h b/include/onnxruntime/core/common/logging/capture.h
deleted file mode 100755
index 4f71bb3..0000000
--- a/include/onnxruntime/core/common/logging/capture.h
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <cstdarg>
-#include <gsl/gsl>
-#include "core/common/common.h"
-#include "core/common/code_location.h"
-#include "core/common/logging/severity.h"
-
-namespace onnxruntime {
-namespace logging {
-
-class Logger;
-enum class DataType;
-
-/**
- Class to capture the details of a log message.
-*/
-class Capture {
- public:
- /**
- Initializes a new instance of the Capture class.
- @param logger The logger.
- @param severity The severity.
- @param category The category.
- @param dataType Type of the data.
- @param location The file location the log message is coming from.
- */
- Capture(const Logger& logger, logging::Severity severity, const char* category,
- logging::DataType dataType, const CodeLocation& location)
- : logger_{&logger}, severity_{severity}, category_{category}, data_type_{dataType}, location_{location} {
- }
-
- /**
- The stream that can capture the message via operator<<.
- @returns Output stream.
- */
- std::ostream& Stream() noexcept {
- return stream_;
- }
-
-#ifdef _MSC_VER
-// add SAL annotation for printf format string. requires Code Analysis to run to validate usage.
-#define msvc_printf_check _Printf_format_string_
-#define __attribute__(x) // Disable for MSVC. Supported by GCC and CLang.
-#else
-#define msvc_printf_check
-#endif
-
- /**
- Captures a printf style log message.
- @param name="format">The printf format.
- @param name="">Arguments to the printf format if needed.
- @remarks
- A maximum of 2K of output will be captured currently.
- Non-static method, so 'this' is implicit first arg, and we use format(printf(2,3)
- */
- void CapturePrintf(msvc_printf_check const char* format, ...) __attribute__((format(printf, 2, 3)));
-
- /**
- Process a printf style log message.
- @param format The printf format.
- @param ... Arguments to the printf format if needed.
- @remarks
- A maximum of 2K of output will be captured currently.
- Note: As va_list is 'char *', we have to disambiguate this from CapturePrintf
- so that something like "One string: %s", "the string" does not consider "the string"
- to be the va_list.
- */
- void ProcessPrintf(msvc_printf_check const char* format, va_list args);
-
- logging::Severity Severity() const noexcept {
- return severity_;
- }
-
- char SeverityPrefix() const noexcept {
- // Carefully setup so severity_ is a valid index
- GSL_SUPPRESS(bounds .2) {
- return logging::SEVERITY_PREFIX[static_cast<int>(severity_)];
- }
- }
-
- const char* Category() const noexcept {
- return category_;
- }
-
- logging::DataType DataType() const noexcept {
- return data_type_;
- }
-
- const CodeLocation& Location() const noexcept {
- return location_;
- }
-
- std::string Message() const noexcept {
- return stream_.str();
- }
-
- ~Capture();
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Capture);
-
- const Logger* logger_;
- const logging::Severity severity_;
- const char* category_;
- const logging::DataType data_type_;
- const CodeLocation location_;
-
- std::ostringstream stream_;
-};
-} // namespace logging
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/logging/isink.h b/include/onnxruntime/core/common/logging/isink.h
deleted file mode 100755
index a67777d..0000000
--- a/include/onnxruntime/core/common/logging/isink.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <string>
-
-#include "core/common/logging/logging.h"
-
-namespace onnxruntime {
-namespace logging {
-class ISink {
- public:
- ISink() = default;
-
- /**
- Sends the message to the sink.
- @param timestamp The timestamp.
- @param logger_id The logger identifier.
- @param message The captured message.
- */
- void Send(const Timestamp& timestamp, const std::string& logger_id, const Capture& message) {
- SendImpl(timestamp, logger_id, message);
- }
-
- /**
- Sends a Profiling Event Record to the sink.
- @param Profiling Event Record
- */
- virtual void SendProfileEvent(profiling::EventRecord&) const {};
-
- virtual ~ISink() = default;
-
- private:
- // Make Code Analysis happy by disabling all for now. Enable as needed.
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ISink);
-
- virtual void SendImpl(const Timestamp& timestamp, const std::string& logger_id, const Capture& message) = 0;
-};
-} // namespace logging
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/logging/logging.h b/include/onnxruntime/core/common/logging/logging.h
deleted file mode 100755
index 96c07f0..0000000
--- a/include/onnxruntime/core/common/logging/logging.h
+++ /dev/null
@@ -1,347 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <atomic>
-#include <chrono>
-#include <climits>
-#include <map>
-#include <memory>
-#include <mutex>
-#include <string>
-
-#include "core/common/common.h"
-#include "core/common/logging/capture.h"
-#include "core/common/logging/severity.h"
-
-#include "core/common/logging/macros.h"
-
-/*
-
- Logging overview and expected usage:
-
- At program startup:
- * Create one or more ISink instances. If multiple, combine using composite_sink.
- * Create a LoggingManager instance with the sink/s with is_default_instance set to true
- * Only one instance should be created in this way, and it should remain valid for
- until the program no longer needs to produce log output.
-
- You can either use the static default Logger which LoggingManager will create when constructed
- via LoggingManager::DefaultLogger(), or separate Logger instances each with different log ids
- via LoggingManager::CreateLogger.
-
- The log id is passed to the ISink instance with the sink determining how the log id is used
- in the output.
-
- LoggingManager
- * creates the Logger instances used by the application
- * provides a static default logger instance
- * owns the log sink instance
- * applies checks on severity and output of user data
-
- The log macros create a Capture instance to capture the information to log.
- If the severity and/or user filtering settings would prevent logging, no evaluation
- of the log arguments will occur, so no performance cost beyond the severity and user
- filtering check.
-
- A sink can do further filter as needed.
-
-*/
-
-namespace onnxruntime {
-namespace profiling {
-
-enum EventCategory {
- SESSION_EVENT = 0,
- NODE_EVENT,
- EVENT_CATEGORY_MAX
-};
-
-/*
-Event descriptions for the above session events.
-*/
-static constexpr const char* event_categor_names_[EVENT_CATEGORY_MAX] = {
- "Session",
- "Node"};
-
-/*
-Timing record for all events.
-*/
-struct EventRecord {
- EventRecord(EventCategory category,
- int process_id,
- int thread_id,
- std::string event_name,
- long long time_stamp,
- long long duration,
- std::unordered_map<std::string, std::string>&& event_args) : cat(category),
- pid(process_id),
- tid(thread_id),
- name(std::move(event_name)),
- ts(time_stamp),
- dur(duration),
- args(event_args) {}
- EventCategory cat;
- int pid;
- int tid;
- std::string name;
- long long ts;
- long long dur;
- std::unordered_map<std::string, std::string> args;
-};
-} // namespace profiling
-
-namespace logging {
-
-using Timestamp = std::chrono::time_point<std::chrono::system_clock>;
-
-#ifndef NDEBUG
-ORT_ATTRIBUTE_UNUSED static bool vlog_enabled = true; // Set directly based on your needs.
-#else
-constexpr bool vlog_enabled = false; // no VLOG output
-#endif
-
-enum class DataType {
- SYSTEM = 0, ///< System data.
- USER = 1 ///< Contains potentially sensitive user data.
-};
-
-// Internal log categories.
-// Logging interface takes const char* so arbitrary values can also be used.
-struct Category {
- static const char* onnxruntime; ///< General output
- static const char* System; ///< Log output regarding interactions with the host system
- // TODO: What other high level categories are meaningful? Model? Optimizer? Execution?
-};
-
-class ISink;
-class Logger;
-class Capture;
-
-/// <summary>
-/// The logging manager.
-/// Owns the log sink and potentially provides a default Logger instance.
-/// Provides filtering based on a minimum LogSeverity level, and of messages with DataType::User if enabled.
-/// </summary>
-class LoggingManager final {
- public:
- enum InstanceType {
- Default, ///< Default instance of LoggingManager that should exist for the lifetime of the program
- Temporal ///< Temporal instance. CreateLogger(...) should be used, however DefaultLogger() will NOT be provided via this instance.
- };
-
- /**
- Initializes a new instance of the LoggingManager class.
- @param sink The sink to write to. Use CompositeSink if you need to write to multiple places.
- @param default_min_severity The default minimum severity. Messages with lower severity will be ignored unless
- overridden in CreateLogger.
- @param default_filter_user_data If set to true ignore messages with DataType::USER unless overridden in CreateLogger.
- @param instance_type If InstanceType::Default, this is the default instance of the LoggingManager
- and is expected to exist for the lifetime of the program.
- It creates and owns the default logger that calls to the static DefaultLogger method return.
- @param default_logger_id Logger Id to use for the default logger. nullptr/ignored if instance_type == Temporal.
- @param default_max_vlog_level Default maximum level for VLOG messages to be created unless overridden in CreateLogger.
- Requires a severity of kVERBOSE for VLOG messages to be logged.
- */
- LoggingManager(std::unique_ptr<ISink> sink, Severity default_min_severity, bool default_filter_user_data,
- InstanceType instance_type,
- const std::string* default_logger_id = nullptr,
- int default_max_vlog_level = -1);
-
- /**
- Creates a new logger instance which will use the provided logger_id and default severity and vlog levels.
- @param logger_id The log identifier.
- @returns A new Logger instance that the caller owns.
- */
- std::unique_ptr<Logger> CreateLogger(const std::string& logger_id);
-
- /**
- Creates a new logger instance which will use the provided logger_id, severity and vlog levels.
- @param logger_id The log identifier.
- @param min_severity The minimum severity. Requests to create messages with lower severity will be ignored.
- @param filter_user_data If set to true ignore messages with DataType::USER.
- @param max_vlog_level Maximum level for VLOG messages to be created.
- @returns A new Logger instance that the caller owns.
- */
- std::unique_ptr<Logger> CreateLogger(const std::string& logger_id,
- Severity min_severity, bool filter_user_data, int max_vlog_level = -1);
-
- /**
- Gets the default logger instance if set. Throws if no default logger is currently registered.
- @remarks
- Creating a LoggingManager instance with is_default_instance == true registers a default logger.
- Note that the default logger is only valid until the LoggerManager that registered it is destroyed.
- @returns The default logger if available.
- */
- static const Logger& DefaultLogger();
-
- /**
- Change the minimum severity level for log messages to be output by the default logger.
- @param severity The severity.
- */
- static void SetDefaultLoggerSeverity(Severity severity);
-
- /**
- Logs a FATAL level message and creates an exception that can be thrown with error information.
- @param category The log category.
- @param location The location the log message was generated.
- @param format_str The printf format string.
- @param ... The printf arguments.
- @returns A new Logger instance that the caller owns.
- */
- static std::exception LogFatalAndCreateException(const char* category,
- const CodeLocation& location,
- const char* format_str, ...);
-
- /**
- Logs the message using the provided logger id.
- @param logger_id The log identifier.
- @param message The log message.
- */
- void Log(const std::string& logger_id, const Capture& message) const;
-
- /**
- Sends a Profiling Event Record to the sink.
- @param Profiling Event Record
- */
- void SendProfileEvent(profiling::EventRecord& eventRecord) const;
- ~LoggingManager();
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(LoggingManager);
-
- Timestamp GetTimestamp() const noexcept;
- void CreateDefaultLogger(const std::string& logger_id);
-
- std::unique_ptr<ISink> sink_;
- const Severity default_min_severity_;
- const bool default_filter_user_data_;
- const int default_max_vlog_level_;
- bool owns_default_logger_;
-
- static Logger* s_default_logger_;
-
- struct Epochs {
- const std::chrono::time_point<std::chrono::high_resolution_clock> high_res;
- const std::chrono::time_point<std::chrono::system_clock> system;
- const std::chrono::minutes localtime_offset_from_utc;
- };
-
- static const Epochs& GetEpochs() noexcept;
-};
-
-/**
- Logger provides a per-instance log id. Everything else is passed back up to the LoggingManager
-*/
-class Logger {
- public:
- /**
- Initializes a new instance of the Logger class.
- @param loggingManager The logging manager.
- @param id The identifier for messages coming from this Logger.
- @param severity Minimum severity for messages to be created and logged.
- @param filter_user_data Should USER data be filtered from output.
- @param vlog_level Minimum level for VLOG messages to be created. Note that a severity of kVERBOSE must be provided
- for VLOG messages to be logged.
- */
- Logger(const LoggingManager& loggingManager, std::string id,
- Severity severity, bool filter_user_data, int vlog_level)
- : logging_manager_{&loggingManager},
- id_{id},
- min_severity_{severity},
- filter_user_data_{filter_user_data},
- max_vlog_level_{severity > Severity::kVERBOSE ? -1 : vlog_level} { // disable unless logging VLOG messages
- }
-
- /**
- Get the minimum severity level for log messages to be output.
- @returns The severity.
- */
- Severity GetSeverity() const noexcept { return min_severity_; }
-
- /**
- Change the minimum severity level for log messages to be output.
- @param severity The severity.
- */
- void SetSeverity(Severity severity) noexcept { min_severity_ = severity; }
-
- /**
- Check if output is enabled for the provided LogSeverity and DataType values.
- @param severity The severity.
- @param data_type Type of the data.
- @returns True if a message with these values will be logged.
- */
- bool OutputIsEnabled(Severity severity, DataType data_type) const noexcept {
- return (severity >= min_severity_ && (data_type != DataType::USER || !filter_user_data_));
- }
-
- /**
- Return the maximum VLOG level allowed.
- */
- int VLOGMaxLevel() const noexcept {
- return max_vlog_level_;
- }
-
- /**
- Logs the captured message.
- @param message The log message.
- */
- void Log(const Capture& message) const {
- logging_manager_->Log(id_, message);
- }
-
- /**
- Sends a Profiling Event Record to the sink.
- @param Profiling Event Record
- */
- void SendProfileEvent(profiling::EventRecord& eventRecord) const {
- logging_manager_->SendProfileEvent(eventRecord);
- }
-
- private:
- const LoggingManager* logging_manager_;
- const std::string id_;
- Severity min_severity_;
- const bool filter_user_data_;
- const int max_vlog_level_;
-};
-
-inline const Logger& LoggingManager::DefaultLogger() {
- if (s_default_logger_ == nullptr) {
- // fail early for attempted misuse. don't use logging macros as we have no logger.
- ORT_THROW("Attempt to use DefaultLogger but none has been registered.");
- }
-
- return *s_default_logger_;
-}
-
-inline void LoggingManager::SetDefaultLoggerSeverity(Severity severity) {
- if (s_default_logger_ == nullptr) {
- // fail early for attempted misuse. don't use logging macros as we have no logger.
- ORT_THROW("Attempt to use DefaultLogger but none has been registered.");
- }
-
- s_default_logger_->SetSeverity(severity);
-}
-
-inline Timestamp LoggingManager::GetTimestamp() const noexcept {
- static const Epochs& epochs = GetEpochs();
-
- const auto high_res_now = std::chrono::high_resolution_clock::now();
- return std::chrono::time_point_cast<std::chrono::system_clock::duration>(
- epochs.system + (high_res_now - epochs.high_res) + epochs.localtime_offset_from_utc);
-}
-
-/**
- Return the current thread id.
-*/
-unsigned int GetThreadId();
-
-/**
- Return the current process id.
-*/
-unsigned int GetProcessId();
-
-} // namespace logging
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/logging/macros.h b/include/onnxruntime/core/common/logging/macros.h
deleted file mode 100755
index 570bc14..0000000
--- a/include/onnxruntime/core/common/logging/macros.h
+++ /dev/null
@@ -1,209 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-// NOTE: Don't include this file directly. Include logging.h
-
-#define CREATE_MESSAGE(logger, severity, category, datatype) \
- ::onnxruntime::logging::Capture(logger, ::onnxruntime::logging::Severity::k##severity, category, datatype, ORT_WHERE)
-
-/*
- Both printf and stream style logging are supported.
- Not that printf currently has a 2K limit to the message size.
-
- LOGS_* macros are for stream style
- LOGF_* macros are for printf style
-
- The Message class captures the log input, and pushes it through the logger in its destructor.
-
- Use the *FATAL* macros if you want a Severity::kFatal message to also throw.
-
- There are a few variants to minimize the length of the macro name required in the calling code.
- They are optimized so the shortest names are for the (expected) most common usage. This can be
- tweaked if needed.
-
- Explicit logger vs LoggingManager::DefaulLogger()
- Default is for a logger instance to be explicitly passed in.
- The logger instance provides an identifier so that log messages from different runs can be separated.
-
- Variants with DEFAULT in the macro name use the default logger provided by logging manager. This is
- static so accessible from any code, provided a LoggingManager instance created with InstanceType::Default
- exists somewhere. See logging.h for further explanation of the expected setup.
-
- DataType
- Default uses DataType::SYSTEM.
-
- Variants with USER in the macro name use DataType::USER. This is data that could be PII, and may need to
- be filtered from output. LoggingManager applies this filtering.
-
- Category
- Default category is ::onnxruntime::Logging::Category::onnxruntime.
-
- If you wish to provide a different category, use variants with CATEGORY in the macro name
-
-*/
-
-// Logging with explicit category
-
-// iostream style logging. Capture log info in Message, and push to the logger in ~Message.
-#define LOGS_CATEGORY(logger, severity, category) \
- if ((logger).OutputIsEnabled(::onnxruntime::logging::Severity::k##severity, ::onnxruntime::logging::DataType::SYSTEM)) \
- CREATE_MESSAGE(logger, severity, category, ::onnxruntime::logging::DataType::SYSTEM).Stream()
-
-#define LOGS_USER_CATEGORY(logger, severity, category) \
- if ((logger).OutputIsEnabled(::onnxruntime::logging::Severity::k##severity, ::onnxruntime::logging::DataType::USER)) \
- CREATE_MESSAGE(logger, severity, category, ::onnxruntime::logging::DataType::USER).Stream()
-
- // printf style logging. Capture log info in Message, and push to the logger in ~Message.
-#define LOGF_CATEGORY(logger, severity, category, format_str, ...) \
- if ((logger).OutputIsEnabled(::onnxruntime::logging::Severity::k##severity, ::onnxruntime::logging::DataType::SYSTEM)) \
- CREATE_MESSAGE(logger, severity, category, ::onnxruntime::logging::DataType::SYSTEM).CapturePrintf(format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_CATEGORY(logger, severity, category, format_str, ...) \
- if ((logger).OutputIsEnabled(::onnxruntime::logging::Severity::k##severity, ::onnxruntime::logging::DataType::USER)) \
- CREATE_MESSAGE(logger, severity, category, ::onnxruntime::logging::DataType::USER).CapturePrintf(format_str, ##__VA_ARGS__)
-
- // Logging with category of "onnxruntime"
-
-#define LOGS(logger, severity) \
- LOGS_CATEGORY(logger, severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGS_USER(logger, severity) \
- LOGS_USER_CATEGORY(logger, severity, ::onnxruntime::logging::Category::onnxruntime)
-
- // printf style logging. Capture log info in Message, and push to the logger in ~Message.
-#define LOGF(logger, severity, format_str, ...) \
- LOGF_CATEGORY(logger, severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER(logger, severity, format_str, ...) \
- LOGF_USER_CATEGORY(logger, severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
- /*
-
- Macros that use the default logger.
- A LoggingManager instance must be currently valid for the default logger to be available.
-
- */
-
- // Logging with explicit category
-
-#define LOGS_DEFAULT_CATEGORY(severity, category) \
- LOGS_CATEGORY(::onnxruntime::logging::LoggingManager::DefaultLogger(), severity, category)
-
-#define LOGS_USER_DEFAULT_CATEGORY(severity, category) \
- LOGS_USER_CATEGORY(::onnxruntime::logging::LoggingManager::DefaultLogger(), severity, category)
-
-#define LOGF_DEFAULT_CATEGORY(severity, category, format_str, ...) \
- LOGF_CATEGORY(::onnxruntime::logging::LoggingManager::DefaultLogger(), severity, category, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_DEFAULT_CATEGORY(severity, category, format_str, ...) \
- LOGF_USER_CATEGORY(::onnxruntime::logging::LoggingManager::DefaultLogger(), severity, category, format_str, ##__VA_ARGS__)
-
-// Logging with category of "onnxruntime"
-
-#define LOGS_DEFAULT(severity) \
- LOGS_DEFAULT_CATEGORY(severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGS_USER_DEFAULT(severity) \
- LOGS_USER_DEFAULT_CATEGORY(severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGF_DEFAULT(severity, format_str, ...) \
- LOGF_DEFAULT_CATEGORY(severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_DEFAULT(severity, format_str, ...) \
- LOGF_USER_DEFAULT_CATEGORY(severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
- /*
-
- Conditional logging
-
- */
-
- // Logging with explicit category
-
-#define LOGS_CATEGORY_IF(boolean_expression, logger, severity, category) \
- if ((boolean_expression) == true) LOGS_CATEGORY(logger, severity, category)
-
-#define LOGS_DEFAULT_CATEGORY_IF(boolean_expression, severity, category) \
- if ((boolean_expression) == true) LOGS_DEFAULT_CATEGORY(severity, category)
-
-#define LOGS_USER_CATEGORY_IF(boolean_expression, logger, severity, category) \
- if ((boolean_expression) == true) LOGS_USER_CATEGORY(logger, severity, category)
-
-#define LOGS_USER_DEFAULT_CATEGORY_IF(boolean_expression, severity, category) \
- if ((boolean_expression) == true) LOGS_USER_DEFAULT_CATEGORY(severity, category)
-
-#define LOGF_CATEGORY_IF(boolean_expression, logger, severity, category, format_str, ...) \
- if ((boolean_expression) == true) LOGF_CATEGORY(logger, severity, category, format_str, ##__VA_ARGS__)
-
-#define LOGF_DEFAULT_CATEGORY_IF(boolean_expression, severity, category, format_str, ...) \
- if ((boolean_expression) == true) LOGF_DEFAULT_CATEGORY(severity, category, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_CATEGORY_IF(boolean_expression, logger, severity, category, format_str, ...) \
- if ((boolean_expression) == true) LOGF_USER_CATEGORY(logger, severity, category, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_DEFAULT_CATEGORY_IF(boolean_expression, severity, category, format_str, ...) \
- if ((boolean_expression) == true) LOGF_USER_DEFAULT_CATEGORY(severity, category, format_str, ##__VA_ARGS__)
-
- // Logging with category of "onnxruntime"
-
-#define LOGS_IF(boolean_expression, logger, severity) \
- LOGS_CATEGORY_IF(boolean_expression, logger, severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGS_DEFAULT_IF(boolean_expression, severity) \
- LOGS_DEFAULT_CATEGORY_IF(boolean_expression, severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGS_USER_IF(boolean_expression, logger, severity) \
- LOGS_USER_CATEGORY_IF(boolean_expression, logger, severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGS_USER_DEFAULT_IF(boolean_expression, severity) \
- LOGS_USER_DEFAULT_CATEGORY_IF(boolean_expression, severity, ::onnxruntime::logging::Category::onnxruntime)
-
-#define LOGF_IF(boolean_expression, logger, severity, format_str, ...) \
- LOGF_CATEGORY_IF(boolean_expression, logger, severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
-#define LOGF_DEFAULT_IF(boolean_expression, severity, format_str, ...) \
- LOGF_DEFAULT_CATEGORY_IF(boolean_expression, severity, ::onnxruntime::logging::Category::onnxruntime, format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_IF(boolean_expression, logger, severity, format_str, ...) \
- LOGF_USER_CATEGORY_IF(boolean_expression, logger, severity, ::onnxruntime::logging::Category::onnxruntime, \
- format_str, ##__VA_ARGS__)
-
-#define LOGF_USER_DEFAULT_IF(boolean_expression, severity, format_str, ...) \
- LOGF_USER_DEFAULT_CATEGORY_IF(boolean_expression, severity, ::onnxruntime::logging::Category::onnxruntime, \
- format_str, ##__VA_ARGS__)
-
-/*
-
- Debug verbose logging of caller provided level.
- Disabled in Release builds.
- Use the _USER variants for VLOG statements involving user data that may need to be filtered.
-*/
-#define VLOGS(logger, level) \
- if (::onnxruntime::logging::vlog_enabled && level <= (logger).VLOGMaxLevel()) \
- LOGS_CATEGORY(logger, VERBOSE, "VLOG" #level)
-
-#define VLOGS_USER(logger, level) \
- if (::onnxruntime::logging::vlog_enabled && level <= (logger).VLOGMaxLevel()) \
- LOGS_USER_CATEGORY(logger, VERBOSE, "VLOG" #level)
-
-#define VLOGF(logger, level, format_str, ...) \
- if (::onnxruntime::logging::vlog_enabled && level <= (logger).VLOGMaxLevel()) \
- LOGF_CATEGORY(logger, VERBOSE, "VLOG" #level, format_str, ##__VA_ARGS__)
-
-#define VLOGF_USER(logger, level, format_str, ...) \
- if (::onnxruntime::logging::vlog_enabled && level <= (logger).VLOGMaxLevel()) \
- LOGF_USER_CATEGORY(logger, VERBOSE, "VLOG" #level, format_str, ##__VA_ARGS__)
-
- // Default logger variants
-#define VLOGS_DEFAULT(level) \
- VLOGS(::onnxruntime::logging::LoggingManager::DefaultLogger(), level)
-
-#define VLOGS_USER_DEFAULT(level) \
- VLOGS_USER(::onnxruntime::logging::LoggingManager::DefaultLogger(), level)
-
-#define VLOGF_DEFAULT(level, format_str, ...) \
- VLOGF(::onnxruntime::logging::LoggingManager::DefaultLogger(), level, format_str, ##__VA_ARGS__)
-
-#define VLOGF_USER_DEFAULT(level, format_str, ...) \
- VLOGF_USER(::onnxruntime::logging::LoggingManager::DefaultLogger(), level, format_str, ##__VA_ARGS__)
diff --git a/include/onnxruntime/core/common/logging/severity.h b/include/onnxruntime/core/common/logging/severity.h
deleted file mode 100755
index e43f192..0000000
--- a/include/onnxruntime/core/common/logging/severity.h
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-namespace logging {
-// mild violation of naming convention. the 'k' lets us use token concatenation in the macro
-// ::onnxruntime::Logging::Severity::k##severity. It's not legal to have ::onnxruntime::Logging::Severity::##severity
-// the uppercase makes the LOG macro usage look as expected for passing an enum value as it will be LOGS(logger, ERROR)
-enum class Severity {
- kVERBOSE = 0,
- kINFO = 1,
- kWARNING = 2,
- kERROR = 3,
- kFATAL = 4
-};
-
-constexpr const char* SEVERITY_PREFIX = "VIWEF";
-
-} // namespace logging
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/make_string.h b/include/onnxruntime/core/common/make_string.h
deleted file mode 100755
index a6e421a..0000000
--- a/include/onnxruntime/core/common/make_string.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * Copyright (c) 2016-present, Facebook, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-// Portions Copyright (c) Microsoft Corporation
-
-#pragma once
-
-#include <locale>
-#include <sstream>
-
-namespace onnxruntime {
-
-namespace detail {
-inline void MakeStringImpl(std::ostringstream& /*ss*/) noexcept {
-}
-
-template <typename T>
-inline void MakeStringImpl(std::ostringstream& ss, const T& t) noexcept {
- ss << t;
-}
-
-template <typename T, typename... Args>
-inline void MakeStringImpl(std::ostringstream& ss, const T& t, const Args&... args) noexcept {
- MakeStringImpl(ss, t);
- MakeStringImpl(ss, args...);
-}
-} // namespace detail
-
-/**
- * Makes a string by concatenating string representations of the arguments.
- * This version uses the current locale.
- */
-template <typename... Args>
-std::string MakeString(const Args&... args) {
- std::ostringstream ss;
- detail::MakeStringImpl(ss, args...);
- return ss.str();
-}
-
-/**
- * Makes a string by concatenating string representations of the arguments.
- * This version uses std::locale::classic().
- */
-template <typename... Args>
-std::string MakeStringWithClassicLocale(const Args&... args) {
- std::ostringstream ss;
- ss.imbue(std::locale::classic());
- detail::MakeStringImpl(ss, args...);
- return ss.str();
-}
-
-// MakeString versions for already-a-string types.
-
-inline std::string MakeString(const std::string& str) {
- return str;
-}
-
-inline std::string MakeString(const char* cstr) {
- return cstr;
-}
-
-inline std::string MakeStringWithClassicLocale(const std::string& str) {
- return str;
-}
-
-inline std::string MakeStringWithClassicLocale(const char* cstr) {
- return cstr;
-}
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/make_unique.h b/include/onnxruntime/core/common/make_unique.h
deleted file mode 100755
index b401f0d..0000000
--- a/include/onnxruntime/core/common/make_unique.h
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2017 The Abseil Authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// https://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// -----------------------------------------------------------------------------
-// File: make_unique.h
-// -----------------------------------------------------------------------------
-//
-// This header file contains utility functions for managing the creation and
-// conversion of smart pointers. This file is an extension to the C++
-// standard <memory> library header file.
-/* Modifications Copyright (c) Microsoft. */
-
-#pragma once
-
-#include <cstddef>
-#include <limits>
-#include <memory>
-#include <new>
-#include <type_traits>
-#include <utility>
-
-namespace onnxruntime {
-
-template <typename T>
-using remove_extent_t = typename std::remove_extent<T>::type;
-
-namespace memory_internal {
-
-// Traits to select proper overload and return type for `absl::make_unique<>`.
-template <typename T>
-struct MakeUniqueResult {
- using scalar = std::unique_ptr<T>;
-};
-template <typename T>
-struct MakeUniqueResult<T[]> {
- using array = std::unique_ptr<T[]>;
-};
-template <typename T, size_t N>
-struct MakeUniqueResult<T[N]> {
- using invalid = void;
-};
-
-} // namespace memory_internal
-
-// gcc 4.8 has __cplusplus at 201301 but doesn't define make_unique. Other
-// supported compilers either just define __cplusplus as 201103 but have
-// make_unique (msvc), or have make_unique whenever __cplusplus > 201103 (clang)
-#if (__cplusplus > 201103L || defined(_MSC_VER)) && \
- !(defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 8)
-using std::make_unique;
-#else
-// -----------------------------------------------------------------------------
-// Function Template: make_unique<T>()
-// -----------------------------------------------------------------------------
-//
-// Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries
-// during the construction process. `absl::make_unique<>` also avoids redundant
-// type declarations, by avoiding the need to explicitly use the `new` operator.
-//
-// This implementation of `absl::make_unique<>` is designed for C++11 code and
-// will be replaced in C++14 by the equivalent `std::make_unique<>` abstraction.
-// `absl::make_unique<>` is designed to be 100% compatible with
-// `std::make_unique<>` so that the eventual migration will involve a simple
-// rename operation.
-//
-// For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic,
-// see Herb Sutter's explanation on
-// (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/].
-// (In general, reviewers should treat `new T(a,b)` with scrutiny.)
-//
-// Example usage:
-//
-// auto p = make_unique<X>(args...); // 'p' is a std::unique_ptr<X>
-// auto pa = make_unique<X[]>(5); // 'pa' is a std::unique_ptr<X[]>
-//
-// Three overloads of `absl::make_unique` are required:
-//
-// - For non-array T:
-//
-// Allocates a T with `new T(std::forward<Args> args...)`,
-// forwarding all `args` to T's constructor.
-// Returns a `std::unique_ptr<T>` owning that object.
-//
-// - For an array of unknown bounds T[]:
-//
-// `absl::make_unique<>` will allocate an array T of type U[] with
-// `new U[n]()` and return a `std::unique_ptr<U[]>` owning that array.
-//
-// Note that 'U[n]()' is different from 'U[n]', and elements will be
-// value-initialized. Note as well that `std::unique_ptr` will perform its
-// own destruction of the array elements upon leaving scope, even though
-// the array [] does not have a default destructor.
-//
-// NOTE: an array of unknown bounds T[] may still be (and often will be)
-// initialized to have a size, and will still use this overload. E.g:
-//
-// auto my_array = absl::make_unique<int[]>(10);
-//
-// - For an array of known bounds T[N]:
-//
-// `absl::make_unique<>` is deleted (like with `std::make_unique<>`) as
-// this overload is not useful.
-//
-// NOTE: an array of known bounds T[N] is not considered a useful
-// construction, and may cause undefined behavior in templates. E.g:
-//
-// auto my_array = absl::make_unique<int[10]>();
-//
-// In those cases, of course, you can still use the overload above and
-// simply initialize it to its desired size:
-//
-// auto my_array = absl::make_unique<int[]>(10);
-
-// `absl::make_unique` overload for non-array types.
-template <typename T, typename... Args>
-typename memory_internal::MakeUniqueResult<T>::scalar make_unique(
- Args&&... args) {
- return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
-}
-
-// `absl::make_unique` overload for an array T[] of unknown bounds.
-// The array allocation needs to use the `new T[size]` form and cannot take
-// element constructor arguments. The `std::unique_ptr` will manage destructing
-// these array elements.
-template <typename T>
-typename memory_internal::MakeUniqueResult<T>::array make_unique(size_t n) {
- return std::unique_ptr<T>(new typename onnxruntime::remove_extent_t<T>[n]());
-}
-
-// `absl::make_unique` overload for an array T[N] of known bounds.
-// This construction will be rejected.
-template <typename T, typename... Args>
-typename memory_internal::MakeUniqueResult<T>::invalid make_unique(
- Args&&... /* args */) = delete;
-#endif
-
-}
\ No newline at end of file
diff --git a/include/onnxruntime/core/common/optional.h b/include/onnxruntime/core/common/optional.h
deleted file mode 100755
index ab32cf6..0000000
--- a/include/onnxruntime/core/common/optional.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <nonstd/optional.hpp>
-
-namespace onnxruntime {
-
-using nonstd::optional;
-
-#ifndef ORT_NO_EXCEPTIONS
-using nonstd::bad_optional_access;
-#endif
-
-using nonstd::nullopt;
-using nonstd::nullopt_t;
-
-using nonstd::in_place;
-using nonstd::in_place_t;
-
-using nonstd::make_optional;
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/parse_string.h b/include/onnxruntime/core/common/parse_string.h
deleted file mode 100755
index 1429859..0000000
--- a/include/onnxruntime/core/common/parse_string.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <locale>
-#include <sstream>
-#include <type_traits>
-
-#include "core/common/common.h"
-
-namespace onnxruntime {
-
-/**
- * Tries to parse a value from an entire string.
- */
-template <typename T>
-bool TryParseStringWithClassicLocale(const std::string& str, T& value) {
- if (std::is_integral<T>::value && std::is_unsigned<T>::value) {
- // if T is unsigned integral type, reject negative values which will wrap
- if (!str.empty() && str[0] == '-') {
- return false;
- }
- }
-
- // don't allow leading whitespace
- if (!str.empty() && std::isspace(str[0], std::locale::classic())) {
- return false;
- }
-
- std::istringstream is{str};
- is.imbue(std::locale::classic());
- T parsed_value{};
-
- const bool parse_successful =
- is >> parsed_value &&
- is.get() == std::istringstream::traits_type::eof(); // don't allow trailing characters
- if (!parse_successful) {
- return false;
- }
-
- value = std::move(parsed_value);
- return true;
-}
-
-inline bool TryParseStringWithClassicLocale(const std::string& str, std::string& value) {
- value = str;
- return true;
-}
-
-inline bool TryParseStringWithClassicLocale(const std::string& str, bool& value) {
- if (str == "0" || str == "False" || str == "false") {
- value = false;
- return true;
- }
-
- if (str == "1" || str == "True" || str == "true") {
- value = true;
- return true;
- }
-
- return false;
-}
-
-/**
- * Parses a value from an entire string.
- */
-template <typename T>
-Status ParseStringWithClassicLocale(const std::string& s, T& value) {
- ORT_RETURN_IF_NOT(TryParseStringWithClassicLocale(s, value), "Failed to parse value: \"", value, "\"");
- return Status::OK();
-}
-
-/**
- * Parses a value from an entire string.
- */
-template <typename T>
-T ParseStringWithClassicLocale(const std::string& s) {
- T value{};
- ORT_THROW_IF_ERROR(ParseStringWithClassicLocale(s, value));
- return value;
-}
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/spin_pause.h b/include/onnxruntime/core/common/spin_pause.h
deleted file mode 100755
index 49b71e5..0000000
--- a/include/onnxruntime/core/common/spin_pause.h
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#if defined(_M_AMD64)
-#include <intrin.h>
-#endif
-
-#if defined(__x86_64__)
-#include <xmmintrin.h>
-#endif
-
-namespace onnxruntime {
-
-namespace concurrency {
-
-// Intrinsic to use in spin-loops
-
-inline void SpinPause() {
-#if defined(_M_AMD64) || defined(__x86_64__)
- _mm_pause();
-#endif
-}
-
-} // namespace concurrency
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/common/status.h b/include/onnxruntime/core/common/status.h
deleted file mode 100755
index c107655..0000000
--- a/include/onnxruntime/core/common/status.h
+++ /dev/null
@@ -1,191 +0,0 @@
-/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-==============================================================================*/
-// Modifications Copyright (c) Microsoft.
-
-#pragma once
-
-#include <memory>
-#include <ostream>
-#include <string>
-#ifdef _WIN32
-#include <winerror.h>
-#endif
-
-namespace onnxruntime {
-namespace common {
-
-enum StatusCategory {
- NONE = 0,
- SYSTEM = 1,
- ONNXRUNTIME = 2,
-};
-
-/**
- Error code for ONNXRuntime.
-*/
-enum StatusCode {
- OK = 0,
- FAIL = 1,
- INVALID_ARGUMENT = 2,
- NO_SUCHFILE = 3,
- NO_MODEL = 4,
- ENGINE_ERROR = 5,
- RUNTIME_EXCEPTION = 6,
- INVALID_PROTOBUF = 7,
- MODEL_LOADED = 8,
- NOT_IMPLEMENTED = 9,
- INVALID_GRAPH = 10,
- EP_FAIL = 11
-};
-
-inline const char* StatusCodeToString(StatusCode status) noexcept {
- switch (status) {
- case StatusCode::OK:
- return "SUCCESS";
- case StatusCode::FAIL:
- return "FAIL";
- case StatusCode::INVALID_ARGUMENT:
- return "INVALID_ARGUMENT";
- case StatusCode::NO_SUCHFILE:
- return "NO_SUCHFILE";
- case StatusCode::NO_MODEL:
- return "NO_MODEL";
- case StatusCode::ENGINE_ERROR:
- return "ENGINE_ERROR";
- case StatusCode::RUNTIME_EXCEPTION:
- return "RUNTIME_EXCEPTION";
- case StatusCode::INVALID_PROTOBUF:
- return "INVALID_PROTOBUF";
- case StatusCode::MODEL_LOADED:
- return "MODEL_LOADED";
- case StatusCode::NOT_IMPLEMENTED:
- return "NOT_IMPLEMENTED";
- case StatusCode::INVALID_GRAPH:
- return "INVALID_GRAPH";
- case StatusCode::EP_FAIL:
- return "EP_FAIL";
- default:
- return "GENERAL ERROR";
- }
-}
-
-#ifdef _WIN32
-inline HRESULT StatusCodeToHRESULT(StatusCode status) noexcept {
- switch (status)
- {
- case StatusCode::OK:
- return S_OK;
- case StatusCode::FAIL:
- return E_FAIL;
- case StatusCode::INVALID_ARGUMENT:
- return E_INVALIDARG;
- case StatusCode::NO_SUCHFILE:
- return __HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
- case StatusCode::NO_MODEL:
- return __HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
- case StatusCode::ENGINE_ERROR:
- return E_FAIL;
- case StatusCode::RUNTIME_EXCEPTION:
- return E_FAIL;
- case StatusCode::INVALID_PROTOBUF:
- return __HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
- case StatusCode::MODEL_LOADED:
- return __HRESULT_FROM_WIN32(ERROR_INTERNAL_ERROR);
- case StatusCode::NOT_IMPLEMENTED:
- return E_NOTIMPL;
- case StatusCode::INVALID_GRAPH:
- return __HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
- case StatusCode::EP_FAIL:
- return __HRESULT_FROM_WIN32(ERROR_INTERNAL_ERROR);
- default:
- return E_FAIL;
- }
-}
-#endif
-
-class Status {
- public:
- Status() noexcept = default;
-
- Status(StatusCategory category, int code, const std::string& msg);
-
- Status(StatusCategory category, int code, const char* msg);
-
- Status(StatusCategory category, int code);
-
- Status(const Status& other)
- : state_((other.state_ == nullptr) ? nullptr : new State(*other.state_)) {}
-
- Status& operator=(const Status& other) {
- if (state_ != other.state_) {
- if (other.state_ == nullptr) {
- state_.reset();
- } else {
- state_.reset(new State(*other.state_));
- }
- }
- return *this;
- }
-
- Status(Status&&) = default;
- Status& operator=(Status&&) = default;
- ~Status() = default;
-
- bool IsOK() const {
- return (state_ == nullptr);
- }
-
- int Code() const noexcept;
-
- StatusCategory Category() const noexcept;
-
- const std::string& ErrorMessage() const noexcept;
-
- std::string ToString() const;
-
- bool operator==(const Status& other) const {
- return (this->state_ == other.state_) || (ToString() == other.ToString());
- }
-
- bool operator!=(const Status& other) const {
- return !(*this == other);
- }
-
- static Status OK() {
- return Status();
- }
-
- private:
- static const std::string& EmptyString() noexcept;
-
- struct State {
- State(StatusCategory cat0, int code0, const std::string& msg0)
- : category(cat0), code(code0), msg(msg0) {}
-
- State(StatusCategory cat0, int code0, const char* msg0)
- : category(cat0), code(code0), msg(msg0) {}
-
- const StatusCategory category;
- const int code;
- const std::string msg;
- };
-
- // As long as Code() is OK, state_ == nullptr.
- std::unique_ptr<State> state_;
-};
-
-inline std::ostream& operator<<(std::ostream& out, const Status& status) {
- return out << status.ToString();
-}
-
-} // namespace common
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/alloc_kind.h b/include/onnxruntime/core/framework/alloc_kind.h
deleted file mode 100755
index 4534d08..0000000
--- a/include/onnxruntime/core/framework/alloc_kind.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#include <iosfwd>
-
-namespace onnxruntime {
-// The ml-Values fall into the following categories with respect to their
-// memory management:
-// - inference inputs: owned (allocated and freed) by caller, and is by
-// default read-only by the runtime.
-// - inference outputs: allocated by runtime, ownership transferred to
-// caller. TODO: Make sure this semantics is clear in InferenceSession API.
-// - weights (constant tensors): can be allocated once (statically), and
-// reused by all inference calls within an InferenceSession.
-// - tensor values: The lifetimes of these tensor-values are statically
-// determined, which is used for memory reuse/sharing optimizations. The
-// runtime allocates/frees these values at the right time (as determined
-// by the static allocation plan). Note that this is simplified since we
-// do not try to optimize for "slice" like ops, where we may be able to
-// conditionally reuse memory/data in some cases but not others.
-// Generalizing this is future work.
-
-enum class AllocKind {
- kNotSet = -1,
- kAllocate = 0,
- kReuse = 1,
- kPreExisting = 2,
- kAllocateStatically = 3,
- kAllocateOutput = 4,
- kShare = 5
-};
-
-std::ostream& operator<<(std::ostream& out, AllocKind alloc_kind);
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/allocator.h b/include/onnxruntime/core/framework/allocator.h
deleted file mode 100755
index 1059c39..0000000
--- a/include/onnxruntime/core/framework/allocator.h
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/common.h"
-#include "core/framework/fence.h"
-#include "core/session/onnxruntime_c_api.h"
-#include "ortdevice.h"
-#include "ortmemoryinfo.h"
-
-// This configures the arena based allocator used by ORT
-// See docs/C_API.md for details on what these mean and how to choose these values
-struct OrtArenaCfg {
- size_t max_mem; // use 0 to allow ORT to choose the default
- int arena_extend_strategy; // use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested
- int initial_chunk_size_bytes; // use -1 to allow ORT to choose the default
- int max_dead_bytes_per_chunk; // use -1 to allow ORT to choose the default
-};
-
-namespace onnxruntime {
-constexpr const char* CPU = "Cpu";
-constexpr const char* CUDA = "Cuda";
-constexpr const char* CUDA_PINNED = "CudaPinned";
-// TODO: Unify the allocator for CUDA and Tensorrt
-constexpr const char* TRT = "Tensorrt";
-constexpr const char* TRT_PINNED = "TensorrtPinned";
-constexpr const char* MIGRAPHX = "MIGraphX";
-constexpr const char* MIGRAPHX_PINNED = "MIGraphXPinned";
-
-constexpr size_t kAllocAlignment = 256;
-
-// forward declaration
-class SessionState;
-
-template <typename T>
-using IAllocatorUniquePtr = std::unique_ptr<T, std::function<void(T*)>>;
-
-class IAllocator {
- public:
- IAllocator(const OrtMemoryInfo& info) : memory_info_(info) {}
- virtual ~IAllocator() = default;
- /**
- @remarks Use SafeInt when calculating the size of memory to allocate using Alloc.
- */
- virtual void* Alloc(size_t size) = 0;
- virtual void Free(void* p) = 0;
- const OrtMemoryInfo& Info() const { return memory_info_; };
-
- /**
- optional CreateFence interface, as provider like DML has its own fence
- */
- virtual FencePtr CreateFence(const SessionState* /*unused*/) { return nullptr; }
-
- static bool CalcMemSizeForArray(size_t nmemb, size_t size, size_t* out) noexcept {
- return CalcMemSizeForArrayWithAlignment(nmemb, size, 0, out);
- }
-
- /**
- * Calculate the memory size for an array. The size is bounds checked using SafeInt.
- * \tparam alignment must be power of 2
- * \param nmemb Number of members or elements in the array
- * \param size Size of each element
- * \param out Total size required after any alignment is applied
- * \return true, successful. false, overflow
- */
- static bool CalcMemSizeForArrayWithAlignment(size_t nmemb, size_t size, size_t alignment, size_t* out) noexcept ORT_MUST_USE_RESULT;
-
- /**
- * https://cwe.mitre.org/data/definitions/190.html
- * \param alignment must be power of 2
- * \param nmemb Number of members or elements in the array
- * \param size Size of each element
- * \param out Total size required after any alignment is applied
- * \return true, successful. false, overflow
- * \remarks This was the original API and was implemented in the header. Replaced with the above version
- * implemented in the .cc file so that the SafeInt dependency is internal.
- */
- template <size_t alignment>
- static bool CalcMemSizeForArrayWithAlignment(size_t nmemb, size_t size, size_t* out) noexcept ORT_MUST_USE_RESULT;
-
- /**
- * allocate memory for an array which has nmemb items of data, each size bytes long
- */
- void* AllocArray(size_t nmemb, size_t size) {
- size_t len;
- if (!CalcMemSizeForArray(nmemb, size, &len))
- return nullptr;
- return Alloc(len);
- }
-
- /**
- * allocate memory for an array which has nmemb items of data, each size bytes long
- */
- template <size_t alignment>
- void* AllocArrayWithAlignment(size_t nmemb, size_t size) {
- size_t len;
- if (!CalcMemSizeForArrayWithAlignment(nmemb, size, alignment, &len))
- return nullptr;
- return Alloc(len);
- }
-
- /**
- Create a std::unique_ptr that is allocated and freed by the provided IAllocator.
- @param allocator The allocator.
- @param count_or_bytes The exact bytes to allocate if T is void, otherwise the number of elements to allocate.
- @returns std::unique_ptr with allocated memory and deleter.
- */
- template <typename T>
- static IAllocatorUniquePtr<T> MakeUniquePtr(std::shared_ptr<IAllocator> allocator, size_t count_or_bytes) {
- if (allocator == nullptr) return nullptr;
- // for now limit to fundamental types. we could support others, but to do so either we or the caller
- // needs to call the dtor for the objects, for buffers allocated on device we don't have destructor
- //static_assert(std::is_fundamental<T>::value, "Fundamental type required as no destructors are called.");
-
- size_t alloc_size = count_or_bytes;
-
- // if T is not void, 'count_or_bytes' == number of items so allow for that
- if (!std::is_void<T>::value) {
- // sizeof(void) isn't valid, but the compiler isn't smart enough to ignore that this line isn't
- // reachable if T is void. use std::conditional to 'use' void* in the sizeof call
- if (!CalcMemSizeForArray(count_or_bytes,
- sizeof(typename std::conditional<std::is_void<T>::value, void*, T>::type),
- &alloc_size)) return nullptr;
- }
-
- return IAllocatorUniquePtr<T>{
- static_cast<T*>(allocator->Alloc(alloc_size)), // allocate
- [=](T* ptr) { // capture 'allocator' by value so it's always valid
- allocator->Free(ptr);
- }};
- }
-
- private:
- OrtMemoryInfo memory_info_;
-};
-
-template <size_t alignment>
-bool IAllocator::CalcMemSizeForArrayWithAlignment(size_t nmemb, size_t size, size_t* out) noexcept {
- return CalcMemSizeForArrayWithAlignment(nmemb, size, alignment, out);
-}
-
-class CPUAllocator : public IAllocator {
- public:
- explicit CPUAllocator(const OrtMemoryInfo& memory_info) : IAllocator(memory_info) {}
-
- CPUAllocator() : IAllocator(OrtMemoryInfo(CPU, OrtAllocatorType::OrtDeviceAllocator)) {}
-
- void* Alloc(size_t size) override;
- void Free(void* p) override;
-};
-
-#if defined(USE_MIMALLOC_ARENA_ALLOCATOR)
-class MiMallocAllocator : public IAllocator {
- public:
- explicit MiMallocAllocator(const OrtMemoryInfo& memory_info) : IAllocator(memory_info) {}
- MiMallocAllocator() : IAllocator(OrtMemoryInfo(CPU, OrtAllocatorType::OrtDeviceAllocator)) {}
-
- void* Alloc(size_t size) override;
- void Free(void* p) override;
-};
-
-#endif
-
-#if defined(USE_MIMALLOC_ARENA_ALLOCATOR)
-using TAllocator = MiMallocAllocator;
-#else
-using TAllocator = CPUAllocator;
-#endif
-
-using AllocatorPtr = std::shared_ptr<IAllocator>;
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/customregistry.h b/include/onnxruntime/core/framework/customregistry.h
deleted file mode 100755
index aafe5a5..0000000
--- a/include/onnxruntime/core/framework/customregistry.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/status.h"
-#include "core/common/logging/logging.h"
-#include "core/graph/schema_registry.h"
-#include "core/framework/op_kernel.h"
-#include "core/framework/kernel_def_builder.h"
-#include "core/framework/kernel_registry.h"
-
-namespace onnxruntime {
-
-/**
- Represents a registry that contains both custom kernels and custom schemas.
-*/
-class CustomRegistry final {
- public:
- CustomRegistry() :
- kernel_registry_(std::make_shared<KernelRegistry>()),
- opschema_registry_(std::make_shared<onnxruntime::OnnxRuntimeOpSchemaRegistry>()) {}
-
- /**
- * Register a kernel definition together with kernel factory method to this session.
- * If any conflict happened between registered kernel def and built-in kernel def,
- * registered kernel will have higher priority.
- * Call this before invoking Initialize().
- * @return OK if success.
- */
- common::Status RegisterCustomKernel(KernelDefBuilder& kernel_def_builder, const KernelCreateFn& kernel_creator);
-
- common::Status RegisterCustomKernel(KernelCreateInfo&);
-
- common::Status RegisterOpSet(std::vector<ONNX_NAMESPACE::OpSchema>& schemas, const std::string& domain,
- int baseline_opset_version, int opset_version);
-
- const std::shared_ptr<KernelRegistry>& GetKernelRegistry();
-
- const std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry>& GetOpschemaRegistry();
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(CustomRegistry);
- std::shared_ptr<KernelRegistry> kernel_registry_;
- std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> opschema_registry_;
-
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/data_types.h b/include/onnxruntime/core/framework/data_types.h
deleted file mode 100755
index 6d4633a..0000000
--- a/include/onnxruntime/core/framework/data_types.h
+++ /dev/null
@@ -1,1039 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <cstdint>
-#include <cstring>
-#include <string>
-#include <type_traits>
-#include <map>
-#include <unordered_map>
-
-#include "core/common/common.h"
-#include "core/common/exceptions.h"
-#include "core/framework/endian.h"
-#include "core/graph/onnx_protobuf.h"
-
-struct OrtValue;
-
-namespace ONNX_NAMESPACE {
-class TypeProto;
-} // namespace ONNX_NAMESPACE
-
-namespace onnxruntime {
-/// Predefined registered types
-
-#if !defined(DISABLE_ML_OPS)
-//maps (only used by ML ops)
-using MapStringToString = std::map<std::string, std::string>;
-using MapStringToInt64 = std::map<std::string, int64_t>;
-using MapStringToFloat = std::map<std::string, float>;
-using MapStringToDouble = std::map<std::string, double>;
-using MapInt64ToString = std::map<int64_t, std::string>;
-using MapInt64ToInt64 = std::map<int64_t, int64_t>;
-using MapInt64ToFloat = std::map<int64_t, float>;
-using MapInt64ToDouble = std::map<int64_t, double>;
-#endif
-
-//vectors/sequences
-#if !defined(DISABLE_ML_OPS)
-using VectorMapStringToFloat = std::vector<MapStringToFloat>;
-using VectorMapInt64ToFloat = std::vector<MapInt64ToFloat>;
-#endif
-using VectorString = std::vector<std::string>;
-using VectorInt64 = std::vector<int64_t>;
-
-class DataTypeImpl;
-class TensorTypeBase;
-class SparseTensorTypeBase;
-class SequenceTensorTypeBase;
-class NonTensorTypeBase;
-class PrimitiveDataTypeBase;
-
-// MLFloat16
-union MLFloat16 {
- uint16_t val;
-
- explicit MLFloat16(uint16_t x) : val(x) {}
- MLFloat16() : val(0) {}
-
- // Taken from https://stackoverflow.com/a/60047308/12627730
- float AsFloat(uint32_t x) const {
- float out = 0.0f;
- std::memcpy(&out, &x, sizeof(x));
- return out;
- }
-
- // Taken from https://stackoverflow.com/a/60047308/12627730
- uint32_t AsUint(float x) const {
- uint32_t out = 0;
- std::memcpy(&out, &x, sizeof(x));
- return out;
- }
-
- float HalfToFloat(const uint16_t x) const {
- uint16_t half = x;
- if (endian::native == endian::big) {
- // Taken from https://stackoverflow.com/a/2182184/12627730
- half = (x >> 8) | (x << 8);
- }
-
- // Taken from https://stackoverflow.com/a/60047308/12627730
- // IEEE-754 16-bit floating-point format (without infinity): 1-5-10, exp-15, +-131008.0, +-6.1035156E-5,
- // +-5.9604645E-8, 3.311 digits
- const uint32_t e = (half & 0x7C00) >> 10; // exponent
- const uint32_t m = (half & 0x03FF) << 13; // mantissa
- // evil log2 bit hack to count leading zeros in denormalized format
- const uint32_t v = AsUint(static_cast<float>(m)) >> 23;
- uint32_t full = (half & 0x8000) << 16 | (e != 0) * ((e + 112) << 23 | m) |
- ((e == 0) & (m != 0)) * ((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000)); // sign : normalized : denormalized
-
- if (endian::native == endian::big) {
- // Taken from https://stackoverflow.com/a/2182184/12627730
- full = ((full >> 24) & 0xff) | // move byte 3 to byte 0
- ((full << 8) & 0xff0000) | // move byte 1 to byte 2
- ((full >> 8) & 0xff00) | // move byte 2 to byte 1
- ((full << 24) & 0xff000000); // byte 0 to byte 3
- }
-
- return AsFloat(full);
- }
-
- operator float() const {
- return HalfToFloat(val);
- }
-};
-
-inline bool operator==(const MLFloat16& left, const MLFloat16& right) {
- return left.val == right.val;
-}
-
-inline bool operator!=(const MLFloat16& left, const MLFloat16& right) {
- return left.val != right.val;
-}
-
-inline bool operator<(const MLFloat16& left, const MLFloat16& right) {
- return left.val < right.val;
-}
-
-//BFloat16
-struct BFloat16 {
- uint16_t val{0};
- explicit BFloat16() = default;
- explicit BFloat16(uint16_t v) : val(v) {}
- explicit BFloat16(float v) {
- if (endian::native == endian::little) {
- std::memcpy(&val, reinterpret_cast<char*>(&v) + sizeof(uint16_t), sizeof(uint16_t));
- } else {
- std::memcpy(&val, &v, sizeof(uint16_t));
- }
- }
-
- float ToFloat() const {
- float result;
- char* const first = reinterpret_cast<char*>(&result);
- char* const second = first + sizeof(uint16_t);
- if (endian::native == endian::little) {
- std::memset(first, 0, sizeof(uint16_t));
- std::memcpy(second, &val, sizeof(uint16_t));
- } else {
- std::memcpy(first, &val, sizeof(uint16_t));
- std::memset(second, 0, sizeof(uint16_t));
- }
- return result;
- }
-
- operator float() const {
- return ToFloat();
- }
-};
-
-inline void BFloat16ToFloat(const BFloat16* blf, float* flt, size_t size) {
- auto src = blf;
- auto d = flt;
- for (; size != 0; ++src, ++d, --size) {
- *d = src->ToFloat();
- }
-}
-
-inline void FloatToBFloat16(const float* flt, BFloat16* blf, size_t size) {
- auto src = flt;
- auto d = blf;
- for (; size != 0; ++src, ++d, --size) {
- new (d) BFloat16(*src);
- }
-}
-
-inline bool operator==(const BFloat16& left, const BFloat16& right) {
- return left.val == right.val;
-}
-
-inline bool operator!=(const BFloat16& left, const BFloat16& right) {
- return left.val != right.val;
-}
-
-inline bool operator<(const BFloat16& left, const BFloat16& right) {
- return left.val < right.val;
-}
-
-// DataTypeImpl pointer as unique DataTypeImpl identifier.
-using MLDataType = const DataTypeImpl*;
-// be used with class MLValue
-using DeleteFunc = void (*)(void*);
-using CreateFunc = void* (*)();
-
-/**
- * \brief Base class for MLDataType
- *
- */
-class DataTypeImpl {
- public:
- virtual ~DataTypeImpl() = default;
-
- /**
- * \brief this API will be used to check type compatibility at runtime
- *
- * \param type_proto a TypeProto instance that is constructed for a specific type
- * will be checked against a TypeProto instance contained within a corresponding
- * MLDataType instance.
- */
- virtual bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const = 0;
-
- virtual size_t Size() const = 0;
-
- virtual DeleteFunc GetDeleteFunc() const = 0;
-
- /**
- * \brief Retrieves an instance of TypeProto for
- * a given MLDataType
- * \returns optional TypeProto. Only ONNX types
- has type proto, non-ONNX types will return nullptr.
- */
- virtual const ONNX_NAMESPACE::TypeProto* GetTypeProto() const = 0;
-
- virtual bool IsTensorType() const {
- return false;
- }
-
- virtual bool IsTensorSequenceType() const {
- return false;
- }
-
- virtual bool IsSparseTensorType() const {
- return false;
- }
-
- // Returns this if this is of tensor-type and null otherwise
- virtual const TensorTypeBase* AsTensorType() const {
- return nullptr;
- }
-
- virtual const SequenceTensorTypeBase* AsSequenceTensorBase() const {
- return nullptr;
- }
-
- // Returns this if this is of sparse-tensor-type and null otherwise
- virtual const SparseTensorTypeBase* AsSparseTensorType() const {
- return nullptr;
- }
-
- virtual const NonTensorTypeBase* AsNonTensorTypeBase() const {
- return nullptr;
- }
-
- // Returns this if this is one of the primitive data types (specialization of PrimitiveDataTypeBase)
- // and null otherwise
- virtual const PrimitiveDataTypeBase* AsPrimitiveDataType() const {
- return nullptr;
- }
-
- // Return the type meta that we are using in the runtime.
- template <typename T>
- static MLDataType GetType();
-
- // Return the types for a concrete tensor type, like Tensor_Float
- template <typename elemT>
- static MLDataType GetTensorType();
-
- template <typename elemT>
- static MLDataType GetSequenceTensorType();
-
- // Return the MLDataType for a concrete sparse tensor type.
- template <typename elemT>
- static MLDataType GetSparseTensorType();
-
- /**
- * Convert an ONNX TypeProto to onnxruntime DataTypeImpl.
- * However, this conversion is lossy. Don't try to use 'this->GetTypeProto()' converting it back.
- * Even though GetTypeProto() will not have the original information, it will still have enough to correctly
- * map to MLDataType.
- * \param proto
- */
- static MLDataType TypeFromProto(const ONNX_NAMESPACE::TypeProto& proto);
-
- static const TensorTypeBase* TensorTypeFromONNXEnum(int type);
- static const SparseTensorTypeBase* SparseTensorTypeFromONNXEnum(int type);
- static const NonTensorTypeBase* SequenceTensorTypeFromONNXEnum(int type);
-
- static const char* ToString(MLDataType type);
- static std::vector<std::string> ToString(const std::vector<MLDataType>& types);
- // Registers ONNX_NAMESPACE::DataType (internalized string) with
- // MLDataType. DataType is produced by internalizing an instance of
- // TypeProto contained within MLDataType
- static void RegisterDataType(MLDataType);
- static MLDataType GetDataType(const std::string&);
-
- static const std::vector<MLDataType>& AllTensorTypes();
- static const std::vector<MLDataType>& AllFixedSizeTensorTypes();
- static const std::vector<MLDataType>& AllSequenceTensorTypes();
- static const std::vector<MLDataType>& AllFixedSizeSequenceTensorTypes();
- static const std::vector<MLDataType>& AllNumericTensorTypes();
- static const std::vector<MLDataType>& AllIEEEFloatTensorTypes();
- static const std::vector<MLDataType>& AllFixedSizeTensorExceptHalfTypes();
- static const std::vector<MLDataType>& AllIEEEFloatTensorExceptHalfTypes();
- static const std::vector<MLDataType>& AllTensorAndSequenceTensorTypes();
- static const std::vector<MLDataType>& AllFixedSizeTensorAndSequenceTensorTypes();
-};
-
-std::ostream& operator<<(std::ostream& out, MLDataType data_type);
-
-/*
- * Type registration helpers
- */
-namespace data_types_internal {
-/// TensorType helpers
-///
-
-template <typename T>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType();
-
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<float>() {
- return ONNX_NAMESPACE::TensorProto_DataType_FLOAT;
-}
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<uint8_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT8;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<int8_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT8;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<uint16_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<int16_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<int32_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT32;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<int64_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT64;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<std::string>() {
- return ONNX_NAMESPACE::TensorProto_DataType_STRING;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<bool>() {
- return ONNX_NAMESPACE::TensorProto_DataType_BOOL;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<MLFloat16>() {
- return ONNX_NAMESPACE::TensorProto_DataType_FLOAT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<double>() {
- return ONNX_NAMESPACE::TensorProto_DataType_DOUBLE;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<uint32_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT32;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<uint64_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT64;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorDataType<BFloat16>() {
- return ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16;
-}
-
-// There is a specialization only for one
-// type argument.
-template <typename... Types>
-struct TensorElementTypeSetter {
- static void SetTensorElementType(ONNX_NAMESPACE::TypeProto&);
- static void SetMapKeyType(ONNX_NAMESPACE::TypeProto&);
- static int32_t GetElementType();
-};
-
-/// Is a given type on the list of types?
-/// Accepts a list of types and the first argument is the type
-/// We are checking if it is listed among those that follow
-template <typename T, typename... Types>
-struct IsAnyOf;
-
-/// Two types remaining, end of the list
-template <typename T, typename Tail>
-struct IsAnyOf<T, Tail> : public std::is_same<T, Tail> {
-};
-
-template <typename T, typename H, typename... Tail>
-struct IsAnyOf<T, H, Tail...> {
- static constexpr bool value = (std::is_same<T, H>::value ||
- IsAnyOf<T, Tail...>::value);
-};
-
-/// Tells if the specified type is one of fundamental types
-/// that can be contained within a tensor.
-/// We do not have raw fundamental types, rather a subset
-/// of fundamental types is contained within tensors.
-template <typename T>
-struct IsTensorContainedType : public IsAnyOf<T, float, uint8_t, int8_t, uint16_t, int16_t,
- int32_t, int64_t, std::string, bool, MLFloat16,
- double, uint32_t, uint64_t, BFloat16> {
-};
-
-/// Use "IsSparseTensorContainedType<T>::value" to test if a type T
-/// is permitted as the element-type of a sparse-tensor.
-
-template <typename T>
-struct IsSparseTensorContainedType : public IsAnyOf<T, float, uint8_t, int8_t, uint16_t, int16_t,
- int32_t, int64_t, bool, MLFloat16,
- double, uint32_t, uint64_t, BFloat16> {
-};
-
-/// This template's Get() returns a corresponding MLDataType
-/// It dispatches the call to either GetTensorType<>() or
-/// GetType<>()
-template <typename T, bool TensorContainedType>
-struct GetMLDataType;
-
-template <typename T>
-struct GetMLDataType<T, true> {
- static MLDataType Get() {
- return DataTypeImpl::GetTensorType<T>();
- }
-};
-
-template <typename T>
-struct GetMLDataType<T, false> {
- static MLDataType Get() {
- return DataTypeImpl::GetType<T>();
- }
-};
-
-#if !defined(DISABLE_ML_OPS)
-/// MapTypes helper API
-/// K should always be one of the primitive data types
-/// V can be either a primitive type (in which case it is a tensor)
-/// or other preregistered types
-
-void CopyMutableMapValue(const ONNX_NAMESPACE::TypeProto&,
- ONNX_NAMESPACE::TypeProto&);
-
-template <typename K, typename V>
-struct SetMapTypes {
- static void Set(ONNX_NAMESPACE::TypeProto& proto) {
- TensorElementTypeSetter<K>::SetMapKeyType(proto);
- MLDataType dt = GetMLDataType<V, IsTensorContainedType<V>::value>::Get();
- const auto* value_proto = dt->GetTypeProto();
-#ifdef ORT_NO_RTTI
- ORT_ENFORCE(value_proto != nullptr, "expected a registered ONNX type");
-#else
- ORT_ENFORCE(value_proto != nullptr, typeid(V).name(),
- " expected to be a registered ONNX type");
-#endif
- CopyMutableMapValue(*value_proto, proto);
- }
-};
-#endif
-
-/// Sequence helpers
-///
-// Element type is a primitive type so we set it to a tensor<elemT>
-void CopyMutableSeqElement(const ONNX_NAMESPACE::TypeProto&,
- ONNX_NAMESPACE::TypeProto&);
-
-template <typename T>
-struct SetSequenceType {
- static void Set(ONNX_NAMESPACE::TypeProto& proto) {
- MLDataType dt = GetMLDataType<T, IsTensorContainedType<T>::value>::Get();
- const auto* elem_proto = dt->GetTypeProto();
-#ifdef ORT_NO_RTTI
- ORT_ENFORCE(elem_proto != nullptr, "expected a registered ONNX type");
-#else
- ORT_ENFORCE(elem_proto != nullptr, typeid(T).name(),
- " expected to be a registered ONNX type");
-#endif
- CopyMutableSeqElement(*elem_proto, proto);
- }
-};
-
-/// OpaqueTypes helpers
-///
-void AssignOpaqueDomainName(const char* domain, const char* name,
- ONNX_NAMESPACE::TypeProto& proto);
-
-} // namespace data_types_internal
-
-/// All tensors base
-class TensorTypeBase : public DataTypeImpl {
- public:
- static MLDataType Type();
-
- /// We first compare type_proto pointers and then
- /// if they do not match try to account for the case
- /// where TypeProto was created ad-hoc and not queried from MLDataType
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override;
-
- bool IsTensorType() const override {
- return true;
- }
-
- const TensorTypeBase* AsTensorType() const override {
- return this;
- }
-
- size_t Size() const override;
-
- DeleteFunc GetDeleteFunc() const override;
-
- const ONNX_NAMESPACE::TypeProto* GetTypeProto() const override;
-
- virtual MLDataType GetElementType() const {
- // should never reach here.
- ORT_NOT_IMPLEMENTED(__FUNCTION__, " is not implemented");
- }
-
- TensorTypeBase(const TensorTypeBase&) = delete;
- TensorTypeBase& operator=(const TensorTypeBase&) = delete;
-
- protected:
- ONNX_NAMESPACE::TypeProto& mutable_type_proto();
-
- TensorTypeBase();
- ~TensorTypeBase() override;
-
- private:
- struct Impl;
- Impl* impl_;
-};
-
-/**
- * \brief Tensor type. This type does not have a C++ type associated with
- * it at registration time except the element type. One of the types mentioned
- * above at IsTensorContainedType<> list is acceptable.
- *
- * \details
- * Usage:
- * ORT_REGISTER_TENSOR(ELEMENT_TYPE)
- * Currently all of the Tensors irrespective of the dimensions are mapped to Tensor<type>
- * type. IsCompatible() currently ignores shape.
- */
-
-template <typename elemT>
-class TensorType : public TensorTypeBase {
- public:
- static_assert(data_types_internal::IsTensorContainedType<elemT>::value,
- "Requires one of the tensor fundamental types");
-
- static MLDataType Type();
-
- /// Tensors only can contain basic data types
- /// that have been previously registered with ONNXRuntime
- MLDataType GetElementType() const override {
- return DataTypeImpl::GetType<elemT>();
- }
-
- private:
- TensorType() {
- using namespace data_types_internal;
- TensorElementTypeSetter<elemT>::SetTensorElementType(this->mutable_type_proto());
- }
-};
-
-/// Common base-class for all sparse-tensors (with different element types).
-class SparseTensorTypeBase : public DataTypeImpl {
- public:
- static MLDataType Type();
-
- bool IsSparseTensorType() const override {
- return true;
- }
-
- const SparseTensorTypeBase* AsSparseTensorType() const override {
- return this;
- }
-
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override;
-
- size_t Size() const override;
-
- DeleteFunc GetDeleteFunc() const override;
-
- const ONNX_NAMESPACE::TypeProto* GetTypeProto() const override;
-
- virtual MLDataType GetElementType() const {
- // should never reach here.
- ORT_NOT_IMPLEMENTED(__FUNCTION__, " is not implemented");
- }
-
- SparseTensorTypeBase(const SparseTensorTypeBase&) = delete;
- SparseTensorTypeBase& operator=(const SparseTensorTypeBase&) = delete;
-
- protected:
- ONNX_NAMESPACE::TypeProto& mutable_type_proto();
-
- SparseTensorTypeBase();
- ~SparseTensorTypeBase() override;
-
- private:
- struct Impl;
- Impl* impl_;
-};
-
-template <typename elemT>
-class SparseTensorType : public SparseTensorTypeBase {
- public:
- static_assert(data_types_internal::IsSparseTensorContainedType<elemT>::value,
- "Requires one of the sparse-tensor fundamental types");
-
- static MLDataType Type();
-
- /// Return a MLDataType representing the element-type
- MLDataType GetElementType() const override {
- return DataTypeImpl::GetType<elemT>();
- }
-
- private:
- SparseTensorType() {
- using namespace data_types_internal;
- TensorElementTypeSetter<elemT>::SetSparseTensorElementType(mutable_type_proto());
- }
-};
-
-/**
- * \brief Provide a specialization for your C++ Non-tensor type
- * so your implementation FromDataTypeContainer/ToDataTypeContainer
- * functions correctly. Otherwise you get a default implementation
- * which may not be what you need/want.
- *
- * This class is used to create OrtValue, fetch data from OrtValue via
- * C/C++ APIs
- */
-template <class T>
-struct NonTensorTypeConverter {
- static void FromContainer(MLDataType /*dtype*/, const void* /*data*/, size_t /*data_size*/, OrtValue& /*output*/) {
- ORT_THROW("Not implemented");
- }
- static void ToContainer(const OrtValue& /*input*/, size_t /*data_size*/, void* /*data*/) {
- ORT_THROW("Not implemented");
- }
-};
-
-/**
- * \brief Base type for all non-tensors, maps, sequences and opaques
- */
-class NonTensorTypeBase : public DataTypeImpl {
- public:
- size_t Size() const override = 0;
-
- DeleteFunc GetDeleteFunc() const override = 0;
-
- virtual CreateFunc GetCreateFunc() const = 0;
-
- const ONNX_NAMESPACE::TypeProto* GetTypeProto() const override;
-
- const NonTensorTypeBase* AsNonTensorTypeBase() const override {
- return this;
- }
-
- // \brief Override for Non-tensor types to initialize non-tensor CPP
- // data representation from data. The caller of the interface
- // should have a shared definition of the data which is used to initialize
- // CPP data representation. This is used from C API.
- //
- // \param data - pointer to a data container structure non_tensor type specific
- // \param data_size - size of the data container structure, used for rudimentary checks
- // \param output - reference to a default constructed non-tensor type
- // \returns OrtValue
- // \throw if there is an error
- virtual void FromDataContainer(const void* data, size_t data_size, OrtValue& output) const;
-
- // \brief Override for Non-tensor types to fetch data from the internal CPP data representation
- // The caller of the interface should have a shared definition of the data which is used to initialize
- // CPP data representation. This is used from C API.
- //
- // \param input - OrtValue containing data
- // \param data_size - size of the structure that is being passed for receiving data, used for
- // validation
- // \param data - pointer to receiving data structure
- virtual void ToDataContainer(const OrtValue& input, size_t data_size, void* data) const;
-
- NonTensorTypeBase(const NonTensorTypeBase&) = delete;
- NonTensorTypeBase& operator=(const NonTensorTypeBase&) = delete;
-
- protected:
- NonTensorTypeBase();
- ~NonTensorTypeBase() override;
-
- ONNX_NAMESPACE::TypeProto& mutable_type_proto();
-
- bool IsMapCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const;
-
- bool IsSequenceCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const;
-
- bool IsOpaqueCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const;
-
- private:
- struct Impl;
- Impl* impl_;
-};
-
-// This is where T is the actual CPPRuntimeType
-template <typename T>
-class NonTensorType : public NonTensorTypeBase {
- private:
- static void Delete(void* p) {
- delete static_cast<T*>(p);
- }
-
- public:
- size_t Size() const override {
- return sizeof(T);
- }
-
- DeleteFunc GetDeleteFunc() const override {
- return &Delete;
- }
-
- CreateFunc GetCreateFunc() const override {
- return []() -> void* { return new T(); };
- }
-
- protected:
- NonTensorType() = default;
-};
-
-#if !defined(DISABLE_ML_OPS)
-/**
- * \brief MapType. Use this type to register
- * mapping types.
- *
- * \param T - cpp type that you wish to register as runtime MapType
- *
- * \details Usage: ORT_REGISTER_MAP(C++Type)
- * The type is required to have mapped_type and
- * key_type defined
- */
-template <typename CPPType>
-class MapType : public NonTensorType<CPPType> {
- public:
- static_assert(data_types_internal::IsTensorContainedType<typename CPPType::key_type>::value,
- "Requires one of the tensor fundamental types as key");
-
- static MLDataType Type();
-
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override {
- return this->IsMapCompatible(type_proto);
- }
-
- private:
- MapType() {
- using namespace data_types_internal;
- SetMapTypes<typename CPPType::key_type, typename CPPType::mapped_type>::Set(this->mutable_type_proto());
- }
-};
-#endif
-
-/**
- * \brief SequenceType. Use to register sequence for non-tensor types.
- *
- * \param T - CPP type that you wish to register as Sequence
- * runtime type.
- *
- * \details Usage: ORT_REGISTER_SEQ(C++Type)
- * The type is required to have value_type defined
- */
-template <typename CPPType>
-class SequenceType : public NonTensorType<CPPType> {
- public:
- static MLDataType Type();
-
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override {
- return this->IsSequenceCompatible(type_proto);
- }
-
- private:
- SequenceType() {
- data_types_internal::SetSequenceType<typename CPPType::value_type>::Set(this->mutable_type_proto());
- }
-};
-
-/**
- * \brief SequenceTensorTypeBase serves as a base type class for
- * Tensor sequences. Akin TensorTypeBase.
- * Runtime representation is always TensorSeq.
- */
-class SequenceTensorTypeBase : public DataTypeImpl {
- public:
- static MLDataType Type();
-
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override;
-
- bool IsTensorSequenceType() const override {
- return true;
- }
-
- const SequenceTensorTypeBase* AsSequenceTensorBase() const override {
- return this;
- }
-
- virtual MLDataType GetElementType() const {
- // should never reach here.
- ORT_NOT_IMPLEMENTED(__FUNCTION__, " is not implemented");
- }
-
- size_t Size() const override;
-
- DeleteFunc GetDeleteFunc() const override;
-
- const ONNX_NAMESPACE::TypeProto* GetTypeProto() const override;
-
- SequenceTensorTypeBase(const SequenceTensorTypeBase&) = delete;
- SequenceTensorTypeBase& operator=(const SequenceTensorTypeBase&) = delete;
-
- protected:
- SequenceTensorTypeBase();
- ~SequenceTensorTypeBase();
-
- ONNX_NAMESPACE::TypeProto& mutable_type_proto();
-
- private:
- struct Impl;
- Impl* impl_;
-};
-
-/**
- * \brief SequenceTensorType. Use to register sequence for non-tensor types.
- *
- * \param CPPRuntime - We always use TensorSeq
- *
- * \param TensorElemType - one of the primitive types
- *
- * \details Usage: ORT_REGISTER_SEQ_TENSOR_TYPE()
- * The type is required to have value_type defined
- */
-template <typename TensorElemType>
-class SequenceTensorType : public SequenceTensorTypeBase {
- public:
- static MLDataType Type();
-
- /// Return a MLDataType representing the element-type
- MLDataType GetElementType() const override {
- return DataTypeImpl::GetType<TensorElemType>();
- }
-
- private:
- SequenceTensorType() {
- data_types_internal::SetSequenceType<TensorElemType>::Set(this->mutable_type_proto());
- }
-};
-
-/**
- * \brief OpaqueType
- *
- * \param T - cpp runtume that implements the Opaque type
- *
- * \param const char D[] - domain must be extern to be unique
- *
- * \param const char N[] - name must be extern to be unique
- *
- * \details Only one CPP type can be associated with a particular
- * OpaqueType registration
- *
- */
-template <typename T, const char D[], const char N[]>
-class OpaqueType : public NonTensorType<T> {
- public:
- static MLDataType Type();
-
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto& type_proto) const override {
- return this->IsOpaqueCompatible(type_proto);
- }
-
- void FromDataContainer(const void* data, size_t data_size, OrtValue& output) const override {
- NonTensorTypeConverter<T>::FromContainer(this, data, data_size, output);
- }
-
- void ToDataContainer(const OrtValue& input, size_t data_size, void* data) const override {
- NonTensorTypeConverter<T>::ToContainer(input, data_size, data);
- }
-
- private:
- OpaqueType() {
- data_types_internal::AssignOpaqueDomainName(D, N, this->mutable_type_proto());
- }
-};
-
-/**
- * \brief PrimitiveDataTypeBase
- * Base class for primitive Tensor contained types
- *
- * \details This class contains an integer constant that can be
- * used for input data type dispatching
- *
- */
-class PrimitiveDataTypeBase : public DataTypeImpl {
- public:
- bool IsCompatible(const ONNX_NAMESPACE::TypeProto&) const override {
- return false;
- }
-
- const PrimitiveDataTypeBase* AsPrimitiveDataType() const override final {
- return this;
- }
-
- const ONNX_NAMESPACE::TypeProto* GetTypeProto() const final {
- return nullptr;
- }
-
- int32_t GetDataType() const {
- return data_type_;
- }
-
- protected:
- PrimitiveDataTypeBase() = default;
-
- void SetDataType(int32_t data_type) {
- data_type_ = data_type;
- }
-
- private:
- int32_t data_type_;
-};
-
-/**
- * \brief PrimitiveDataType
- * Typed specialization for primitive types.
- * Concrete instances of this class are used by Tensor.
- *
- * \param T - primitive data type
- *
- */
-template <typename T>
-class PrimitiveDataType : public PrimitiveDataTypeBase {
- private:
- static void Delete(void* p) {
- delete static_cast<T*>(p);
- }
-
- public:
- static MLDataType Type();
-
- size_t Size() const override {
- return sizeof(T);
- }
-
- DeleteFunc GetDeleteFunc() const override {
- return &Delete;
- }
-
- private:
- PrimitiveDataType() {
- this->SetDataType(data_types_internal::TensorElementTypeSetter<T>::GetElementType());
- }
-};
-
-// Explicit specialization of base class template function
-// is only possible within the enclosing namespace scope,
-// thus a simple way to pre-instantiate a given template
-// at a registration time does not currently work and the macro
-// is needed.
-#define ORT_REGISTER_TENSOR_TYPE(ELEM_TYPE) \
- template <> \
- MLDataType TensorType<ELEM_TYPE>::Type() { \
- static TensorType<ELEM_TYPE> tensor_type; \
- return &tensor_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetTensorType<ELEM_TYPE>() { \
- return TensorType<ELEM_TYPE>::Type(); \
- }
-
-#define ORT_REGISTER_SPARSE_TENSOR_TYPE(ELEM_TYPE) \
- template <> \
- MLDataType SparseTensorType<ELEM_TYPE>::Type() { \
- static SparseTensorType<ELEM_TYPE> tensor_type; \
- return &tensor_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetSparseTensorType<ELEM_TYPE>() { \
- return SparseTensorType<ELEM_TYPE>::Type(); \
- }
-
-#if !defined(DISABLE_ML_OPS)
-#define ORT_REGISTER_MAP(TYPE) \
- template <> \
- MLDataType MapType<TYPE>::Type() { \
- static MapType<TYPE> map_type; \
- return &map_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetType<TYPE>() { \
- return MapType<TYPE>::Type(); \
- }
-#endif
-
-#define ORT_REGISTER_SEQ(TYPE) \
- template <> \
- MLDataType SequenceType<TYPE>::Type() { \
- static SequenceType<TYPE> sequence_type; \
- return &sequence_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetType<TYPE>() { \
- return SequenceType<TYPE>::Type(); \
- }
-
-#define ORT_REGISTER_SEQ_TENSOR_TYPE(ELEM_TYPE) \
- template <> \
- MLDataType SequenceTensorType<ELEM_TYPE>::Type() { \
- static SequenceTensorType<ELEM_TYPE> sequence_tensor_type; \
- return &sequence_tensor_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetSequenceTensorType<ELEM_TYPE>() { \
- return SequenceTensorType<ELEM_TYPE>::Type(); \
- }
-
-#define ORT_REGISTER_PRIM_TYPE(TYPE) \
- template <> \
- MLDataType PrimitiveDataType<TYPE>::Type() { \
- static PrimitiveDataType<TYPE> prim_data_type; \
- return &prim_data_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetType<TYPE>() { \
- return PrimitiveDataType<TYPE>::Type(); \
- }
-
-#define ORT_REGISTER_OPAQUE_TYPE(CPPType, Domain, Name) \
- template <> \
- MLDataType OpaqueType<CPPType, Domain, Name>::Type() { \
- static OpaqueType<CPPType, Domain, Name> opaque_type; \
- return &opaque_type; \
- } \
- template <> \
- MLDataType DataTypeImpl::GetType<CPPType>() { \
- return OpaqueType<CPPType, Domain, Name>::Type(); \
- }
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/data_types_internal.h b/include/onnxruntime/core/framework/data_types_internal.h
deleted file mode 100755
index 1f154fc..0000000
--- a/include/onnxruntime/core/framework/data_types_internal.h
+++ /dev/null
@@ -1,520 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <assert.h>
-#include <stdint.h>
-#include <string>
-#include <vector>
-
-#include "core/common/common.h"
-#include "core/framework/data_types.h"
-#include "core/graph/onnx_protobuf.h"
-
-#ifdef _MSC_VER
-#pragma warning(push)
-//TODO: fix the warning in CallableDispatchableRetHelper
-#pragma warning(disable : 4702)
-#endif
-namespace onnxruntime {
-namespace utils {
-
-template <typename T>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType() {
- return ONNX_NAMESPACE::TensorProto_DataType_UNDEFINED;
-}
-
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<float>() {
- return ONNX_NAMESPACE::TensorProto_DataType_FLOAT;
-}
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<uint8_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT8;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<int8_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT8;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<uint16_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<int16_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<int32_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT32;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<int64_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_INT64;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<std::string>() {
- return ONNX_NAMESPACE::TensorProto_DataType_STRING;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<bool>() {
- return ONNX_NAMESPACE::TensorProto_DataType_BOOL;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<MLFloat16>() {
- return ONNX_NAMESPACE::TensorProto_DataType_FLOAT16;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<double>() {
- return ONNX_NAMESPACE::TensorProto_DataType_DOUBLE;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<uint32_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT32;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<uint64_t>() {
- return ONNX_NAMESPACE::TensorProto_DataType_UINT64;
-};
-template <>
-constexpr ONNX_NAMESPACE::TensorProto_DataType ToTensorProtoElementType<BFloat16>() {
- return ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16;
-};
-
- // The following primitives are strongly recommended for switching on tensor input datatypes for
- // kernel implementations.
- //
- // 1) If you need to handle all of the primitive tensor contained datatypes, the best choice would be macros
- // DispatchOnTensorType or DispatchOnTensorTypeWithReturn. Use inline wrappers so your function can be invoked as function<T>().
- // 2) if you have a few types, use Tensor.IsDataType<T>()/IsDataTypeString() or use utils::IsPrimitiveDataType<T>()
- // if you have a standalone MLDatatType with a sequence of if/else statements.
- // 3) For something in between, we suggest to use CallDispatcher pattern.
- //
- // Invoking DataTypeImpl::GetType<T>() for switching on input types is discouraged and should be avoided.
- // Every primitive type carries with it an integer constant that can be used for quick switching on types.
-
-#define DispatchOnTensorType(tensor_type, function, ...) \
- switch (tensor_type->AsPrimitiveDataType()->GetDataType()) { \
- case ONNX_NAMESPACE::TensorProto_DataType_FLOAT: \
- function<float>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_BOOL: \
- function<bool>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_DOUBLE: \
- function<double>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_STRING: \
- function<std::string>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT8: \
- function<int8_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT8: \
- function<uint8_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT16: \
- function<int16_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT16: \
- function<uint16_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT32: \
- function<int32_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT32: \
- function<uint32_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT64: \
- function<int64_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT64: \
- function<uint64_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_FLOAT16: \
- function<MLFloat16>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16: \
- function<BFloat16>(__VA_ARGS__); \
- break; \
- default: \
- ORT_ENFORCE(false, "Unknown tensor type of ", tensor_type); \
- }
-
-#define DispatchOnTensorTypeWithReturn(tensor_type, retval, function, ...) \
- switch (tensor_type->AsPrimitiveDataType()->GetDataType()) { \
- case ONNX_NAMESPACE::TensorProto_DataType_FLOAT: \
- retval = function<float>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_BOOL: \
- retval = function<bool>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_DOUBLE: \
- retval = function<double>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_STRING: \
- retval = function<std::string>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT8: \
- retval = function<int8_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT8: \
- retval = function<uint8_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT16: \
- retval = function<uint16_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT16: \
- retval = function<int16_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT32: \
- retval = function<int32_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT32: \
- retval = function<uint32_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_INT64: \
- retval = function<int64_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_UINT64: \
- retval = function<uint64_t>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_FLOAT16: \
- retval = function<MLFloat16>(__VA_ARGS__); \
- break; \
- case ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16: \
- retval = function<BFloat16>(__VA_ARGS__); \
- break; \
- default: \
- ORT_ENFORCE(false, "Unknown tensor type of ", tensor_type); \
- }
-
-////////////////////////////////////////////////////////////////////////////////
-/// Use the following primitives if you have a few types to switch on so you
-// can write a short sequence of if/else statements.
-
-// This is a frequently used check so we make a separate utility function.
-inline bool IsDataTypeString(MLDataType dt_type) {
- auto prim_type = dt_type->AsPrimitiveDataType();
- return (prim_type != nullptr && prim_type->GetDataType() == ONNX_NAMESPACE::TensorProto_DataType_STRING);
-}
-
-// Test if MLDataType is a concrete type of PrimitiveDataTypeBase
-// and it is T
-template <class T>
-inline bool IsPrimitiveDataType(MLDataType dt_type) {
- auto prim_type = dt_type->AsPrimitiveDataType();
- return (prim_type != nullptr && prim_type->GetDataType() == ToTensorProtoElementType<T>());
-}
-
-// Use after AsPrimitiveDataType() is successful
-// Check if PrimitiveDataTypeBase is of type T
-template <class T>
-inline bool IsPrimitiveDataType(const PrimitiveDataTypeBase* prim_type) {
- assert(prim_type != nullptr);
- return prim_type->GetDataType() == ToTensorProtoElementType<T>();
-}
-
-// This implementation contains a workaround for GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47226
-// GCC until very recently does not support template parameter pack expansion within lambda context.
-namespace mltype_dispatcher_internal {
-// T - type handled by this helper
-struct CallableDispatchableHelper {
- int32_t dt_type_; // Type currently dispatched
- size_t called_;
-
- explicit CallableDispatchableHelper(int32_t dt_type) noexcept : dt_type_(dt_type), called_(0) {}
-
- // Must return integer to be in a expandable context
- template <class T, class Fn, class... Args>
- int Invoke(Fn&& fn, Args&&... args) {
- if (utils::ToTensorProtoElementType<T>() == dt_type_) {
- std::forward<Fn>(fn)(std::forward<Args>(args)...);
- ++called_;
- }
- return 0;
- }
-};
-
-// Default policy is to throw with no return type.
-template <class Ret>
-struct UnsupportedTypeDefaultPolicy {
- Ret operator()(int32_t dt_type) const {
- ORT_THROW("Unsupported data type: ", dt_type);
- }
-};
-
-// Helper with the result type
-template <class Ret, class UnsupportedPolicy = UnsupportedTypeDefaultPolicy<Ret>>
-struct CallableDispatchableRetHelper {
- int32_t dt_type_; // Type currently dispatched
- size_t called_;
- Ret result_;
-
- explicit CallableDispatchableRetHelper(int32_t dt_type) noexcept : dt_type_(dt_type), called_(0), result_() {}
-
- Ret Get() {
- // See if there were multiple invocations.It is a bug.
- ORT_ENFORCE(called_ < 2, "Check for duplicate types in MLTypeCallDispatcherRet");
- // No type was invoked
- if (called_ == 0) {
- result_ = UnsupportedPolicy()(dt_type_);
- }
- return result_;
- }
-
- // Must return integer to be in a expandable context
- template <class T, class Fn, class... Args>
- int Invoke(Fn&& fn, Args&&... args) {
- if (utils::ToTensorProtoElementType<T>() == dt_type_) {
- result_ = std::forward<Fn>(fn)(std::forward<Args>(args)...);
- ++called_;
- }
- return 0;
- }
-};
-
-} // namespace mltype_dispatcher_internal
-
-// This class helps to efficiently dispatch calls for templated
-// kernel implementation functions that has no return value.
-// If your implementation function must return a value such as Status
-// Use MLTypeCallDispatcherRet class.
-//
-// The first template parameter is a template<T> struct/class functor
-// that must implement operator() with arbitrary number of arguments
-// and void return turn. It must return Ret type if you are using MLTypeCallDispatcherRet.
-// Fn must be default constructible.
-//
-// Types is a type list that are supported by this kernel implementation.
-// There should be no duplicate types. An exception will be thrown if there
-// a duplicate.
-//
-// The constructor accepts an enum that is obtained from
-// input_tensor->DataType()->AsPrimitiveType()->GetDataType().
-// Fn will be called only once the type designated by dt_type value.
-// If current dt_type is not handled, the Dispatcher will throw an exception.
-//
-template <template <typename> class Fn, typename... Types>
-class MLTypeCallDispatcher {
- int32_t dt_type_;
-
- public:
- explicit MLTypeCallDispatcher(int32_t dt_type) noexcept : dt_type_(dt_type) {}
-
- template <typename... Args>
- void Invoke(Args&&... args) const {
- mltype_dispatcher_internal::CallableDispatchableHelper helper(dt_type_);
- int results[] = {0, helper.template Invoke<Types>(Fn<Types>(), std::forward<Args>(args)...)...};
- ORT_UNUSED_PARAMETER(results);
- ORT_ENFORCE(helper.called_ < 2, "Check for duplicate types in MLTypeCallDispatcher");
- ORT_ENFORCE(helper.called_ == 1, "Unsupported data type: ", dt_type_);
- }
-};
-
-// Version of the MLTypeDispatcher with a return type.
-// Return type of Fn must return type convertible to Ret
-// The value of the return type will be the return value
-// of the function for type T which was specified for execution.
-template <class Ret, template <typename> class Fn, typename... Types>
-class MLTypeCallDispatcherRet {
- int32_t dt_type_;
-
- public:
- explicit MLTypeCallDispatcherRet(int32_t dt_type) noexcept : dt_type_(dt_type) {}
-
- template <typename... Args>
- Ret Invoke(Args&&... args) const {
- mltype_dispatcher_internal::CallableDispatchableRetHelper<Ret> helper(dt_type_);
- int results[] = {0, helper.template Invoke<Types>(Fn<Types>(), std::forward<Args>(args)...)...};
- ORT_UNUSED_PARAMETER(results);
- return helper.Get();
- }
-
- template <class UnsupportedPolicy, typename... Args>
- Ret InvokeWithUnsupportedPolicy(Args&&... args) const {
- mltype_dispatcher_internal::CallableDispatchableRetHelper<Ret, UnsupportedPolicy> helper(dt_type_);
- int results[] = {0, helper.template Invoke<Types>(Fn<Types>(), std::forward<Args>(args)...)...};
- ORT_UNUSED_PARAMETER(results);
- return helper.Get();
- }
-};
-
-// Version of the MLTypeDispatcher that has an input type which is passed through ('carried')
-// as the first type parameter in the call to Fn when dispatching.
-template <typename TCarried, template <typename, typename> class Fn, typename... Types>
-class MLTypeCallDispatcherWithCarriedType {
- int32_t dt_type_;
-
- public:
- explicit MLTypeCallDispatcherWithCarriedType(int32_t dt_type) noexcept : dt_type_(dt_type) {}
-
- template <typename... Args>
- void Invoke(Args&&... args) const {
- mltype_dispatcher_internal::CallableDispatchableHelper helper(dt_type_);
- int results[] = {0, helper.template Invoke<Types>(Fn<TCarried, Types>(), std::forward<Args>(args)...)...};
- ORT_UNUSED_PARAMETER(results);
- ORT_ENFORCE(helper.called_ < 2, "Check for duplicate types in MLTypeCallDispatcher");
- ORT_ENFORCE(helper.called_ == 1, "Unsupported data type: ", dt_type_);
- }
-};
-
-namespace data_types_internal {
-
-enum class ContainerType : uint16_t {
- kUndefined = 0,
- kTensor = 1,
- kMap = 2,
- kSequence = 3,
- kOpaque = 4
-};
-
-class TypeNode {
- // type_ is a TypeProto value case enum
- // that may be a kTypeTensor, kTypeMap, kTypeSequence
- // prim_type_ is a TypeProto_DataType enum that has meaning
- // - for Tensor then prim_type_ is the contained type
- // - for Map prim_type is the key type. Next entry describes map value
- // - For sequence prim_type_ is not used and has no meaning. Next entry
- // describes the value for the sequence
- // Tensor is always the last entry as it describes a contained primitive type.
- ContainerType type_;
- uint16_t prim_type_;
-
- public:
- TypeNode(ContainerType type, int32_t prim_type) noexcept {
- type_ = type;
- prim_type_ = static_cast<uint16_t>(prim_type);
- }
-
- bool IsType(ContainerType type) const noexcept {
- return type_ == type;
- }
-
- bool IsPrimType(int32_t prim_type) const noexcept {
- return prim_type_ == static_cast<uint16_t>(prim_type);
- }
-};
-
-} // namespace data_types_internal
-
-////////////////////////////////////////////////////////////////////
-/// Provides generic interface to test whether MLDataType is a Sequence,
-/// Map or an Opaque type including arbitrary recursive definitions
-/// without querying DataTypeImpl::GetType<T> for all known complex types
-
-// T is a sequence contained element type
-// If returns true then we know that the runtime
-// representation is std::vector<T>
-// T itself can be a runtime representation of another
-// sequence, map, opaque type or a tensor
-//
-// That is it can be std::vector or a std::map
-// If T is a primitive type sequence is tested whether it contains
-// tensors of that type
-//
-// If T is an opaque type, then it is only tested to be opaque but not exactly
-// a specific opaque type. To Test for a specific Opaque type use IsOpaqueType() below
-//
-// This class examines the supplied MLDataType and records
-// its information in a vector so any subsequent checks for Sequences and Maps
-// are quick.
-class ContainerChecker {
- using Cont = std::vector<data_types_internal::TypeNode>;
- Cont types_;
-
- // Default IsContainerOfType is for Opaque type
- template <class T>
- struct IsContainerOfType {
- static bool check(const Cont& c, size_t index) {
- if (index >= c.size()) {
- return false;
- }
- return c[index].IsType(data_types_internal::ContainerType::kOpaque);
- }
- };
-
- // Handles the case where sequence element is also a sequence
- template <class T>
- struct IsContainerOfType<std::vector<T>> {
- static bool check(const Cont& c, size_t index) {
- if (index >= c.size()) {
- return false;
- }
- if (c[index].IsType(data_types_internal::ContainerType::kSequence)) {
- ORT_ENFORCE(++index < c.size(), "Sequence is missing type entry for its element");
- constexpr int32_t prim_type = ToTensorProtoElementType<T>();
- // Check if this is a primitive type and it matches
- if (prim_type != ONNX_NAMESPACE::TensorProto_DataType_UNDEFINED) {
- return c[index].IsType(data_types_internal::ContainerType::kTensor) &&
- c[index].IsPrimType(prim_type);
- } else {
- // T is not primitive, check next entry for non-primitive proto
- return IsContainerOfType<T>::check(c, index);
- }
- }
- return false;
- }
- };
-
- template <class K, class V>
- struct IsContainerOfType<std::map<K, V>> {
- static bool check(const Cont& c, size_t index) {
- static_assert(ToTensorProtoElementType<K>() != ONNX_NAMESPACE::TensorProto_DataType_UNDEFINED,
- "Map Key can not be a non-primitive type");
- if (index >= c.size()) {
- return false;
- }
- if (!c[index].IsType(data_types_internal::ContainerType::kMap)) {
- return false;
- }
- constexpr int32_t key_type = ToTensorProtoElementType<K>();
- if (!c[index].IsPrimType(key_type)) {
- return false;
- }
- ORT_ENFORCE(++index < c.size(), "Map is missing type entry for its value");
- constexpr int32_t val_type = ToTensorProtoElementType<V>();
- if (val_type != ONNX_NAMESPACE::TensorProto_DataType_UNDEFINED) {
- return c[index].IsType(data_types_internal::ContainerType::kTensor) &&
- c[index].IsPrimType(val_type);
- }
- return IsContainerOfType<V>::check(c, index);
- }
- };
-
- public:
- explicit ContainerChecker(MLDataType);
- ~ContainerChecker() = default;
-
- bool IsMap() const noexcept {
- assert(!types_.empty());
- return types_[0].IsType(data_types_internal::ContainerType::kMap);
- }
-
- bool IsSequence() const noexcept {
- assert(!types_.empty());
- return types_[0].IsType(data_types_internal::ContainerType::kSequence);
- }
-
- template <class T>
- bool IsSequenceOf() const {
- assert(!types_.empty());
- return IsContainerOfType<std::vector<T>>::check(types_, 0);
- }
-
- template <class K, class V>
- bool IsMapOf() const {
- assert(!types_.empty());
- return IsContainerOfType<std::map<K, V>>::check(types_, 0);
- }
-};
-
-bool IsOpaqueType(MLDataType ml_type, const char* domain, const char* name);
-
-} // namespace utils
-} // namespace onnxruntime
-
-#ifdef _MSC_VER
-#pragma warning(pop)
-#endif
diff --git a/include/onnxruntime/core/framework/endian.h b/include/onnxruntime/core/framework/endian.h
deleted file mode 100755
index 629fb78..0000000
--- a/include/onnxruntime/core/framework/endian.h
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-
-// the semantics of this enum should match std::endian from C++20
-enum class endian {
-#if defined(_WIN32)
- little = 0,
- big = 1,
- native = little,
-#elif defined(__GNUC__) || defined(__clang__)
- little = __ORDER_LITTLE_ENDIAN__,
- big = __ORDER_BIG_ENDIAN__,
- native = __BYTE_ORDER__,
-#else
-#error onnxruntime::endian is not implemented in this environment.
-#endif
-};
-
-static_assert(
- endian::native == endian::little || endian::native == endian::big,
- "Only little-endian or big-endian native byte orders are supported.");
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/execution_provider.h b/include/onnxruntime/core/framework/execution_provider.h
deleted file mode 100755
index 3c877f2..0000000
--- a/include/onnxruntime/core/framework/execution_provider.h
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#ifndef PROVIDER_BRIDGE_PROVIDER
-#include <map>
-#include <unordered_map>
-#include <unordered_set>
-
-#include "core/common/status.h"
-#include "core/common/logging/logging.h"
-#include "core/framework/tensor.h"
-#include "core/framework/data_transfer.h"
-
-namespace onnxruntime {
-
-class GraphViewer;
-class Node;
-struct ComputeCapability;
-class KernelRegistry;
-class KernelRegistryManager;
-} // namespace onnxruntime
-#endif
-
-#include "core/framework/provider_options.h"
-#include "core/framework/func_api.h"
-
-namespace onnxruntime {
-
-/**
- Logical device representation.
-*/
-using AllocatorMap = std::map<int, AllocatorPtr>;
-using MemoryInfoSet = std::set<OrtMemoryInfo>;
-
-// if we are export the fused function to dll, the function will still in the same binary as onnxruntime
-// use std function to give execution provider some chance to capture some state.
-using CreateFunctionStateFunc = std::function<int(ComputeContext*, FunctionState*)>;
-using ComputeFunc = std::function<Status(FunctionState, const OrtApi*, OrtKernelContext*)>;
-using DestroyFunctionStateFunc = std::function<void(FunctionState)>;
-
-struct NodeComputeInfo {
- CreateFunctionStateFunc create_state_func;
- ComputeFunc compute_func;
- DestroyFunctionStateFunc release_state_func;
-};
-
-class IExecutionProvider {
- protected:
- IExecutionProvider(const std::string& type, bool use_metadef_id_creator = false)
- : type_{type} {
- if (use_metadef_id_creator) {
- metadef_id_generator_ = onnxruntime::make_unique<ModelMetadefIdGenerator>();
- }
- }
-
- public:
- virtual ~IExecutionProvider() = default;
-
- /**
- Get all IAllocators for <*this> execution provider.
- */
- const std::vector<AllocatorPtr>& GetAllocators() const {
- return allocator_list_;
- }
-
- /**
- * Get an allocator with specified device id and MemType. Return nullptr if it doesn't exist
- */
- virtual AllocatorPtr GetAllocator(int id, OrtMemType mem_type) const;
-
- /**
- * Returns a data transfer object that implements methods to copy to and
- * from this device.
- * If no copy is required for the successful operation of this provider,
- * return a nullptr.
- */
- virtual std::unique_ptr<onnxruntime::IDataTransfer> GetDataTransfer() const {
- return nullptr;
- }
-
- /**
- Get execution provider's capability for the specified <graph>.
- Return a bunch of IndexedSubGraphs <*this> execution provider can run if
- the sub-graph contains only one node or can fuse to run if the sub-graph
- contains more than one node. The node indexes contained in sub-graphs may
- have overlap, and it's ONNXRuntime's responsibility to do the partition
- and decide whether a node will be assigned to <*this> execution provider.
- */
- virtual std::vector<std::unique_ptr<ComputeCapability>>
- GetCapability(const onnxruntime::GraphViewer& graph_viewer,
- const std::vector<const KernelRegistry*>& kernel_registries) const;
-
- /**
- Get kernel registry per execution provider type.
- The KernelRegistry share pointer returned is shared across sessions.
-
- NOTE: this is a tricky but final solution to achieve following goals,
- 1. The execution provider type based kernel registry should be shared
- across sessions.
- Only one copy of this kind of kernel registry exists in ONNXRuntime
- with multiple sessions/models.
- 2. Adding an execution provider into ONNXRuntime does not need to touch ONNXRuntime
- frameowrk/session code.
- 3. onnxruntime (framework/session) does not depend on any specific
- execution provider lib.
- */
- virtual std::shared_ptr<KernelRegistry> GetKernelRegistry() const { return nullptr; }
-
- /**
- Get the device id of current execution provider
- */
- virtual int GetDeviceId() const { return -1; };
-
- /**
- Get execution provider's configuration options.
- */
- virtual ProviderOptions GetProviderOptions() const { return {}; }
-
- /**
- Returns an opaque handle whose exact type varies based on the provider
- and is interpreted accordingly by the corresponding kernel implementation.
- For Direct3D operator kernels, this may return an IUnknown supporting
- QueryInterface to ID3D12GraphicsCommandList1.
- */
- virtual const void* GetExecutionHandle() const noexcept {
- return nullptr;
- }
-
- /**
- @return type of the execution provider; should match that set in the node
- through the SetExecutionProvider API. Example valid return values are:
- kCpuExecutionProvider, kCudaExecutionProvider
- */
- const std::string& Type() const { return type_; }
-
- /**
- Blocks until the device has completed all preceding requested tasks.
- Currently this is primarily used by the IOBinding object to ensure that all
- inputs have been copied to the device before execution begins.
- */
- virtual common::Status Sync() const { return Status::OK(); }
-
- /**
- Called when InferenceSession::Run started
- NOTE that due to async execution in provider, the actual work of previous
- Run may not be finished on device This function should be regarded as the
- point after which a new Run would start to submit commands from CPU
- */
- virtual common::Status OnRunStart() { return Status::OK(); }
-
- /**
- Called when InferenceSession::Run ended
- NOTE that due to async execution in provider, the actual work of this Run
- may not be finished on device This function should be regarded as the point
- that all commands of current Run has been submmited by CPU
- */
- virtual common::Status OnRunEnd() { return Status::OK(); }
-
- /**
- Called when session creation is complete
- This provides an opportunity for execution providers to optionally synchronize and
- clean up its temporary resources to reduce memory and ensure the first run is fast.
- */
- virtual common::Status OnSessionInitializationEnd() { return Status::OK(); }
-
- void InsertAllocator(AllocatorPtr allocator);
- void ReplaceAllocator(AllocatorPtr allocator);
-
- // creation of a fused node is not supported in a minimal build, so any EP enabled in that scenario must support
- // compilation via GraphViewer instances.
-#if !defined(ORT_MINIMAL_BUILD)
- /**
- Given a list of fused_node, return create_state/compute/release_state func for each node.
- */
- virtual common::Status Compile(const std::vector<onnxruntime::Node*>& fused_nodes,
- std::vector<NodeComputeInfo>& node_compute_funcs);
-
- /**
- Given a list of fused_node, return a dll that expose functions for each node.
- For each node, there should be three symbols:
- Create_State_${node_name}
- Compute_${node_name}
- Release_State_${node_name}
- */
- virtual common::Status Compile(const std::vector<onnxruntime::Node*>& fused_nodes,
- std::string& dll_path);
-
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
- struct FusedNodeAndGraph {
- const std::reference_wrapper<onnxruntime::Node> fused_node;
- // GraphViewer that filters the full graph to the nodes that are covered by 'node'
- const std::reference_wrapper<GraphViewer> filtered_graph;
- };
-
- /**
- Given a collection of fused Nodes and the respective GraphViewer instance for the nodes that were fused,
- return create_state/compute/release_state func for each node.
- @remarks This is an optional interface that is only needed if the execution provider compiles nodes
- in a scenario involving the minimal build. i.e. on a mobile or embedded device with ORT format model.
-
- Do NOT cache the GraphViewer in FusedNodeAndGraph.filtered_graph in any of the NodeComputeInfo functions
- as it is only valid for the duration of the call to Compile.
- */
- virtual common::Status Compile(const std::vector<FusedNodeAndGraph>& fused_nodes_and_graphs,
- std::vector<NodeComputeInfo>& node_compute_funcs);
-#endif
-
- // Fusion approach that is suppported
- enum class FusionStyle {
- // The node fusion will create an onnxruntime::Function based Node that contains a completely new Graph instance
- // in the Node body. The original nodes and initializers are copied to the new Graph instance in Function::Body().
- // A GraphProto can be produced from the Node body.
- Function,
-
- // The node fusion will create a new Node that defines the inputs and outputs using the IndexedSubGraph
- // that GetCapability returned. The Node will not be onnxruntime::Function based so will have no Body().
- // Instead a GraphViewer that filters the full Graph to the fused Nodes will be created.
- // This is significantly cheaper as it doesn't incur the cost of creating a new Graph instance,
- // and can be supported in a minimal build.
- FilteredGraphViewer
- };
-
- virtual FusionStyle GetFusionStyle() const {
- // existing EPs use this mode so default to it.
- // newer EPs that can use the cheaper approach, or need to run in a minimal build, should override to return
- // FilteredGraphViewer
- return FusionStyle::Function;
- }
-
- void SetLogger(const logging::Logger* logger) {
- logger_ = logger;
- }
-
- const logging::Logger* GetLogger() const {
- return logger_;
- }
-
- /** Generate a unique id that can be used in a MetaDef name. Values are unique for a model instance.
- The model hash is also returned if you wish to include that in the MetaDef name to ensure uniqueness across models.
- @param graph_viewer[in] Graph viewer that GetCapability was called with. Can be for the main graph or nested graph.
- @param model_hash[out] Returns the hash for the main (i.e. top level) graph in the model.
- This is created using the model path if available,
- or the model input names and the output names from all nodes in the main graph.
- @remarks e.g. the TensorRT Execution Provider is used in multiple sessions and the underlying infrastructure caches
- compiled kernels, so the name must be unique and deterministic across models and sessions.
- NOTE: Ideally this would be a protected method, but to work across the EP bridge it has to be public and
- virtual, and ModelMetadefIdGenerator but be defined in the header as well.
- */
- virtual int GenerateMetaDefId(const onnxruntime::GraphViewer& graph_viewer, uint64_t& model_hash) const;
-
- private:
- const std::string type_;
- AllocatorMap allocators_;
- MemoryInfoSet mem_info_set_; // to ensure only allocators with unique OrtMemoryInfo are registered in the provider.
- //It will be set when this object is registered to a session
- const logging::Logger* logger_ = nullptr;
- // convenience list of the allocators so GetAllocatorList doesn't have to build a new vector each time
- // contains the same instances as allocators_
- std::vector<AllocatorPtr> allocator_list_;
-
- // helper to generate ids that are unique to model and deterministic, even if the execution provider is shared across
- // multiple sessions.
- class ModelMetadefIdGenerator {
- public:
- int GenerateId(const onnxruntime::GraphViewer& graph_viewer, uint64_t& model_hash);
-
- private:
- std::unordered_map<uint64_t, int64_t> main_graph_hash_; // map graph instance hash to model contents hash
- std::unordered_map<int64_t, int> model_metadef_id_; // current unique id for model
- };
-
- std::unique_ptr<ModelMetadefIdGenerator> metadef_id_generator_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/fence.h b/include/onnxruntime/core/framework/fence.h
deleted file mode 100755
index e8408d1..0000000
--- a/include/onnxruntime/core/framework/fence.h
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-
-using ProviderType = const std::string&;
-
-/*
- We use a simple fence mechanism for async compute. Assumptions in this fence mechanism:
- * Execution provider command queues, which execute in the same order of submit
- * No fence needed for kernels within one execution provider command queue
- * Fence is used to synchronize between command queues, and execution providers
-
- Fence usage:
- 1. Fence object would be created by allocation planer for input/output when KernelDef::ExecQueueId() is not zero
- 2. If fence object exists, executor would call BeforeUsingAs* prior to kernel::Compute(), and AfterUsedAs* afterwards
-*/
-class IFence {
- public:
- virtual ~IFence() = default;
-
- /**
- Called by executor before OrtValue is used as input in a compute kernel in provider_type and exec queue_id
- This should wait in the specified provider's exec queue for previous write to OrtValue to finish
- */
- virtual void BeforeUsingAsInput(onnxruntime::ProviderType provider_type, int queue_id) = 0;
-
- /**
- Called by executor before OrtValue is used as output in a compute kernel in provider_type and exec queue_id
- This should wait in the specified provider's exec queue for previous read to OrtValue to finish
- */
- virtual void BeforeUsingAsOutput(onnxruntime::ProviderType provider_type, int queue_id) = 0;
-
- /**
- Called by executor after OrtValue is used as input in a compute kernel in provider_type and exec queue_id
- This should update the read fence of the MLValue
- */
- virtual void AfterUsedAsInput(int queue_id) = 0;
-
- /**
- Called by executor after OrtValue is used as output in a compute kernel in provider_type and exec queue_id
- This should update the write fence of the MLValue
- */
- virtual void AfterUsedAsOutput(int queue_id) = 0;
-
- /**
- Called by executor before release OrtValue to see whether async data read is finished or not. This is non-blocking.
- */
- virtual bool CanRelease() = 0;
-};
-using Fence_t = IFence*;
-using FencePtr = std::shared_ptr<IFence>;
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/framework_common.h b/include/onnxruntime/core/framework/framework_common.h
deleted file mode 100755
index dd0dea9..0000000
--- a/include/onnxruntime/core/framework/framework_common.h
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-#include "run_options.h"
-
-namespace onnxruntime { // forward declarations
-class Model;
-class GraphTransformer;
-class NodeArg;
-} // namespace onnxruntime
-
-namespace onnxruntime {
-using InputDefList = std::vector<const onnxruntime::NodeArg*>;
-using OutputDefList = std::vector<const onnxruntime::NodeArg*>;
-
-using NameMLValMap = std::unordered_map<std::string, OrtValue>;
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/func_api.h b/include/onnxruntime/core/framework/func_api.h
deleted file mode 100755
index 93b52d8..0000000
--- a/include/onnxruntime/core/framework/func_api.h
+++ /dev/null
@@ -1,27 +0,0 @@
-#pragma once
-#include "core/common/status.h"
-using onnxruntime::common::Status; // TODO: Needed by WinML, but shouldn't be put into the global namespace like this
-
-namespace onnxruntime {
-
-// AllocateFunc(void* handle, size_t alignment, size_t size)
-using AllocateFunc = void* (*)(void*, size_t, size_t);
-using DestroyFunc = void (*)(void*, void*);
-using AllocatorHandle = void*;
-
-typedef struct {
- //right now we only include allocation for host memory
- AllocateFunc allocate_func;
- DestroyFunc release_func;
- AllocatorHandle allocator_handle;
- const char* node_name;
-} ComputeContext;
-
-using FunctionState = void*;
-// take the ComputeContext, and create a function state.
-using CreateFunctionStateC = int (*)(ComputeContext*, FunctionState*);
-// pass in the function state and input/output tensors, perform compute and return status
-using ComputeFuncC = common::Status (*)(FunctionState, const OrtApi*, OrtKernelContext*);
-// release the function state.
-using DestroyFunctionStateC = void (*)(FunctionState);
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/kernel_def_builder.h b/include/onnxruntime/core/framework/kernel_def_builder.h
deleted file mode 100755
index 63c9269..0000000
--- a/include/onnxruntime/core/framework/kernel_def_builder.h
+++ /dev/null
@@ -1,339 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <memory>
-#include <string>
-#include <unordered_map>
-#include <vector>
-#include <limits.h>
-
-#include "core/common/common.h"
-#include "core/common/optional.h"
-#include "core/graph/basic_types.h"
-#include "core/framework/data_types.h"
-#include "core/framework/allocator.h"
-
-namespace onnxruntime {
-class KernelDefBuilder;
-
-typedef std::map<size_t, OrtMemType> MemTypeMap;
-
-class KernelDef {
- private:
- // note that input/output might be on CPU implicitly when the node is from CPU execution provider
- static inline bool MemTypeOnCpuExplicitly(OrtMemType mem_type) {
- return mem_type == OrtMemTypeCPUInput || mem_type == OrtMemTypeCPUOutput;
- }
-
- public:
- explicit KernelDef() = default;
-
- const std::string& OpName() const {
- return op_name_;
- }
-
- const std::string& Domain() const {
- return op_domain_;
- }
-
- void SinceVersion(/*out*/ int* start, /*out*/ int* end) const {
- *start = op_since_version_start_;
- *end = op_since_version_end_;
- }
-
-#ifdef onnxruntime_PYBIND_EXPORT_OPSCHEMA
- const std::pair<int, int> SinceVersion() const {
- return std::pair<int, int>(op_since_version_start_, op_since_version_end_);
- }
-#endif
-
- onnxruntime::ProviderType Provider() const {
- return provider_type_;
- }
-
- const std::map<std::string, std::vector<MLDataType>>& TypeConstraints() const {
- return type_constraints_;
- }
-
- const std::vector<std::pair<int, int>>& MayInplace() const {
- return inplace_map_;
- }
-
- const std::vector<std::pair<int, int>>& Alias() const {
- return alias_map_;
- }
-
- const optional<std::pair<int, int>>& VariadicAlias() const {
- return variadic_alias_offsets_;
- }
-
- OrtMemType InputMemoryType(size_t input_index) const {
- auto it = input_memory_type_args_.find(input_index);
- if (it == input_memory_type_args_.end())
- return default_inputs_mem_type_;
- return it->second;
- }
-
- bool IsInputOnCpu(size_t input_index) const { return MemTypeOnCpuExplicitly(InputMemoryType(input_index)); }
-
- bool IsOutputOnCpu(size_t output_index) const { return MemTypeOnCpuExplicitly(OutputMemoryType(output_index)); }
-
- bool AllocateInputsContiguously() const { return allocate_inputs_contiguously_; }
-
- OrtMemType OutputMemoryType(size_t output_index) const {
- auto it = output_memory_type_args_.find(output_index);
- if (it == output_memory_type_args_.end())
- return default_outputs_mem_type_;
- return it->second;
- }
-
- int ExecQueueId() const {
- return exec_queue_id_;
- }
-
- bool IsConflict(const KernelDef& other) const;
-
- uint64_t GetHash() const noexcept {
- // if we need to support different hash versions we can update CalculateHash to take a version number
- // and calculate any non-default versions dynamically. we only use this during kernel lookup so
- // it's not performance critical
- return hash_;
- }
-
- private:
- friend class KernelDefBuilder;
-
- // called once by KernelDefBuilder::Build
- void CalculateHash();
-
- // The operator name supported by <*this> kernel..
- std::string op_name_;
-
- // The operator since_version range supported by <*this> kernel.
- // A kernel could support an operator definition between <op_since_version_start>
- // and <op_since_version_end> (inclusive).
- int op_since_version_start_ = 1;
- int op_since_version_end_ = INT_MAX;
-
- // The operator domain supported by <*this> kernel.
- // Default to 'onnxruntime::kOnnxDomain'.
- // Please note the behavior of std::string("") and std::string() are different
- std::string op_domain_;
-
- // The type of the execution provider.
- std::string provider_type_;
-
- // The supported data types for inputs/outputs.
- // Key is input/output name defined in op schema, Value are supported types.
- // note: std::map as we need the order to be deterministic for the hash
- std::map<std::string, std::vector<MLDataType>> type_constraints_;
-
- // An element <i, j> means that output j reuses the memory of input i.
- std::vector<std::pair<int, int>> inplace_map_;
-
- // An element <i, j> means that output j is an alias of input i.
- std::vector<std::pair<int, int>> alias_map_;
-
- // This variable stores <input_offset, output_offset> for the variadic alias mapping
- // output 'i + output_offset' is an alias of input 'i + input_offset' for all i >= 0
- optional<std::pair<int, int>> variadic_alias_offsets_;
-
- // Require input tensors to be allocated contiguously.
- bool allocate_inputs_contiguously_ = false;
-
- // The memory types of inputs/outputs of this kernel
- MemTypeMap input_memory_type_args_;
- MemTypeMap output_memory_type_args_;
-
- // execution command queue id, 0 for default queue in execution provider
- int exec_queue_id_ = 0;
- // Default memory type for all inputs
- OrtMemType default_inputs_mem_type_{OrtMemTypeDefault};
- // Default memory type for all outputs
- OrtMemType default_outputs_mem_type_{OrtMemTypeDefault};
-
- // hash of kernel definition for lookup in minimal build
- uint64_t hash_ = 0;
-};
-
-class KernelDefBuilder {
- public:
- explicit KernelDefBuilder()
- : kernel_def_(new KernelDef()) {}
-
- KernelDefBuilder& SetName(const std::string& op_name);
- KernelDefBuilder& SetName(const char* op_name);
-
- KernelDefBuilder& SetDomain(const std::string& domain);
- KernelDefBuilder& SetDomain(const char* domain);
-
- /**
- This kernel supports operator definition since <since_version> (to latest).
- */
- KernelDefBuilder& SinceVersion(int since_version) {
- kernel_def_->op_since_version_start_ = since_version;
- return *this;
- }
-
- /**
- The start and end version should be set accordingly per version range for
- each domain registered in OpSchemaRegistry::DomainToVersionRange in
- \onnxruntime\onnxruntime\core\graph\op.h as below.
- Key: domain. Value: <lowest version, highest version> pair.
- std::unordered_map<std::string, std::pair<int, int>> map_;
- */
- KernelDefBuilder& SinceVersion(int since_version_start, int since_version_end) {
- kernel_def_->op_since_version_start_ = since_version_start;
- kernel_def_->op_since_version_end_ = since_version_end;
- return *this;
- }
-
- /**
- The execution provider type of the kernel.
- */
- KernelDefBuilder& Provider(onnxruntime::ProviderType provider_type);
- KernelDefBuilder& Provider(const char* provider_type);
-
- /**
- Specify the set of types that this kernel supports. A further restriction
- of the set of types specified in the op schema.
- The arg name could be either op formal parameter name, say "X", or type
- argument name specified in op schema, say "T".
- */
- KernelDefBuilder& TypeConstraint(const std::string& arg_name,
- const std::vector<MLDataType>& supported_types);
- KernelDefBuilder& TypeConstraint(const char* arg_name,
- const std::vector<MLDataType>& supported_types);
-
- /**
- Like TypeConstraint but supports just a single type.
- */
- KernelDefBuilder& TypeConstraint(const std::string& arg_name, MLDataType supported_type);
- KernelDefBuilder& TypeConstraint(const char* arg_name, MLDataType supported_type);
-
- /**
- Inplace mapping from inputs to outputs allowed.
- It means that uplayer runtime could do memory in-place optimization
- as it will not impact the correctness of this kernel.
- */
- KernelDefBuilder& MayInplace(const std::vector<std::pair<int, int>>& inplaces);
- KernelDefBuilder& MayInplace(int input_index, int output_index);
-
- /**
- Alias mapping from inputs to outputs. Different from Inplace that the
- content of the tensor is not changed. This is to take care of operators
- such as Identity and Reshape.
- */
- KernelDefBuilder& Alias(const std::vector<std::pair<int, int>>& aliases);
- KernelDefBuilder& Alias(int input_index, int output_index);
-
- /**
- Apply variadic number of alias mapping from inputs to outputs.
- This is effectively applying Alias(i + input_offset, i + output_offset) for i >= 0
- */
- KernelDefBuilder& VariadicAlias(int input_offset, int output_offset);
-
- /**
- Specify that this kernel requires input tensors to be allocated
- contiguously. This allows kernels to execute as a single large
- computation, rather than numerous smaller computations.
- */
- KernelDefBuilder& AllocateInputsContiguously() {
- kernel_def_->allocate_inputs_contiguously_ = true;
- return *this;
- }
-
- /**
- Specify that this kernel requires an input arg
- in certain memory type (instead of the default, device memory).
- */
- template <OrtMemType T>
- KernelDefBuilder& InputMemoryType(int input_index) {
- kernel_def_->input_memory_type_args_.insert(std::make_pair(input_index, T));
- return *this;
- }
-
- KernelDefBuilder& InputMemoryType(OrtMemType type, int input_index) {
- kernel_def_->input_memory_type_args_.insert(std::make_pair(input_index, type));
- return *this;
- }
-
- /**
- Specify that this kernel requires input arguments
- in certain memory type (instead of the default, device memory).
- */
- template <OrtMemType T>
- KernelDefBuilder& InputMemoryType(const std::vector<int>& input_indexes) {
- for (auto input_index : input_indexes) {
- kernel_def_->input_memory_type_args_.insert(std::make_pair(input_index, T));
- }
- return *this;
- }
-
- /**
- Specify that this kernel provides an output arg
- in certain memory type (instead of the default, device memory).
- */
- template <OrtMemType T>
- KernelDefBuilder& OutputMemoryType(int output_index) {
- kernel_def_->output_memory_type_args_.insert(std::make_pair(output_index, T));
- return *this;
- }
-
- KernelDefBuilder& OutputMemoryType(OrtMemType type, int output_index) {
- kernel_def_->output_memory_type_args_.insert(std::make_pair(output_index, type));
- return *this;
- }
-
- /**
- Specify that this kernel provides an output arguments
- in certain memory type (instead of the default, device memory).
- */
- template <OrtMemType T>
- KernelDefBuilder& OutputMemoryType(const std::vector<int>& output_indexes) {
- for (auto output_index : output_indexes) {
- kernel_def_->output_memory_type_args_.insert(std::make_pair(output_index, T));
- }
- return *this;
- }
-
- /**
- Specify that this kernel runs on which execution queue in the provider
- */
- KernelDefBuilder& ExecQueueId(int queue_id) {
- kernel_def_->exec_queue_id_ = queue_id;
- return *this;
- }
-
- /**
- Specify the default inputs memory type, if not specified, it is DefaultMemory
- */
- KernelDefBuilder& SetDefaultInputsMemoryType(OrtMemType mem_type) {
- kernel_def_->default_inputs_mem_type_ = mem_type;
- return *this;
- }
-
- /**
- Specify the default outputs memory type, if not specified, it is DefaultMemory
- */
- KernelDefBuilder& SetDefaultOutputMemoryType(OrtMemType mem_type) {
- kernel_def_->default_outputs_mem_type_ = mem_type;
- return *this;
- }
-
- /**
- Return the kernel definition, passing ownership of the KernelDef to the caller
- */
- std::unique_ptr<KernelDef> Build() {
- kernel_def_->CalculateHash();
- return std::move(kernel_def_);
- }
-
- private:
- // we own the KernelDef until Build() is called.
- std::unique_ptr<KernelDef> kernel_def_;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/kernel_registry.h b/include/onnxruntime/core/framework/kernel_registry.h
deleted file mode 100755
index 0542183..0000000
--- a/include/onnxruntime/core/framework/kernel_registry.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/framework/op_kernel.h"
-
-namespace onnxruntime {
-/**
- * Each provider has a KernelRegistry. Often, the KernelRegistry only belongs to that specific provider.
- *
- */
-class KernelRegistry {
- public:
- KernelRegistry() = default;
-
- // Register a kernel with kernel definition and function to create the kernel.
- Status Register(KernelDefBuilder& kernel_def_builder, const KernelCreateFn& kernel_creator) ORT_MUST_USE_RESULT;
-
- Status Register(KernelCreateInfo&& create_info) ORT_MUST_USE_RESULT;
-
-#if !defined(ORT_MINIMAL_BUILD)
- static bool HasImplementationOf(const KernelRegistry& r, const onnxruntime::Node& node,
- onnxruntime::ProviderType exec_provider) {
- const KernelCreateInfo* info;
- Status st = r.TryFindKernel(node, exec_provider, &info);
- return st.IsOK();
- }
-
- // factory functions should always return a unique_ptr for maximum flexibility
- // for its clients unless the factory is managing the lifecycle of the pointer
- // itself.
- // TODO(Task:132) Make usage of unique_ptr/shared_ptr as out param consistent
- Status TryCreateKernel(const onnxruntime::Node& node, const IExecutionProvider& execution_provider,
- const std::unordered_map<int, OrtValue>& constant_initialized_tensors,
- const OrtValueNameIdxMap& mlvalue_name_idx_map, const FuncManager& funcs_mgr,
- const DataTransferManager& data_transfer_mgr,
- std::unique_ptr<OpKernel>& op_kernel) const ORT_MUST_USE_RESULT;
-
- // Check if an execution provider can create kernel for a node and return the kernel if so
- Status TryFindKernel(const onnxruntime::Node& node, onnxruntime::ProviderType exec_provider,
- const KernelCreateInfo** out) const;
-
-#endif
-
- // Check if an execution provider can create kernel for a node and return the kernel if so.
- // Kernel matching is via kernel_def_hash.
- Status TryFindKernel(const onnxruntime::Node& node, onnxruntime::ProviderType exec_provider,
- uint64_t kernel_def_hash,
- const KernelCreateInfo** out) const;
-
- bool IsEmpty() const { return kernel_creator_fn_map_.empty(); }
-
-#ifdef onnxruntime_PYBIND_EXPORT_OPSCHEMA
- // This is used by the opkernel doc generator to enlist all registered operators for a given provider's opkernel
- const KernelCreateMap& GetKernelCreateMap() const {
- return kernel_creator_fn_map_;
- }
-#endif
-
- private:
-#if !defined(ORT_MINIMAL_BUILD)
- // Check whether the types of inputs/outputs of the given node match the extra
- // type-constraints of the given kernel. This serves two purposes: first, to
- // select the right kernel implementation based on the types of the arguments
- // when we have multiple kernels, e.g., Clip<float> and Clip<int>; second, to
- // accommodate (and check) mapping of ONNX (specification) type to the onnxruntime
- // implementation type (e.g., if we want to implement ONNX's float16 as a regular
- // float in onnxruntime). (The second, however, requires a globally uniform mapping.)
- //
- // Note that this is not intended for type-checking the node against the ONNX
- // type specification of the corresponding op, which is done before this check.
- //
- // if this function is called before graph partition, then node.provider is not set.
- // In this case, kernel_def.provider must equal to exec_provider
- // otherwise, kernel_def.provider must equal to node.provider. exec_provider is ignored.
- static bool VerifyKernelDef(const onnxruntime::Node& node,
- const KernelDef& kernel_def,
- std::string& error_str);
-#endif
-
- static std::string GetMapKey(const std::string& op_name, const std::string& domain, const std::string& provider) {
- std::string key(op_name);
- key.append(1, ' ').append(domain.empty() ? kOnnxDomainAlias : domain).append(1, ' ').append(provider);
- return key;
- }
-
- static std::string GetMapKey(const KernelDef& kernel_def) {
- return GetMapKey(kernel_def.OpName(), kernel_def.Domain(), kernel_def.Provider());
- }
- // Kernel create function map from op name to kernel creation info.
- // key is opname+domain_name+provider_name
- KernelCreateMap kernel_creator_fn_map_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/ml_value.h b/include/onnxruntime/core/framework/ml_value.h
deleted file mode 100755
index 27ffa58..0000000
--- a/include/onnxruntime/core/framework/ml_value.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <string>
-#include "core/common/common.h"
-#include "core/common/exceptions.h"
-#include "core/framework/allocator.h"
-#include "core/framework/data_types.h"
-#include "core/framework/tensor.h"
-
-namespace onnxruntime {
-class SparseTensor;
-class TensorSeq;
-} // namespace onnxruntime
-
-/**
- Represents both tensors and non-tensors.
-*/
-struct OrtValue {
- public:
- OrtValue() : data_(nullptr) {}
- ~OrtValue() = default;
-
- OrtValue(void* pData, onnxruntime::MLDataType type, onnxruntime::DeleteFunc deleter) {
- Init(pData, type, deleter);
- }
-
- void Init(void* pData, onnxruntime::MLDataType type, onnxruntime::DeleteFunc deleter) {
- data_.reset(pData, deleter);
- type_ = type;
- }
-
- bool IsAllocated() const {
- return data_ && type_;
- }
-
- template <typename T>
- const T& Get() const {
- ORT_ENFORCE(onnxruntime::DataTypeImpl::GetType<T>() == type_, onnxruntime::DataTypeImpl::GetType<T>(), " != ", type_);
- return *static_cast<T*>(data_.get());
- }
-
- template <typename T>
- T* GetMutable() {
- ORT_ENFORCE(onnxruntime::DataTypeImpl::GetType<T>() == type_, onnxruntime::DataTypeImpl::GetType<T>(), " != ", type_);
- return static_cast<T*>(data_.get());
- }
-
- bool IsTensor() const noexcept {
- return (type_ != nullptr && type_->IsTensorType());
- }
-
- bool IsTensorSequence() const noexcept {
- return (type_ != nullptr && type_->IsTensorSequenceType());
- }
-
- bool IsSparseTensor() const noexcept {
- return (type_ != nullptr && type_->IsSparseTensorType());
- }
-
- onnxruntime::MLDataType Type() const {
- return type_;
- }
-
- onnxruntime::Fence_t Fence() const {
- return fence_.get();
- }
-
- void SetFence(onnxruntime::FencePtr fence) {
- fence_ = fence;
- }
-
- void ShareFenceWith(OrtValue& v) {
- fence_ = v.fence_;
- }
-
- private:
- std::shared_ptr<void> data_;
- onnxruntime::MLDataType type_{nullptr};
- onnxruntime::FencePtr fence_;
-};
-
-template <>
-inline const onnxruntime::Tensor& OrtValue::Get<onnxruntime::Tensor>() const {
- ORT_ENFORCE(IsTensor(), "Trying to get a Tensor, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return *static_cast<onnxruntime::Tensor*>(data_.get());
-}
-
-template <>
-inline onnxruntime::Tensor* OrtValue::GetMutable<onnxruntime::Tensor>() {
- ORT_ENFORCE(IsTensor(), "Trying to get a Tensor, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return static_cast<onnxruntime::Tensor*>(data_.get());
-}
-
-template <>
-inline const onnxruntime::TensorSeq& OrtValue::Get<onnxruntime::TensorSeq>() const {
- ORT_ENFORCE(IsTensorSequence(), "Trying to get a TensorSeq, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return *static_cast<onnxruntime::TensorSeq*>(data_.get());
-}
-
-template <>
-inline onnxruntime::TensorSeq* OrtValue::GetMutable<onnxruntime::TensorSeq>() {
- ORT_ENFORCE(IsTensorSequence(), "Trying to get a TensorSeq, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return static_cast<onnxruntime::TensorSeq*>(data_.get());
-}
-
-template <>
-inline const onnxruntime::SparseTensor& OrtValue::Get<onnxruntime::SparseTensor>() const {
- ORT_ENFORCE(IsSparseTensor(), "Trying to get a SparseTensor, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return *static_cast<onnxruntime::SparseTensor*>(data_.get());
-}
-
-template <>
-inline onnxruntime::SparseTensor* OrtValue::GetMutable<onnxruntime::SparseTensor>() {
- ORT_ENFORCE(IsSparseTensor(), "Trying to get a SparseTensor, but got: ", onnxruntime::DataTypeImpl::ToString(type_));
- return static_cast<onnxruntime::SparseTensor*>(data_.get());
-}
-
-//TODO: remove the following line
-#define MLValue OrtValue
diff --git a/include/onnxruntime/core/framework/op_kernel.h b/include/onnxruntime/core/framework/op_kernel.h
deleted file mode 100755
index 2e3937a..0000000
--- a/include/onnxruntime/core/framework/op_kernel.h
+++ /dev/null
@@ -1,484 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <functional>
-
-#include "core/common/exceptions.h"
-#include "core/common/logging/logging.h"
-#include "core/common/status.h"
-#include "core/framework/execution_provider.h"
-#include "core/framework/kernel_def_builder.h"
-#include "core/framework/ml_value.h"
-#include "core/framework/op_kernel_info.h"
-#include "core/framework/op_node_proto_helper.h"
-#include "core/framework/tensor.h"
-#include "core/framework/sparse_tensor.h"
-#include "core/graph/constants.h"
-#include "core/graph/graph_viewer.h"
-#include "core/graph/onnx_protobuf.h"
-#include "gsl/gsl"
-
-namespace onnxruntime {
-class IExecutionFrame;
-class OpKernelContext;
-class OpKernelWrapper;
-namespace concurrency {
-class ThreadPool;
-}
-
-class OpKernel {
- public:
- using DoneCallback = std::function<void()>;
-
- explicit OpKernel(const OpKernelInfo& info) : op_kernel_info_(info) {}
- virtual ~OpKernel() = default;
-
- const onnxruntime::Node& Node() const {
- return op_kernel_info_.node();
- }
-
- const onnxruntime::KernelDef& KernelDef() const {
- return op_kernel_info_.GetKernelDef();
- }
-
- virtual Status Compute(_Inout_ OpKernelContext* context) const ORT_MUST_USE_RESULT = 0;
-
- virtual Status ComputeAsync(_Inout_ OpKernelContext*, DoneCallback) const ORT_MUST_USE_RESULT {
- ORT_NOT_IMPLEMENTED(__FUNCTION__, " is not implemented");
- }
-
- // Override this function to PrePack initialized constant tensor to the format as needed.
- // For example, MatMul kernel can pack the input B if it is constant like code below.
- // Status PrePack(const Tensor& tensor, int input_idx, bool& is_packed) override {
- // is_packed = false;
- // if (input_idx == 1) {
- // this.Pack(tensor, this.buffer_);
- // is_packed = true;
- // }
- // return Status::OK();
- // }
- // Please refer to MatMulIntegerToFloatBase for a complete example
- // @param tesnor: The initialized constant tensor
- // @param input_idx: The input index of the tensor in this kernel
- // @param is_packed: Set it to true if the kernel packed the tensor or to false
- // The kernel is responsible keep the packed data and related metadata if is_packed is set to true
- // And the original intialized constant tensor will be released and not accessible anymore in Compute function.
- virtual Status PrePack(const Tensor& /*tensor*/, int /*input_idx*/, bool& is_packed) {
- is_packed = false;
- return Status::OK();
- }
-
- const OrtMemoryInfo& Allocator(int id, OrtMemType mem_type) const {
- return op_kernel_info_.GetMemoryInfo(id, mem_type);
- }
-
- const OpKernelInfo& Info() const { return op_kernel_info_; }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(OpKernel);
- OpKernelInfo op_kernel_info_;
-};
-
-class OpKernelContext {
- public:
- using ArgMap = std::unordered_map<std::string, size_t>;
-
- OpKernelContext(_Inout_ IExecutionFrame* frame, _In_ const OpKernel* kernel,
- _In_opt_ concurrency::ThreadPool* threadpool, _In_ const logging::Logger& logger);
-
- virtual ~OpKernelContext() = default;
-
- /**
- Return the number of inputs for a variadic argument.
- @param arg_num The operator argument number.
- @returns Number of inputs the argument has.
- */
- int NumVariadicInputs(size_t arg_num) const;
-
- MLDataType InputType(int index) const;
- MLDataType OutputType(int index) const;
-
- template <typename T>
- const T* Input(int index) const {
- const OrtValue* p_ml_value = GetInputMLValue(index);
- ORT_TRY {
- return p_ml_value ? &(p_ml_value->Get<T>()) : nullptr;
- }
- ORT_CATCH(const std::exception& /*e*/) {
- ORT_THROW("Missing Input: " + kernel_->Node().InputDefs()[index]->Name());
- }
- }
-
- // Fetch a required input, enforcing that it is present.
- template <typename T>
- const T& RequiredInput(int index) const {
- const T* input_ptr = Input<T>(index);
- ORT_ENFORCE(input_ptr, "Required input at index ", index, " is not present.");
- return *input_ptr;
- }
-
- // Fetch output (non-tensor) with specified index.
- template <typename T>
- T* Output(int index) {
- if (index < 0 || index >= OutputCount())
- return nullptr;
-
- OrtValue* p_ml_value = GetOrCreateOutputMLValue(index);
- return p_ml_value ? p_ml_value->GetMutable<T>() : nullptr;
- }
-
- // In the case that memory allocation has not been done for an output tensor,
- // The memory allocation will be done on-the-fly with given tensor shape.
- // Return nullptr if the output is an unused optional output.
- Tensor* Output(int index, const TensorShape& shape);
- Tensor* Output(int index, const std::vector<int64_t>& shape);
- Tensor* Output(int index, const std::initializer_list<int64_t>& shape);
-
- // Fetch a required tensor output, enforcing that it is present.
- Tensor& RequiredOutput(int index, const TensorShape& shape) {
- Tensor* output_ptr = Output(index, shape);
- ORT_ENFORCE(output_ptr, "Required output at index ", index, " is not present.");
- return *output_ptr;
- }
-
- // Fetch a sparse-tensor output corresponding to the specified index.
- // num_values must specify the number of non-zero values (commonly known as NNZ/nnz),
- // and shape must specify the shape of the underlying dense-tensor.
- // Memory allocation for the output may happen when this method is invoked,
- // unless static optimization pre-allocates it.
- SparseTensor* Output(int index, size_t num_values, const TensorShape& shape);
-
- // Retrieve indexed shape obtained from memory planning before actual
- // computation. If the indexed shape cannot be inferred, this function returns
- // false.
- bool TryGetInferredInputShape(int index, TensorShape& shape) const;
-
- // Retrieve indexed shape obtained from memory planning before actual
- // computation. If the indexed shape cannot be inferred, this function returns
- // false.
- bool TryGetInferredOutputShape(int index, TensorShape& shape) const;
-
- const logging::Logger& Logger() const {
- return *logger_;
- }
-
- // always >= 0
- int InputCount() const {
- return static_cast<int>(kernel_->Node().InputDefs().size());
- }
-
- // always >= 0
- int ImplicitInputCount() const {
- return static_cast<int>(kernel_->Node().ImplicitInputDefs().size());
- }
-
- // always >= 0
- int OutputCount() const {
- return static_cast<int>(kernel_->Node().OutputDefs().size());
- }
-
- /**
- Return an allocator on device 0, with memtype of OrtMemTypeDefault.
- @remarks Use SafeInt when calculating the size of memory to allocate using AllocatorPtr->Alloc.
- */
- Status GetTempSpaceAllocator(AllocatorPtr* output) const ORT_MUST_USE_RESULT;
-
- /**
- Return the fence of current node's input.
- @param index The index of the input.
- @returns Point to the Fence of the input OrtValue.
- It is null if the input OrtValue doesn't have fence or the input is optional.
- */
- Fence_t InputFence(int index) const;
-
- /**
- Return the fence of current node's implicit input.
- @param index The index of the implicit input.
- @returns Point to the Fence of the implicit input OrtValue.
- It is null if the input OrtValue doesn't have fence or the input is optional.
- */
- Fence_t ImplicitInputFence(int index) const;
-
- /**
- Return the fence of current node's output identifed by index.
- @param index The index of the output.
- @returns Point to the Fence of the output OrtValue.
- It is null if the output OrtValue doesn't have fence or the output is optional.
- */
- Fence_t OutputFence(int index) const;
-
- /**
- Return the device id that current kernel runs on.
- */
- int GetDeviceId() const {
- return kernel_->Info().GetExecutionProvider()->GetDeviceId();
- }
-
- /**
- Returns the opset domain of the underlying kernel
- **/
- const std::string& GetOpDomain() const;
-
- /**
- Returns the optype of the underlying kernel
- **/
- const std::string& GetOpType() const;
-
- /**
- Returns the node name of the underlying kernel
- **/
- const std::string& GetNodeName() const;
-
- /**
- Returns the intra-op threadpool, if available.
- */
- _Ret_maybenull_ onnxruntime::concurrency::ThreadPool* GetOperatorThreadPool() const { return threadpool_; }
-
- /**
- Returns whether deterministic computation is preferred.
- */
- virtual bool GetUseDeterministicCompute() const {
- return true;
- }
-
- protected:
- onnxruntime::NodeIndex GetNodeIndex() const;
-
- const OrtValue* GetInputMLValue(int index) const;
- const OrtValue* GetImplicitInputMLValue(int index) const;
- OrtValue* GetOutputMLValue(int index);
-
- // Creates the OrtValue* based on the shape, if it does not exist
- // The parameter nnz is used only for sparse-tensors and indicates the
- // number of non-zero values (the number of elements in the values buffer allocated).
- OrtValue* OutputMLValue(int index, const TensorShape& shape, size_t nnz = 0);
-
- private:
- ORT_DISALLOW_COPY_AND_ASSIGNMENT(OpKernelContext);
-
- OrtValue* GetOrCreateOutputMLValue(int index);
-
- int GetInputArgIndex(int index) const;
- int GetImplicitInputArgIndex(int index) const;
- int GetOutputArgIndex(int index) const;
-
- IExecutionFrame* const execution_frame_;
- const OpKernel* const kernel_;
- concurrency::ThreadPool* const threadpool_;
- const logging::Logger* const logger_;
-
- // The argument starting index in ExecutionFrame.
- int node_input_start_index_{-1};
- int node_implicit_input_start_index_{-1};
- int node_output_start_index_{-1};
-};
-
-// Fetching output tensor without shape is not allowed except when it already exists
-template <>
-inline Tensor* OpKernelContext::Output<Tensor>(int index) {
- OrtValue* p_ml_value = GetOutputMLValue(index);
- ORT_ENFORCE(p_ml_value, "Please fetch output tensor with specified shape.");
- return p_ml_value->GetMutable<Tensor>();
-}
-
-using KernelCreateFn = std::function<OpKernel*(const OpKernelInfo& info)>;
-using KernelCreatePtrFn = std::add_pointer<OpKernel*(const OpKernelInfo& info)>::type;
-
-struct KernelCreateInfo {
- std::unique_ptr<KernelDef> kernel_def; // Owned and stored in the global kernel registry.
- KernelCreateFn kernel_create_func;
- Status status;
-
- KernelCreateInfo(std::unique_ptr<KernelDef> definition,
- KernelCreateFn create_func)
- : kernel_def(std::move(definition)),
- kernel_create_func(create_func) {}
-
- KernelCreateInfo(KernelCreateInfo&& other) noexcept
- : kernel_def(std::move(other.kernel_def)),
- kernel_create_func(std::move(other.kernel_create_func)) {}
-
- KernelCreateInfo() = default;
-};
-
-using KernelCreateMap = std::multimap<std::string, KernelCreateInfo>;
-
-// Forward declarations for the non-specialized BuildKernelCreateInfo method.
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-
-namespace ml {
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-} // namespace ml
-
-namespace contrib {
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-} // namespace contrib
-
-namespace featurizers {
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-} // namespace featurizers
-
-namespace contrib {
-namespace cuda {
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-} // namespace cuda
-} // namespace contrib
-
-namespace contrib {
-namespace rocm {
-template <typename T>
-KernelCreateInfo BuildKernelCreateInfo();
-} // namespace rocm
-} // namespace contrib
-
-using BuildKernelCreateInfoFn = KernelCreateInfo (*)();
-
-// Naming convention for operator kernel classes
-#define ONNX_OPERATOR_KERNEL_CLASS_NAME(provider, domain, ver, name) \
- provider##_##name##_##domain##_ver##ver
-
-#define ONNX_CPU_OPERATOR_KERNEL(name, ver, builder, ...) \
- ONNX_OPERATOR_KERNEL_EX(name, kOnnxDomain, ver, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_ML_KERNEL(name, ver, builder, ...) \
- ONNX_OPERATOR_KERNEL_EX(name, kMLDomain, ver, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_OPERATOR_KERNEL_EX(name, domain, ver, provider, builder, ...) \
- class ONNX_OPERATOR_KERNEL_CLASS_NAME(provider, domain, ver, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_KERNEL_CLASS_NAME(provider, domain, ver, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(ver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-#define ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name) \
- provider##_##name##_##domain##_ver##startver##_##endver
-
-#define ONNX_CPU_OPERATOR_VERSIONED_KERNEL(name, startver, endver, builder, ...) \
- ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, kOnnxDomain, startver, endver, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_VERSIONED_ML_KERNEL(name, startver, endver, builder, ...) \
- ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, kMLDomain, startver, endver, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_OPERATOR_VERSIONED_KERNEL_EX(name, domain, startver, endver, provider, builder, ...) \
- class ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_KERNEL_CLASS_NAME(provider, domain, startver, endver, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(startver, endver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-#define ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name) \
- provider##_##name##_##domain##_ver##ver##_##type
-
-#define ONNX_CPU_OPERATOR_TYPED_KERNEL(name, ver, type, builder, ...) \
- ONNX_OPERATOR_TYPED_KERNEL_EX(name, kOnnxDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_TYPED_ML_KERNEL(name, ver, type, builder, ...) \
- ONNX_OPERATOR_TYPED_KERNEL_EX(name, kMLDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_TYPED_MS_KERNEL(name, ver, type, builder, ...) \
- ONNX_OPERATOR_TYPED_KERNEL_EX(name, kMSDomain, ver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_OPERATOR_TYPED_KERNEL_EX(name, domain, ver, type, provider, builder, ...) \
- class ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(ver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-#define ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name) \
- provider##_##name##_##domain##_ver##ver##_##type1##_##type2
-
-#define ONNX_OPERATOR_TWO_TYPED_KERNEL_EX(name, domain, ver, type1, type2, provider, builder, ...) \
- class ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, ver, type1, type2, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(ver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-#define ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type, name) \
- provider##_##name##_##domain##_ver##startver##_##endver##_##type
-
-#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_KERNEL(name, startver, endver, type, builder, ...) \
- ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kOnnxDomain, startver, endver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_ML_KERNEL(name, startver, endver, type, builder, ...) \
- ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kMLDomain, startver, endver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_CPU_OPERATOR_VERSIONED_TYPED_MS_KERNEL(name, startver, endver, type, builder, ...) \
- ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, kMSDomain, startver, endver, type, kCpuExecutionProvider, builder, __VA_ARGS__)
-
-#define ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX(name, domain, startver, endver, type, provider, builder, ...) \
- class ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(startver, endver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-#define ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type1, type2, name) \
- provider##_##name##_##domain##_ver##startver##_##endver##_##type1##_##type2
-
-#define ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_EX(name, domain, startver, endver, type1, type2, provider, builder, ...) \
- class ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type1, type2, name); \
- template <> \
- KernelCreateInfo \
- BuildKernelCreateInfo<ONNX_OPERATOR_VERSIONED_TWO_TYPED_KERNEL_CLASS_NAME(provider, domain, startver, endver, type1, type2, name)>() { \
- return KernelCreateInfo( \
- builder.SetName(#name) \
- .SetDomain(domain) \
- .SinceVersion(startver, endver) \
- .Provider(provider) \
- .Build(), \
- static_cast<KernelCreatePtrFn>([](const OpKernelInfo& info) -> OpKernel* { return new __VA_ARGS__(info); })); \
- }
-
-// Use within macro definitions to create a custom vector of constraints.
-// Example: #define REG_KERNEL(OP, VERSION, KERNEL_CLASS, Type, ...)
-// .TypeConstraint("T", BuildKernelDefConstraints<Type, __VA_ARGS_>())
-template <typename T, typename... Types>
-inline std::vector<MLDataType> BuildKernelDefConstraints() {
- return {DataTypeImpl::GetTensorType<T>(), DataTypeImpl::GetTensorType<Types>()...};
-}
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/op_kernel_info.h b/include/onnxruntime/core/framework/op_kernel_info.h
deleted file mode 100755
index 40b8c9a..0000000
--- a/include/onnxruntime/core/framework/op_kernel_info.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/framework/execution_provider.h"
-#include "core/framework/kernel_def_builder.h"
-#include "core/framework/ml_value.h"
-#include "core/framework/op_node_proto_helper.h"
-#include "core/graph/graph_viewer.h"
-#include "gsl/gsl"
-
-namespace onnxruntime {
-
-class OrtValueNameIdxMap;
-class FuncManager;
-class DataTransferManager;
-
-// A very light-weight class, which works as an aggregated
-// view of all data needed for constructing a Kernel instance.
-// NOTE: it does not own/hold any objects.
-class OpKernelInfo : public OpNodeProtoHelper<ProtoHelperNodeContext> {
- public:
- explicit OpKernelInfo(const onnxruntime::Node& node,
- const KernelDef& kernel_def,
- const IExecutionProvider& execution_provider,
- const std::unordered_map<int, OrtValue>& constant_initialized_tensors,
- const OrtValueNameIdxMap& mlvalue_name_idx_map,
- const FuncManager& funcs_mgr,
- const DataTransferManager& data_transfer_mgr);
-
- OpKernelInfo(const OpKernelInfo& other);
-
- const OrtMemoryInfo& GetMemoryInfo(int device_id, OrtMemType mem_type) const;
-
- AllocatorPtr GetAllocator(int device_id, OrtMemType mem_type) const;
-
- const KernelDef& GetKernelDef() const;
-
- const IExecutionProvider* GetExecutionProvider() const noexcept;
-
- const DataTransferManager& GetDataTransferManager() const noexcept;
-
- const onnxruntime::Node& node() const noexcept;
-
- bool TryGetConstantInput(int input_index, const Tensor** constant_input_value) const;
-
- common::Status GetFusedFuncs(NodeComputeInfo*& compute_info) const;
-
- private:
- ORT_DISALLOW_MOVE(OpKernelInfo);
- ORT_DISALLOW_ASSIGNMENT(OpKernelInfo);
-
- const onnxruntime::Node& node_;
- const KernelDef& kernel_def_;
- // For non cpu/cuda case, this pointer should be set so that function kernel
- // will delegate kernel compute call to <execution_provider> compute call.
- gsl::not_null<const ::onnxruntime::IExecutionProvider*> execution_provider_;
- const std::unordered_map<int, OrtValue>& constant_initialized_tensors_;
- const OrtValueNameIdxMap& ort_value_name_idx_map_;
- const FuncManager& funcs_mgr_;
- const DataTransferManager& data_transfer_mgr_;
- ProtoHelperNodeContext proto_helper_context_;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/op_node_proto_helper.h b/include/onnxruntime/core/framework/op_node_proto_helper.h
deleted file mode 100755
index 7443459..0000000
--- a/include/onnxruntime/core/framework/op_node_proto_helper.h
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/status.h"
-#include "core/graph/graph_viewer.h"
-#include "gsl/gsl"
-
-#ifdef __has_attribute
-#define ORT_HAVE_ATTRIBUTE(x) __has_attribute(x)
-#else
-#define ORT_HAVE_ATTRIBUTE(x) 0
-#endif
-
-#if ORT_HAVE_ATTRIBUTE(nodiscard)
-#define MUST_USE_RESULT [[nodiscard]]
-#elif defined(__clang__) && ORT_HAVE_ATTRIBUTE(warn_unused_result)
-#define MUST_USE_RESULT __attribute__((warn_unused_result))
-#else
-#define MUST_USE_RESULT
-#endif
-
-class IMLOpKernel;
-
-namespace onnxruntime {
-
-/**
- A set of wrappers with common signatures for use with both OpKernelInfo
- (as its base class) and InferenceContext. Used by ABI kernels for both
- shape / type inference and kernel construction
-*/
-template <class Impl_t>
-class OpNodeProtoHelper {
- public:
- explicit OpNodeProtoHelper(const Impl_t* impl) : impl_(impl) {}
-
- /**
- Get a single attribute
- Call this function for a required attribute or when a default value for an optional attribute is specified in the op schema
- */
- template <typename T>
- MUST_USE_RESULT Status GetAttr(const std::string& name, T* value) const;
-
- /**
- Get a single attribute
- Call this function only when a default value for an optional attribute isn't specified in the op schema
- */
- template <typename T>
- T GetAttrOrDefault(const std::string& name, const T& default_value) const {
- T tmp;
- return GetAttr<T>(name, &tmp).IsOK() ? tmp : default_value;
- }
-
- /**
- Get a single attribute
- Call this function only when a default value for an optional attribute isn't specified in the op schema
- */
- template <typename T>
- void GetAttrOrDefault(const std::string& name, T* value, const T& default_value) const {
- if (!GetAttr<T>(name, value).IsOK())
- *value = default_value;
- }
-
- /**
- Get repeated attributes
- Call this function only when a default value for an optional attribute isn't specified in the op schema
- */
- template <typename T>
- MUST_USE_RESULT std::vector<T> GetAttrsOrDefault(const std::string& name, const std::vector<T>& default_value = std::vector<T>{}) const {
- std::vector<T> tmp;
- return GetAttrs<T>(name, tmp).IsOK() ? tmp : default_value;
- }
-
- /**
- Get repeated attributes
- */
- template <typename T>
- MUST_USE_RESULT Status GetAttrs(const std::string& name, std::vector<T>& values) const;
-
- template <typename T>
- MUST_USE_RESULT Status GetAttrs(const std::string& name, gsl::span<T> values) const;
-
- /// <summary>
- /// Return a gsl::span that points to an array of primitive types held by AttributeProto
- /// This function allows to avoid copying big attributes locally into a kernel and operate on
- /// AttributeProto data directly.
- ///
- /// Does not apply to strings, Tensors and Sparse Tensors that require special treatment.
- /// </summary>
- /// <typeparam name="T">Primitive type contained in the array</typeparam>
- /// <param name="name">Attribute name</param>
- /// <param name="values">Attribute data in a span, out parameter</param>
- /// <returns>Status</returns>
- template <typename T>
- MUST_USE_RESULT Status GetAttrsAsSpan(const std::string& name, gsl::span<const T>& values) const;
-
- MUST_USE_RESULT Status GetAttrsStringRefs(const std::string& name,
- std::vector<std::reference_wrapper<const std::string>>& refs) const;
-
- uint32_t GetPrimitiveAttrElementCount(ONNX_NAMESPACE::AttributeProto_AttributeType type,
- const std::string& name) const noexcept;
-
- bool HasPrimitiveAttribute(ONNX_NAMESPACE::AttributeProto_AttributeType type,
- const std::string& name) const noexcept;
-
- uint32_t GetInputCount() const {
- return gsl::narrow_cast<uint32_t>(impl_->getNumInputs());
- }
-
- uint32_t GetOutputCount() const {
- return gsl::narrow_cast<uint32_t>(impl_->getNumOutputs());
- }
-
- const ONNX_NAMESPACE::TypeProto* GetInputType(size_t index) const {
- return impl_->getInputType(index);
- }
-
- const ONNX_NAMESPACE::TypeProto* GetOutputType(size_t index) const {
- // Work around lack of a const method from the onnx InferenceContext interface
- return const_cast<Impl_t*>(impl_)->getOutputType(index);
- }
-
- // Try to query an attribute, returning nullptr if it doesn't exist
- const ONNX_NAMESPACE::AttributeProto* TryGetAttribute(const std::string& name) const {
- return impl_->getAttribute(name);
- }
-
- const ONNX_NAMESPACE::AttributeProto* GetAttribute(const std::string& name) const {
- const ONNX_NAMESPACE::AttributeProto* attr = TryGetAttribute(name);
- ORT_ENFORCE(attr != nullptr);
- return attr;
- }
-
- private:
- OpNodeProtoHelper() = delete;
- const Impl_t* impl_ = nullptr;
-};
-
-// The methods on the following class are called by OpNodeProtoHelper, implementing
-// the same signatures as InferenceContext other than const-ness.
-class ProtoHelperNodeContext {
- public:
- explicit ProtoHelperNodeContext(const onnxruntime::Node& node) : node_(node) {}
- ProtoHelperNodeContext() = delete;
-
- const ONNX_NAMESPACE::AttributeProto* getAttribute(const std::string& name) const;
- size_t getNumInputs() const;
- const ONNX_NAMESPACE::TypeProto* getInputType(size_t index) const;
- size_t getNumOutputs() const;
- const ONNX_NAMESPACE::TypeProto* getOutputType(size_t index) const;
-
- private:
- const onnxruntime::Node& node_;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/ortdevice.h b/include/onnxruntime/core/framework/ortdevice.h
deleted file mode 100755
index afc1518..0000000
--- a/include/onnxruntime/core/framework/ortdevice.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <sstream>
-
-// Struct to represent a physical device.
-struct OrtDevice {
- using DeviceType = int8_t;
- using MemoryType = int8_t;
- using DeviceId = int16_t;
-
- // Pre-defined device types.
- static const DeviceType CPU = 0;
- static const DeviceType GPU = 1; // Nvidia or AMD
- static const DeviceType FPGA = 2;
-
- struct MemType {
- // Pre-defined memory types.
- static const MemoryType DEFAULT = 0;
- static const MemoryType CUDA_PINNED = 1;
- static const MemoryType HIP_PINNED = 2;
- };
-
- constexpr OrtDevice(DeviceType device_type_, MemoryType memory_type_, DeviceId device_id_)
- : device_type(device_type_),
- memory_type(memory_type_),
- device_id(device_id_) {}
-
- constexpr OrtDevice() : OrtDevice(CPU, MemType::DEFAULT, 0) {}
-
- DeviceType Type() const {
- return device_type;
- }
-
- MemoryType MemType() const {
- return memory_type;
- }
-
- DeviceId Id() const {
- return device_id;
- }
-
- std::string ToString() const {
- std::ostringstream ostr;
- ostr << "Device:["
- << "DeviceType:" << static_cast<int>(device_type)
- << " MemoryType:" << static_cast<int>(memory_type)
- << " DeviceId:" << device_id
- << "]";
- return ostr.str();
- }
-
- private:
- // Device type.
- DeviceType device_type;
-
- // Memory type.
- MemoryType memory_type;
-
- // Device index.
- DeviceId device_id;
-};
-
-inline bool operator==(const OrtDevice& left, const OrtDevice& other) {
- return left.Id() == other.Id() && left.MemType() == other.MemType() && left.Type() == other.Type();
-}
-
-inline bool operator!=(const OrtDevice& left, const OrtDevice& other) {
- return !(left == other);
-}
diff --git a/include/onnxruntime/core/framework/ortmemoryinfo.h b/include/onnxruntime/core/framework/ortmemoryinfo.h
deleted file mode 100755
index 77df903..0000000
--- a/include/onnxruntime/core/framework/ortmemoryinfo.h
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-struct OrtMemoryInfo {
- OrtMemoryInfo() = default; // to allow default construction of Tensor
-
- // use string for name, so we could have customized allocator in execution provider.
- const char* name = nullptr;
- int id = -1;
- OrtMemType mem_type = OrtMemTypeDefault;
- OrtAllocatorType alloc_type = Invalid;
- OrtDevice device;
-
- constexpr OrtMemoryInfo(const char* name_, OrtAllocatorType type_, OrtDevice device_ = OrtDevice(), int id_ = 0,
- OrtMemType mem_type_ = OrtMemTypeDefault)
-#if ((defined(__GNUC__) && __GNUC__ > 4) || defined(__clang__))
- // this causes a spurious error in CentOS gcc 4.8 build so disable if GCC version < 5
- __attribute__((nonnull))
-#endif
- : name(name_),
- id(id_),
- mem_type(mem_type_),
- alloc_type(type_),
- device(device_) {
- }
-
- // To make OrtMemoryInfo become a valid key in std map
- bool operator<(const OrtMemoryInfo& other) const {
- if (alloc_type != other.alloc_type)
- return alloc_type < other.alloc_type;
- if (mem_type != other.mem_type)
- return mem_type < other.mem_type;
- if (id != other.id)
- return id < other.id;
-
- return strcmp(name, other.name) < 0;
- }
-
- std::string ToString() const {
- std::ostringstream ostr;
- ostr << "OrtMemoryInfo:["
- << "name:" << name
- << " id:" << id
- << " OrtMemType:" << mem_type
- << " OrtAllocatorType:" << alloc_type
- << " " << device.ToString()
- << "]";
- return ostr.str();
- }
-};
-
-inline bool operator==(const OrtMemoryInfo& left, const OrtMemoryInfo& other) {
- return left.mem_type == other.mem_type &&
- left.alloc_type == other.alloc_type &&
- left.id == other.id &&
- strcmp(left.name, other.name) == 0;
-}
-
-inline bool operator!=(const OrtMemoryInfo& lhs, const OrtMemoryInfo& rhs) { return !(lhs == rhs); }
-
-std::ostream& operator<<(std::ostream& out, const OrtMemoryInfo& info);
diff --git a/include/onnxruntime/core/framework/provider_options.h b/include/onnxruntime/core/framework/provider_options.h
deleted file mode 100755
index aab13e8..0000000
--- a/include/onnxruntime/core/framework/provider_options.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-namespace onnxruntime {
-
-// data types for execution provider options
-
-using ProviderOptions = std::unordered_map<std::string, std::string>;
-using ProviderOptionsVector = std::vector<ProviderOptions>;
-using ProviderOptionsMap = std::unordered_map<std::string, ProviderOptions>;
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/provider_options_utils.h b/include/onnxruntime/core/framework/provider_options_utils.h
deleted file mode 100755
index e326481..0000000
--- a/include/onnxruntime/core/framework/provider_options_utils.h
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <algorithm>
-#include <functional>
-#include <type_traits>
-#include <unordered_map>
-#include <vector>
-
-#include "core/common/common.h"
-#include "core/common/parse_string.h"
-#include "core/framework/provider_options.h"
-
-namespace onnxruntime {
-
-template <typename TEnum>
-using EnumNameMapping = std::vector<std::pair<TEnum, std::string>>;
-
-/**
- * Given a mapping and an enumeration value, gets the corresponding name.
- */
-template <typename TEnum>
-Status EnumToName(const EnumNameMapping<TEnum>& mapping, TEnum value, std::string& name) {
- const auto it = std::find_if(
- mapping.begin(), mapping.end(),
- [&value](const std::pair<TEnum, std::string>& entry) {
- return entry.first == value;
- });
- ORT_RETURN_IF(
- it == mapping.end(),
- "Failed to map enum value to name: ", static_cast<typename std::underlying_type<TEnum>::type>(value));
- name = it->second;
- return Status::OK();
-}
-
-template <typename TEnum>
-std::string EnumToName(const EnumNameMapping<TEnum>& mapping, TEnum value) {
- std::string name;
- ORT_THROW_IF_ERROR(EnumToName(mapping, value, name));
- return name;
-}
-
-/**
- * Given a mapping and a name, gets the corresponding enumeration value.
- */
-template <typename TEnum>
-Status NameToEnum(
- const EnumNameMapping<TEnum>& mapping, const std::string& name, TEnum& value) {
- const auto it = std::find_if(
- mapping.begin(), mapping.end(),
- [&name](const std::pair<TEnum, std::string>& entry) {
- return entry.second == name;
- });
- ORT_RETURN_IF(
- it == mapping.end(),
- "Failed to map enum name to value: ", name);
- value = it->first;
- return Status::OK();
-}
-
-template <typename TEnum>
-TEnum NameToEnum(const EnumNameMapping<TEnum>& mapping, const std::string& name) {
- TEnum value;
- ORT_THROW_IF_ERROR(NameToEnum(mapping, name, value));
- return value;
-}
-
-class ProviderOptionsParser {
- public:
- /**
- * Adds a parser for a particular provider option value.
- *
- * @param name The provider option name.
- * @param value_parser An object that parses the option value.
- * It should be callable with the following signature and return
- * whether the parsing was successful:
- * Status value_parser(const std::string&)
- *
- * @return The current ProviderOptionsParser instance.
- */
- template <typename ValueParserType>
- ProviderOptionsParser& AddValueParser(
- const std::string& name, ValueParserType value_parser) {
- ORT_ENFORCE(
- value_parsers_.emplace(name, ValueParser{value_parser}).second,
- "Provider option \"", name, "\" already has a value parser.");
- return *this;
- }
-
- /**
- * Adds a parser for a particular provider option value which converts a
- * value to the right type and assigns it to the given reference.
- *
- * IMPORTANT: This function stores a reference to the destination variable.
- * The caller must ensure that the reference is valid when Parse() is called!
- *
- * @param name The provider option name.
- * @param dest The destination variable reference.
- *
- * @return The current ProviderOptionsParser instance.
- */
- template <typename ValueType>
- ProviderOptionsParser& AddAssignmentToReference(
- const std::string& name, ValueType& dest) {
- return AddValueParser(
- name,
- [&dest](const std::string& value_str) -> Status {
- return ParseStringWithClassicLocale(value_str, dest);
- });
- }
-
- /**
- * Adds a parser for a particular provider option value which maps an
- * enumeration name to a value and assigns it to the given reference.
- *
- * IMPORTANT: This function stores references to the mapping and destination
- * variables. The caller must ensure that the references are valid when
- * Parse() is called!
- *
- * @param name The provider option name.
- * @param mapping The enumeration value to name mapping.
- * @param dest The destination variable reference.
- *
- * @return The current ProviderOptionsParser instance.
- */
- template <typename EnumType>
- ProviderOptionsParser& AddAssignmentToEnumReference(
- const std::string& name, const EnumNameMapping<EnumType>& mapping, EnumType& dest) {
- return AddValueParser(
- name,
- [&mapping, &dest](const std::string& value_str) -> Status {
- return NameToEnum(mapping, value_str, dest);
- });
- }
-
- /**
- * Parses the given provider options.
- */
- Status Parse(const ProviderOptions& options) const {
- for (const auto& option : options) {
- const auto& name = option.first;
- const auto& value_str = option.second;
-
- const auto value_parser_it = value_parsers_.find(name);
- ORT_RETURN_IF(
- value_parser_it == value_parsers_.end(),
- "Unknown provider option: \"", name, "\".");
-
- const auto parse_status = value_parser_it->second(value_str);
- ORT_RETURN_IF_NOT(
- parse_status.IsOK(),
- "Failed to parse provider option \"", name, "\": ", parse_status.ErrorMessage());
- }
-
- return Status::OK();
- }
-
- private:
- using ValueParser = std::function<Status(const std::string&)>;
- std::unordered_map<std::string, ValueParser> value_parsers_;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/provider_shutdown.h b/include/onnxruntime/core/framework/provider_shutdown.h
deleted file mode 100755
index 7488f12..0000000
--- a/include/onnxruntime/core/framework/provider_shutdown.h
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-void UnloadSharedProviders();
-}
diff --git a/include/onnxruntime/core/framework/run_options.h b/include/onnxruntime/core/framework/run_options.h
deleted file mode 100755
index 85f6e2f..0000000
--- a/include/onnxruntime/core/framework/run_options.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <string>
-#include <atomic>
-#include "core/session/onnxruntime_c_api.h"
-
-/**
- * Configuration information for a Run call.
- */
-struct OrtRunOptions {
- /// Log severity. See https://github.com/microsoft/onnxruntime/blob/master/include/onnxruntime/core/common/logging/severity.h
- /// Default = -1 (use the log severity from the InferenceSession that the Run is for).
- int run_log_severity_level = -1;
- int run_log_verbosity_level = 0; ///< VLOG level if debug build and run_log_severity_level is 0 (VERBOSE).
- std::string run_tag; ///< A tag for the Run() calls using this.
-
- // Set to 'true' to ensure the termination of all the outstanding Run() calls
- // that use this OrtRunOptions instance. Some of the outstanding Run() calls may
- // be forced to terminate with an error status.
- bool terminate = false;
-
- // Set to 'true' to run only the nodes from feeds to required fetches.
- // So it is possible that only some of the nodes are executed.
- bool only_execute_path_to_fetches = false;
-
-#ifdef ENABLE_TRAINING
- // Set to 'true' to run in training mode.
- bool training_mode = true;
-#endif
-
- OrtRunOptions() = default;
- ~OrtRunOptions() = default;
-};
-
-namespace onnxruntime {
-using RunOptions = OrtRunOptions;
-}
diff --git a/include/onnxruntime/core/framework/sparse_tensor.h b/include/onnxruntime/core/framework/sparse_tensor.h
deleted file mode 100755
index ec0abb9..0000000
--- a/include/onnxruntime/core/framework/sparse_tensor.h
+++ /dev/null
@@ -1,72 +0,0 @@
-#pragma once
-
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "core/framework/data_types.h"
-#include "core/framework/tensor_shape.h"
-#include "core/framework/tensor.h"
-
-namespace onnxruntime {
-
-/**
- * @brief This class implements SparseTensor.
- * We represent a SparseTensor as a triple <values, indices, shape>. "values" and "indices" themselves
- * are implemented as Tensors.
- * We follow the Tensor design for memory ownership/management: a sparse-tensor does not own the "value"
- * or "indices" tensors.
- */
-
-class SparseTensor final {
- public:
- SparseTensor(MLDataType elt_type,
- const TensorShape& shape,
- size_t nnz,
- void* values_data,
- void* indices_data,
- const OrtMemoryInfo& memory_info);
-
- SparseTensor(MLDataType elt_type,
- const TensorShape& shape,
- size_t nnz,
- std::shared_ptr<IAllocator> allocator);
-
- ~SparseTensor() = default;
-
- // For now, disallow all copy, assignment, and move.
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(SparseTensor);
-
- // Returns the number of entries in the values tensor (aka "NNZ" or "number of nonzero values")
- size_t NumValues() const { return static_cast<size_t>(values_.Shape().Size()); }
-
- const Tensor& Values() const {
- return values_;
- }
-
- const Tensor& Indices() const {
- return indices_;
- }
-
- const TensorShape& Shape() const {
- return shape_;
- }
-
- Tensor& MutableValues() {
- return values_;
- }
-
- Tensor& MutableIndices() {
- return indices_;
- }
-
- //TensorShape& MutableShape() {
- // return shape_;
- //}
-
- private:
- Tensor values_;
- Tensor indices_;
- TensorShape shape_; // The shape of corresponding dense-tensor.
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/tensor.h b/include/onnxruntime/core/framework/tensor.h
deleted file mode 100755
index 5c67796..0000000
--- a/include/onnxruntime/core/framework/tensor.h
+++ /dev/null
@@ -1,246 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <stddef.h>
-#include <iostream>
-#include <string>
-#include <vector>
-
-#include "gsl/gsl"
-#include "core/common/common.h"
-#include "core/framework/allocator.h"
-#include "core/framework/tensor_shape.h"
-#include "onnxruntime_config.h"
-#include "core/framework/data_types.h"
-#include "core/framework/data_types_internal.h"
-
-namespace onnxruntime {
-// TODO: Do we need this class or is IAllocator::MakeUniquePtr sufficient/better
-class BufferDeleter {
- public:
- BufferDeleter() : alloc_(nullptr) {}
- BufferDeleter(AllocatorPtr alloc)
- : alloc_(alloc) {}
-
- void operator()(void* p) const {
- if (alloc_)
- alloc_->Free(p);
- }
-
- private:
- // TODO: we may need consider the lifetime of alloc carefully
- // The alloc_ here is the allocator that used to allocate the buffer
- // And need go with the unique_ptr together. If it is using our internal
- // allocator, it is ok as our allocators are global managed. But if it
- // is provide by user, user need to be very careful about it.
- // A weak_ptr may be a choice to reduce the impact, but that require to
- // change our current allocator mgr to use shared_ptr. Will revisit it
- // later.
- AllocatorPtr alloc_;
-};
-
-using BufferUniquePtr = std::unique_ptr<void, BufferDeleter>;
-using BufferNakedPtr = void*;
-//TODO:ensure dtype_!=nullptr
-#ifdef __GNUC__
-#pragma GCC diagnostic push
-#ifdef HAS_NULL_DEREFERENCE
-#pragma GCC diagnostic ignored "-Wnull-dereference"
-#endif
-#endif
-/*
- We want to keep tensor as simple as possible, it is just a placeholder
- for a piece of memory, with additional shape information.
- Memory is owned and managed by Executor / Workspace, so Tensor just uses
- it, and won't do any allocation / release.
-*/
-class Tensor final {
- public:
- Tensor() = default; // to allow creating vector<Tensor> to support seq(tensor)
-
- /**
- * Create tensor with given type, shape, pre-allocated memory and allocator info.
- * This function won't check if the preallocated buffer(p_data) has enough room for the shape.
- * \param data A preallocated buffer. Can be NULL if the shape is empty.
- * Tensor does not own the data and will not delete it
- * \param alloc Where the buffer('data') was allocated from
- * \param offset Offset in bytes to start of Tensor within p_data.
- */
- Tensor(MLDataType p_type, const TensorShape& shape, void* p_data, const OrtMemoryInfo& alloc,
- ptrdiff_t offset = 0);
-
- /**
- * Deprecated. The orginal design is this Tensor class won't do any allocation / release.
- * However, this function will allocate the buffer for the shape, and do placement new if p_type is string tensor.
- */
- Tensor(MLDataType p_type, const TensorShape& shape, std::shared_ptr<IAllocator> allocator);
-
- ~Tensor();
-
- //Move is allowed
- ORT_DISALLOW_COPY_AND_ASSIGNMENT(Tensor);
-
- Tensor(Tensor&& other) noexcept;
-
- Tensor& operator=(Tensor&& other) noexcept;
-
- /**
- Returns the data type.
- */
- MLDataType DataType() const { return dtype_; }
-
- /**
- Returns the data type enum constant
- @remarks Use utils::ToTensorProtoElementType<T> for comparison.
- */
- int32_t GetElementType() const {
- return dtype_->GetDataType();
- }
-
- // Check if contains string data. This is a separate
- // interface bc it is frequently used.
- bool IsDataTypeString() const {
- return utils::IsPrimitiveDataType<std::string>(dtype_);
- }
-
- // Checks if the Tensor contains data type T
- template <class T>
- bool IsDataType() const {
- return utils::IsPrimitiveDataType<T>(dtype_);
- }
-
- /**
- Returns the shape of the tensor.
- */
- const TensorShape& Shape() const noexcept { return shape_; }
-
- /**
- Returns the location of the tensor's memory
- */
- const OrtMemoryInfo& Location() const { return alloc_info_; }
-
- /**
- May return nullptr if tensor size is zero
- */
- template <typename T>
- T* MutableData() {
- // Type check
- ORT_ENFORCE(utils::IsPrimitiveDataType<T>(dtype_), "Tensor type mismatch. ",
- "T ", "!=", dtype_);
- return reinterpret_cast<T*>(static_cast<char*>(p_data_) + byte_offset_);
- }
-
- /**
- May return nullptr if tensor size is zero
- */
- template <typename T>
- gsl::span<T> MutableDataAsSpan() {
- // Type check
- ORT_ENFORCE(utils::IsPrimitiveDataType<T>(dtype_), "Tensor type mismatch. ",
- "T ", "!=", dtype_);
- T* data = reinterpret_cast<T*>(static_cast<char*>(p_data_) + byte_offset_);
- return gsl::make_span(data, static_cast<size_t>(shape_.Size()));
- }
-
- template <typename T>
- const T* Data() const {
- // Type check
- ORT_ENFORCE(utils::IsPrimitiveDataType<T>(dtype_), "Tensor type mismatch. ",
- "T ", "!=", dtype_);
- return reinterpret_cast<const T*>(static_cast<char*>(p_data_) + byte_offset_);
- }
-
- template <typename T>
- gsl::span<const T> DataAsSpan() const {
- // Type check
- ORT_ENFORCE(utils::IsPrimitiveDataType<T>(dtype_), "Tensor type mismatch. ",
- "T ", "!=", dtype_);
- const T* data = reinterpret_cast<const T*>(static_cast<char*>(p_data_) + byte_offset_);
- return gsl::make_span(data, static_cast<typename gsl::span<T>::index_type>(shape_.Size()));
- }
-
- void* MutableDataRaw(MLDataType type) {
- ORT_ENFORCE(type == dtype_, "Tensor type mismatch.", type, "!=", dtype_);
- return static_cast<char*>(p_data_) + byte_offset_;
- }
-
- const void* DataRaw(MLDataType type) const {
- ORT_ENFORCE(type == dtype_, "Tensor type mismatch.", type, "!=", dtype_);
- return static_cast<char*>(p_data_) + byte_offset_;
- }
-
- void* MutableDataRaw() noexcept {
- return static_cast<char*>(p_data_) + byte_offset_;
- }
-
- const void* DataRaw() const noexcept {
- return static_cast<char*>(p_data_) + byte_offset_;
- }
-
- bool OwnsBuffer() const noexcept {
- return buffer_deleter_ != nullptr;
- }
-
- /**
- * Resizes the tensor without touching underlying storage.
- * This requires the total size of the tensor to remains constant.
- * @warning this function is NOT thread-safe.
- */
- inline void Reshape(const TensorShape& new_shape) {
- ORT_ENFORCE(shape_.Size() == new_shape.Size(),
- "Tensor size (" + std::to_string(shape_.Size()) +
- ") != new size (" + std::to_string(new_shape.Size()) + ")");
- shape_ = new_shape;
- }
-
- /**
- * Get the byte offset with respect to the p_data
- * @warning this is a temporary solution for reusing the buffer bigger than needed.
- * @warning use with caution - make sure you do boundary check before calling this method (see view.cc)
- */
- inline ptrdiff_t ByteOffset() const {
- return byte_offset_;
- }
-
- /**
- * Set the byte offset with respect to the p_data
- * @warning this is a temporary solution for reusing the buffer bigger than needed.
- */
- inline void SetByteOffset(ptrdiff_t byte_offset) {
- byte_offset_ = byte_offset;
- }
-
- /**
- The number of bytes of data.
- */
- size_t SizeInBytes() const;
-
- // More API methods.
- private:
- void Init(MLDataType p_type,
- const TensorShape& shape,
- void* p_raw_data,
- AllocatorPtr deleter,
- ptrdiff_t offset = 0);
-
- void ReleaseBuffer();
-
- void* p_data_;
- /**
- if buffer_deleter_ is null, it means tensor does not own the buffer.
- otherwise tensor will use the deleter to release the buffer when
- tensor is released.
- */
- AllocatorPtr buffer_deleter_;
-
- TensorShape shape_;
- const PrimitiveDataTypeBase* dtype_;
- OrtMemoryInfo alloc_info_;
- ptrdiff_t byte_offset_;
-};
-#ifdef __GNUC__
-#pragma GCC diagnostic pop
-#endif
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/framework/tensor_shape.h b/include/onnxruntime/core/framework/tensor_shape.h
deleted file mode 100755
index 9a2609b..0000000
--- a/include/onnxruntime/core/framework/tensor_shape.h
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#include <iosfwd>
-#include <vector>
-#include <algorithm>
-#include <string>
-#include <cstring>
-#include "onnxruntime_config.h"
-
-namespace onnxruntime {
-#ifdef __GNUC__
-#pragma GCC diagnostic push
-#ifdef HAS_NULL_DEREFERENCE
-#pragma GCC diagnostic ignored "-Wnull-dereference"
-#endif
-#endif
-class TensorShape : private std::vector<int64_t> {
- // TODO - Use a custom STL allocator to avoid heap allocations in the common case.
- // We use negative numbers for unknown symbolic dimension. Each negative
- // number represents a unique symbolic dimension.
- // Private inheritance is used to prevent ambiguity of element versus dimension size
- public:
- TensorShape() = default;
-
- TensorShape(const TensorShape& /*other*/) = default;
- TensorShape& operator=(const TensorShape& /*other*/) = default;
-
- TensorShape(TensorShape&& /*other*/) = default;
- TensorShape& operator=(TensorShape&& /*other*/) = default;
-
- TensorShape(const std::vector<int64_t>& dims) : std::vector<int64_t>(dims) {}
-
- TensorShape(std::vector<int64_t>&& dims) : std::vector<int64_t>(std::move(dims)) {}
-
- TensorShape(const std::initializer_list<int64_t>& dims) : std::vector<int64_t>(dims) {}
-
- TensorShape(const int64_t* dimension_sizes, size_t dimension_count);
-
- TensorShape(const std::vector<int64_t>& dims, size_t start, size_t end);
-
- /**
- Return the dimension specified by <idx>.
- */
- const int64_t& operator[](size_t idx) const {
- return std::vector<int64_t>::operator[](static_cast<int>(idx));
- }
-
- int64_t& operator[](size_t idx) {
- return std::vector<int64_t>::operator[](static_cast<int>(idx));
- }
-
- bool operator==(const TensorShape& other) const noexcept {
- auto thisVector = static_cast<const std::vector<int64_t>*>(this);
- auto otherVector = static_cast<const std::vector<int64_t>*>(&other);
- return *thisVector == *otherVector;
- }
-
- bool operator!=(const TensorShape& other) const noexcept {
- return !(*this == other);
- }
-
- size_t NumDimensions() const noexcept {
- return size();
- }
-
- /**
- Copy dims into an array with given size
- */
- void CopyDims(int64_t* dims, size_t num_dims) const {
- memcpy(dims, data(), sizeof(value_type) * std::min(num_dims, NumDimensions()));
- }
-
- /**
- Return underlying vector representation.
- */
- const std::vector<int64_t>& GetDims() const { return *this; }
-
- /**
- * Return the total number of elements. Returns 1 for an empty (rank 0) TensorShape.
- *
- * May return -1
- */
- int64_t Size() const;
-
- /**
- Return the total number of elements up to the specified dimension.
- If the dimension interval is empty (dimension == 0), return 1.
- @param dimension Return size up to this dimension. Value must be between 0 and this->NumDimensions(), inclusive.
- */
- int64_t SizeToDimension(size_t dimension) const;
-
- /**
- Return the total number of elements from the specified dimension to the end of the tensor shape.
- If the dimension interval is empty (dimension == this->NumDimensions()), return 1.
- @param dimension Return size from this dimension to the end. Value must be between 0 and this->NumDimensions(),
- inclusive.
- */
- int64_t SizeFromDimension(size_t dimension) const;
-
- /**
- Return a new TensorShape of the dimensions from dimstart to dimend.
- */
- TensorShape Slice(size_t dimstart, size_t dimend) const;
-
- /**
- Return a new TensorShape of the dimensions from dimstart to end.
- */
- TensorShape Slice(size_t dimstart) const;
-
- /**
- output dimensions nicely formatted
- */
- std::string ToString() const;
-
- /**
- Calculate size between start and end.
- Assumes start and end are between 0 and this->NumDimensions(), inclusive, and that
- start < end.
- */
- int64_t SizeHelper(size_t start, size_t end) const;
-
- /**
- empty shape or 1D shape (1) is regarded as scalar tensor
- */
- bool IsScalar() const {
- size_t len = size();
- return len == 0 || (len == 1 && operator[](0) == 1);
- }
-
- static const TensorShape& ReinterpretBaseType(const std::vector<int64_t>& dimensions) {
- static_assert(sizeof(TensorShape) == sizeof(std::vector<int64_t>), "Size of TensorShape prevents safe casting from vector");
- return *static_cast<const TensorShape*>(&dimensions);
- }
-};
-#ifdef __GNUC__
-#pragma GCC diagnostic pop
-#endif
-// operator<< to nicely output to a stream
-std::ostream& operator<<(std::ostream& out, const TensorShape& shape);
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/basic_types.h b/include/onnxruntime/core/graph/basic_types.h
deleted file mode 100755
index 7c1203f..0000000
--- a/include/onnxruntime/core/graph/basic_types.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include <unordered_map>
-#include <unordered_set>
-#include <string>
-#include <cstdint>
-#include <memory>
-#include <functional>
-
-namespace ONNX_NAMESPACE {
-class ValueInfoProto;
-class TensorProto;
-class SparseTensorProto;
-class TypeProto;
-class AttributeProto;
-// define types that would come from the ONNX library if we were building against it.
-#if defined(ORT_MINIMAL_BUILD)
-using OperatorSetVersion = int;
-#endif
-
-} // namespace ONNX_NAMESPACE
-
-namespace onnxruntime {
-using NodeIndex = size_t;
-using Version = int64_t;
-using NodeArgInfo = ONNX_NAMESPACE::ValueInfoProto;
-using InitializedTensorSet = std::unordered_map<std::string, const ONNX_NAMESPACE::TensorProto*>;
-using ArgNameToTypeMap = std::unordered_map<std::string, ONNX_NAMESPACE::TypeProto>;
-using ProviderType = const std::string&;
-// TODO - Evaluate switching the types below to support transparent comparators and enable
-// lookups based on gsl::cstring_span<> and std::string_view. This would reduces allocations
-// converting to std::string, but requires conversion to std::map<std::string, foo, std::less<>>
-// instead of std::unordered_map<std::string, foo, [std::less<foo>]>.
-
-using NodeAttributes = std::unordered_map<std::string, ONNX_NAMESPACE::AttributeProto>;
-class IOnnxRuntimeOpSchemaCollection;
-using IOnnxRuntimeOpSchemaCollectionPtr = std::shared_ptr<IOnnxRuntimeOpSchemaCollection>;
-} // namespace onnxruntime
-
-namespace onnxruntime {
-class OpKernel;
-class OpKernelInfo;
-
-using KernelCreateFn = std::function<OpKernel*(const OpKernelInfo& info)>;
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/constants.h b/include/onnxruntime/core/graph/constants.h
deleted file mode 100755
index f723a39..0000000
--- a/include/onnxruntime/core/graph/constants.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-
-constexpr const char* kNoOp = "NoOp";
-constexpr const char* kConstant = "Constant";
-constexpr const char* kFunctionOp = "_kFunctionOp";
-constexpr const char* kConstantValue = "value";
-constexpr const char* kOnnxDomain = "";
-constexpr const char* kOnnxDomainAlias = "ai.onnx";
-constexpr const char* kMLDomain = "ai.onnx.ml";
-constexpr const char* kMSDomain = "com.microsoft";
-constexpr const char* kMSNchwcDomain = "com.microsoft.nchwc";
-constexpr const char* kMSFeaturizersDomain = "com.microsoft.mlfeaturizers";
-constexpr const char* kMSDmlDomain = "com.microsoft.dml";
-constexpr const char* kNGraphDomain = "com.intel.ai";
-constexpr const char* kMIGraphXDomain = "";
-constexpr const char* kVitisAIDomain = "com.xilinx";
-
-constexpr const char* kCpuExecutionProvider = "CPUExecutionProvider";
-constexpr const char* kCudaExecutionProvider = "CUDAExecutionProvider";
-constexpr const char* kDnnlExecutionProvider = "DnnlExecutionProvider";
-constexpr const char* kOpenVINOExecutionProvider = "OpenVINOExecutionProvider";
-constexpr const char* kNupharExecutionProvider = "NupharExecutionProvider";
-constexpr const char* kVitisAIExecutionProvider = "VitisAIExecutionProvider";
-constexpr const char* kTensorrtExecutionProvider = "TensorrtExecutionProvider";
-constexpr const char* kNnapiExecutionProvider = "NnapiExecutionProvider";
-constexpr const char* kRknpuExecutionProvider = "RknpuExecutionProvider";
-constexpr const char* kDmlExecutionProvider = "DmlExecutionProvider";
-constexpr const char* kMIGraphXExecutionProvider = "MIGraphXExecutionProvider";
-constexpr const char* kAclExecutionProvider = "ACLExecutionProvider";
-constexpr const char* kArmNNExecutionProvider = "ArmNNExecutionProvider";
-constexpr const char* kRocmExecutionProvider = "ROCMExecutionProvider";
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/function.h b/include/onnxruntime/core/graph/function.h
deleted file mode 100755
index cf9eefd..0000000
--- a/include/onnxruntime/core/graph/function.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/common.h"
-#include "core/graph/indexed_sub_graph.h"
-
-namespace onnxruntime {
-class Graph;
-class Node;
-} // namespace onnxruntime
-
-namespace onnxruntime {
-
-/**
-@class Function
-Class representing a Function.
-*/
-class Function {
- public:
- virtual ~Function() = default;
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Gets the OpSchema for the Function. */
- virtual const ONNX_NAMESPACE::OpSchema& OpSchema() const = 0;
-#endif
-
- /** Gets the Graph instance for the Function body subgraph. */
- virtual const onnxruntime::Graph& Body() const = 0;
-};
-
-/**
-Create a new Function instance.
-@param graph The graph containing the Function.
-@param nodes_to_fuse the IndexedSubGraph to use for the Function.
-*/
-std::unique_ptr<Function> MakeFunction(const onnxruntime::Graph& graph,
- const IndexedSubGraph& nodes_to_fuse,
- const logging::Logger& logger);
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/graph.h b/include/onnxruntime/core/graph/graph.h
deleted file mode 100755
index d1841ff..0000000
--- a/include/onnxruntime/core/graph/graph.h
+++ /dev/null
@@ -1,1407 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <limits>
-#include <memory>
-#include <string>
-#include <type_traits>
-#include <unordered_map>
-#include <unordered_set>
-
-#include "core/common/common.h"
-#include "core/common/const_pointer_container.h"
-#include "core/common/path.h"
-#include "core/common/status.h"
-#include "core/common/logging/logging.h"
-#include "core/graph/basic_types.h"
-#include "core/graph/constants.h"
-#include "core/graph/graph_nodes.h"
-#include "core/graph/node_arg.h"
-#include "core/graph/onnx_protobuf.h"
-#include "core/graph/function.h"
-#include "gsl/gsl"
-
-namespace flatbuffers {
-class FlatBufferBuilder;
-template <typename T>
-struct Offset;
-} // namespace flatbuffers
-
-namespace onnxruntime {
-class Graph;
-struct IndexedSubGraph;
-class Model;
-class OpSignature;
-
-namespace experimental {
-namespace fbs {
-struct Graph;
-struct Node;
-struct NodeEdge;
-} // namespace fbs
-} // namespace experimental
-
-/**
-@class Node
-Class representing a node in the graph.
-*/
-class Node {
- public:
- /** Node types */
- enum class Type {
- Primitive = 0, ///< The node refers to a primitive operator.
- Fused = 1, ///< The node refers to a function.
- };
-
- ~Node() = default;
-
- /**
- @class EdgeEnd
- Class representing the end of an edge. It could be an input or output edge end of a node.
- For the node's input edge end, it's the source end, as the destination end is the node itself.
- For the node's output edge end, it's the destination end, as the source end is the node itself.
- */
- class EdgeEnd {
- public:
- /**
- Construct an EdgeEnd
- @param node The source node if this is an input edge to the current node,
- or the destination node if this is an output edge from the current node.
- @param src_arg_index The node arg index of source node of the edge.
- @param dst_arg_index The node arg index of destination node of the edge.
- */
- EdgeEnd(const Node& node, int src_arg_index, int dst_arg_index) noexcept;
-
- /** Construct a control edge.
- @param node The node the edge joins to the current node.
- */
- explicit EdgeEnd(const Node& node) noexcept;
-
- /** Gets the Node that this EdgeEnd refers to. */
- const Node& GetNode() const noexcept { return *node_; }
-
- /** Gets the source arg index.
- @returns the source arg index of <*this> edge.*/
- int GetSrcArgIndex() const { return src_arg_index_; }
-
- /** Gets the destination arg index.
- @returns the destination arg index of <*this> edge.*/
- int GetDstArgIndex() const { return dst_arg_index_; }
-
- private:
- const Node* node_;
- const int src_arg_index_;
- const int dst_arg_index_;
- };
-
- /** Gets the Node's NodeIndex. */
- NodeIndex Index() const noexcept { return index_; }
-
- /** Gets the Node's name. */
- const std::string& Name() const noexcept { return name_; }
-
- /** Gets the Node's operator type. */
- const std::string& OpType() const noexcept { return op_type_; }
-
- /** Gets the domain of the OperatorSet that specifies the operator returned by #OpType. */
- const std::string& Domain() const noexcept { return domain_; }
-
- /** Gets the path of the owning model if any. */
- const Path& ModelPath() const noexcept;
-
- /** Gets the Node's execution priority.
- @remarks Lower value means higher priority */
- int Priority() const noexcept { return priority_; };
-
- /** Sets the execution priority of a node.
- @remarks Lower value means higher priority */
- void SetPriority(int priority) noexcept;
-
- /** Gets the node description. */
- const std::string& Description() const noexcept { return description_; }
-
- /** Gets the Node's Node::Type. */
- Node::Type NodeType() const noexcept { return node_type_; }
-
- /** Gets the opset version that the Node's operator was first defined in.
- @returns Opset version. If -1 the Node's operator has not been set.
- @remarks Prefer over Op()->SinceVersion() as Op() is disabled in a minimal build
- */
- int SinceVersion() const noexcept { return since_version_; }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Gets the Node's OpSchema.
- @remarks The graph containing this node must be resolved, otherwise nullptr will be returned. */
- const ONNX_NAMESPACE::OpSchema* Op() const noexcept { return op_; }
-
- /**
- Gets the function body if applicable otherwise nullptr
- @param try_init_func_body If not already intialized, initialize the function body
- (only applicable to operators which are defined as function in ONNX spec).
- Function body can be initialized in 2 cases :
- 1. For nodes of type "Fused"
- 2. For nodes which are defined as functions in ONNX spec (example: DynamicQuantizeLinear)
- For all other cases this will always return nullptr.
- Nodes of type "Fused" are created during partitioning and the function body
- initialization for such nodes also happens during node creation. Therefore,
- initialization of function body will happen via this method only in case 2 mentioned above.
- */
- const Function* GetFunctionBody(bool try_init_func_body = true);
-
- /** Gets the function body if applicable otherwise nullptr. */
- const Function* GetFunctionBody() const noexcept { return func_body_; }
-
-#endif
-
- /**
- Helper to iterate through the container returned by #InputDefs() or #OutputDefs() and call the provided function.
- @param node_args Collection of NodeArgs returned by #InputDefs() or #OutputDefs()
- @param func Function to call for each valid NodeArg in the node_args. The function is called with the NodeArg
- and the index number in the container.
- @returns common::Status with success or error information.
- @remarks Returns immediately on error.
- */
- static common::Status ForEachWithIndex(const ConstPointerContainer<std::vector<NodeArg*>>& node_args,
- std::function<common::Status(const NodeArg& arg, size_t index)> func) {
- for (size_t index = 0; index < node_args.size(); ++index) {
- auto arg = node_args[index];
- if (!arg->Exists())
- continue;
- ORT_RETURN_IF_ERROR(func(*arg, index));
- }
- return common::Status::OK();
- }
-
- /** Gets the count of arguments for each of the Node's explicit inputs. */
- const std::vector<int>& InputArgCount() const noexcept { return definitions_.input_arg_count; }
-
- /** Gets the Node's input definitions.
- @remarks requires ConstPointerContainer wrapper to apply const to the NodeArg pointers so access is read-only. */
- ConstPointerContainer<std::vector<NodeArg*>> InputDefs() const noexcept {
- return ConstPointerContainer<std::vector<NodeArg*>>(definitions_.input_defs);
- }
-
- /** Gets the implicit inputs to this Node.
- If this Node contains a subgraph, these are the NodeArg's that are implicitly consumed by Nodes within that
- subgraph. e.g. If and Loop operators.*/
- ConstPointerContainer<std::vector<NodeArg*>> ImplicitInputDefs() const noexcept {
- return ConstPointerContainer<std::vector<NodeArg*>>(definitions_.implicit_input_defs);
- }
-
- /** Gets the Node's output definitions.
- @remarks requires ConstPointerContainer wrapper to apply const to the NodeArg pointers so access is read-only. */
- ConstPointerContainer<std::vector<NodeArg*>> OutputDefs() const noexcept {
- return ConstPointerContainer<std::vector<NodeArg*>>(definitions_.output_defs);
- }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /**
- Helper to iterate through the container returned by #MutableInputDefs() or #MutableOutputDefs() and call the provided function.
- @param node_args Collection of NodeArgs returned by #MutableInputDefs() or #MutableOutputDefs()
- @param func Function to call for each valid NodeArg in the node_args. The function is called with the NodeArg
- and the index number in the container.
- @returns common::Status with success or error information.
- @remarks Returns immediately on error.
- */
- static common::Status ForEachMutableWithIndex(std::vector<NodeArg*>& node_args,
- std::function<common::Status(NodeArg& arg, size_t index)> func) {
- for (size_t index = 0; index < node_args.size(); ++index) {
- auto arg = node_args[index];
- if (!arg->Exists())
- continue;
- ORT_RETURN_IF_ERROR(func(*arg, index));
- }
- return common::Status::OK();
- }
- /** Gets a modifiable count of arguments for each of the Node's explicit inputs.
- @todo This should be removed in favor of a method that updates the input args and the count.
- Currently these operations are separate which is not a good setup. */
- std::vector<int>& MutableInputArgsCount() { return definitions_.input_arg_count; }
-
- /** Gets a modifiable collection of the Node's input definitions. */
- std::vector<NodeArg*>& MutableInputDefs() noexcept {
- return definitions_.input_defs;
- }
-
- /** Gets a modifiable collection of the Node's implicit input definitions. */
- std::vector<NodeArg*>& MutableImplicitInputDefs() noexcept {
- return definitions_.implicit_input_defs;
- }
-
- /** Gets a modifiable collection of the Node's output definitions. */
- std::vector<NodeArg*>& MutableOutputDefs() noexcept {
- return definitions_.output_defs;
- }
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Struct to provide sorting between EdgeEnd instances based on NodeIndex first, and NodeArg::Name second. */
- struct EdgeEndCompare {
- bool operator()(const EdgeEnd& lhs, const EdgeEnd& rhs) const {
- if (lhs.GetNode().Index() == rhs.GetNode().Index()) {
- if (lhs.GetSrcArgIndex() == rhs.GetSrcArgIndex()) {
- return lhs.GetDstArgIndex() < rhs.GetDstArgIndex();
- }
- return lhs.GetSrcArgIndex() < rhs.GetSrcArgIndex();
- }
- return lhs.GetNode().Index() < rhs.GetNode().Index();
- }
- };
-
- using EdgeSet = std::set<EdgeEnd, EdgeEndCompare>;
- using EdgeConstIterator = EdgeSet::const_iterator;
-
- /**
- @class NodeConstIterator
- Class to provide const access to Node instances iterated via an EdgeConstIterator. */
- class NodeConstIterator {
- public:
- NodeConstIterator(EdgeConstIterator p_iter);
-
- bool operator==(const NodeConstIterator& p_other) const;
-
- bool operator!=(const NodeConstIterator& p_other) const;
-
- void operator++();
- void operator--();
-
- const Node& operator*() const;
- const Node* operator->() const;
-
- private:
- EdgeConstIterator m_iter;
- };
-
- // Functions defined to traverse a Graph as below.
-
- /** Gets an iterator to the beginning of the input nodes to this Node. */
- NodeConstIterator InputNodesBegin() const noexcept { return NodeConstIterator(relationships_.input_edges.cbegin()); };
- /** Gets an iterator to the end of the input nodes to this Node. */
- NodeConstIterator InputNodesEnd() const noexcept { return NodeConstIterator(relationships_.input_edges.cend()); }
-
- /** Gets an iterator to the beginning of the output nodes from this Node. */
- NodeConstIterator OutputNodesBegin() const noexcept {
- return NodeConstIterator(relationships_.output_edges.cbegin());
- }
-
- /** Gets an iterator to the end of the output nodes from this Node. */
- NodeConstIterator OutputNodesEnd() const noexcept { return NodeConstIterator(relationships_.output_edges.cend()); }
-
- /** Gets an iterator to the beginning of the input edges to this Node.
- @remarks There are no nullptr entries in this collection. */
- EdgeConstIterator InputEdgesBegin() const noexcept { return relationships_.input_edges.cbegin(); }
-
- /** Gets an iterator to the end of the input edges to this Node. */
- EdgeConstIterator InputEdgesEnd() const noexcept { return relationships_.input_edges.cend(); }
-
- /** Gets an iterator to the beginning of the output edges from this Node.
- @remarks There are no nullptr entries in this collection. */
- EdgeConstIterator OutputEdgesBegin() const noexcept { return relationships_.output_edges.cbegin(); }
-
- /** Gets an iterator to the end of the output edges from this Node. */
- EdgeConstIterator OutputEdgesEnd() const noexcept { return relationships_.output_edges.cend(); }
-
- /** Gets the Node's control inputs. */
- const std::set<std::string>& ControlInputs() const noexcept { return relationships_.control_inputs; }
-
- /** Gets the number of input edges to this Node */
- size_t GetInputEdgesCount() const noexcept { return relationships_.input_edges.size(); }
-
- /** Gets the number of output edges from this Node */
- size_t GetOutputEdgesCount() const noexcept { return relationships_.output_edges.size(); }
-
- /** Add an attribute to this Node with specified attribute name and value. */
- void AddAttribute(const std::string& attr_name, const ONNX_NAMESPACE::AttributeProto& value);
-
-#define ADD_ATTR_INTERFACES(TypeName) \
- void AddAttribute(const std::string& attr_name, const TypeName& value); \
- void AddAttribute(const std::string& attr_name, \
- const std::vector<TypeName>& values);
-
- ADD_ATTR_INTERFACES(int64_t)
- ADD_ATTR_INTERFACES(float)
- ADD_ATTR_INTERFACES(std::string)
- ADD_ATTR_INTERFACES(ONNX_NAMESPACE::TensorProto)
- ADD_ATTR_INTERFACES(ONNX_NAMESPACE::GraphProto)
- ADD_ATTR_INTERFACES(ONNX_NAMESPACE::SparseTensorProto)
-
- /** Gets the Node's attributes. */
- const NodeAttributes& GetAttributes() const noexcept { return attributes_; }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Remove the specified attribute from this Node */
- bool ClearAttribute(const std::string& attr_name);
-
- /** Gets the Node's mutable attributes. */
- NodeAttributes& GetMutableAttributes() noexcept { return attributes_; }
-
- /** Gets the Graph instance that is instantiated from a GraphProto attribute during Graph::Resolve.
- @param attr_name Attribute name for the GraphProto attribute.
- @returns nullptr if the Graph instance has not been instantiated or attribute does not contain a GraphProto.
- */
- const Graph* GetGraphAttribute(const std::string& attr_name) const;
-
- /** Gets the mutable Graph instance that is instantiated from a GraphProto attribute during Graph::Resolve.
- @param attr_name Attribute name for the GraphProto attribute.
- @returns nullptr if the Graph instance has not been instantiated or attribute does not contain a GraphProto.
- */
- Graph* GetMutableGraphAttribute(const std::string& attr_name);
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Checks if the Node contains at least one subgraph (this is the case for control flow operators, such as If, Scan, Loop).
- @returns true if the Node contains a subgraph.
- */
- bool ContainsSubgraph() const {
- return !attr_to_subgraph_map_.empty();
- }
-
- /** Get the const subgraphs from a node.
- @remarks Creates a new vector so calling ContainsSubgraphs first is preferred. */
- std::vector<gsl::not_null<const Graph*>> GetSubgraphs() const;
-
- /** Gets a map of attribute name to the mutable Graph instances for all subgraphs of the Node.
- @returns Map of the attribute name that defines the subgraph to the subgraph's Graph instance.
- nullptr if the Node has no subgraphs.
- */
- const std::unordered_map<std::string, gsl::not_null<Graph*>>& GetAttributeNameToMutableSubgraphMap() {
- return attr_to_subgraph_map_;
- }
-
- /** Gets the execution ProviderType that this node will be executed by. */
- ProviderType GetExecutionProviderType() const noexcept { return execution_provider_type_; }
-
- /** Sets the execution ProviderType that this Node will be executed by. */
- void SetExecutionProviderType(ProviderType execution_provider_type) {
- execution_provider_type_ = execution_provider_type;
- }
-
- /** Call the provided function for all explicit inputs, implicit inputs, and outputs of this Node.
- If the NodeArg is an explicit or implicit input, is_input will be true when func is called.
- @param include_missing_optional_defs Include NodeArgs that are optional and were not provided
- i.e. NodeArg::Exists() == false.
- */
- void ForEachDef(std::function<void(const onnxruntime::NodeArg&, bool is_input)> func,
- bool include_missing_optional_defs = false) const;
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Replaces any matching definitions in the Node's explicit inputs or explicit outputs.
- @param replacements Map of current NodeArg to replacement NodeArg.
- */
- void ReplaceDefs(const std::map<const onnxruntime::NodeArg*, onnxruntime::NodeArg*>& replacements);
-
- /** Gets the NodeProto representation of this Node.
- @param update_subgraphs Update the GraphProto values for any subgraphs in the returned NodeProto.
- If graph optimization has been run this is most likely required
- to ensure the complete Graph is valid.
- */
- void ToProto(ONNX_NAMESPACE::NodeProto& proto, bool update_subgraphs = false) const;
-
- Status SaveToOrtFormat(flatbuffers::FlatBufferBuilder& builder,
- flatbuffers::Offset<onnxruntime::experimental::fbs::Node>& fbs_node) const;
-
- flatbuffers::Offset<onnxruntime::experimental::fbs::NodeEdge>
- SaveEdgesToOrtFormat(flatbuffers::FlatBufferBuilder& builder) const;
-
-#endif
-
-#if defined(ENABLE_ORT_FORMAT_LOAD)
- static Status LoadFromOrtFormat(const onnxruntime::experimental::fbs::Node& fbs_node, Graph& graph,
- const logging::Logger& logger, std::unique_ptr<Node>& node);
-
- Status LoadFromOrtFormat(const onnxruntime::experimental::fbs::Node& fbs_node, const logging::Logger& logger);
- Status LoadEdgesFromOrtFormat(const onnxruntime::experimental::fbs::NodeEdge& fbs_node_edgs, const Graph& graph);
-#endif
-
- /**
- @class Definitions
- The input and output definitions for this Node.
- */
- class Definitions {
- public:
- Definitions() = default;
-
- /** The Node's explicit input definitions. */
- std::vector<NodeArg*> input_defs;
-
- /**
- The number of inputs for each argument of the operator or function which this node refers.
- @remarks For example, #input_defs has 10 elements (inputs), and #input_arg_count is {4, 6}.
- This means that 4 elements (inputs) of input_defs map to the first argument of the operator or function, and
- the other 6 map to the second argument.
- */
- std::vector<int> input_arg_count;
-
- /** The Node's output definitions. */
- std::vector<NodeArg*> output_defs;
-
- /** The Node's implicit input definitions if the Node contains one or more subgraphs
- (i.e. GraphProto attributes) and the subgraph/s implicitly consume these values.
- @remarks For example, a subgraph in an 'If' node gets all its input values via this mechanism rather than
- there being explicit inputs to the 'If' node that are passed to the subgraph.
- They are pseudo-inputs to this Node as it has an implicit dependency on them. */
- std::vector<NodeArg*> implicit_input_defs;
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Definitions);
- };
-
- /**
- @class Relationships
- Defines the relationships between this Node and other Nodes in the Graph.
- */
- class Relationships {
- public:
- Relationships() = default;
-
- void Clear() noexcept {
- input_edges.clear();
- output_edges.clear();
- control_inputs.clear();
- }
-
- /** The edges for Nodes that provide inputs to this Node. */
- EdgeSet input_edges;
-
- /** The edges for Nodes that receive outputs from this Node. */
- EdgeSet output_edges;
-
- /** The Node names of the control inputs to this Node. */
- std::set<std::string> control_inputs;
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Relationships);
- };
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Node);
-
- // NOTE: This friendship relationship should ONLY be used for calling methods of the Node class and not accessing
- // the data members directly, so that the Node can maintain its internal invariants.
- friend class Graph;
-
- Node(NodeIndex index, Graph& graph) : index_(index), graph_(&graph) {}
-
-#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
- void Init(const std::string& name,
- const std::string& op_type,
- const std::string& description,
- const std::vector<NodeArg*>& input_args,
- const std::vector<NodeArg*>& output_args,
- const NodeAttributes* attributes,
- const std::string& domain);
-
- // internal only method to allow selected classes to directly alter the input/output definitions and arg counts
- Definitions& MutableDefinitions() noexcept;
-
- // internal only method to allow selected classes to directly alter the links between nodes.
- Relationships& MutableRelationships() noexcept;
-
- void SetNodeType(Node::Type node_type) noexcept { node_type_ = node_type; }
-#endif
-
- // create a Graph instance for an attribute that contains a GraphProto
- void CreateSubgraph(const std::string& attr_name);
-
- const std::vector<std::unique_ptr<Graph>>& MutableSubgraphs() noexcept { return subgraphs_; }
-
- // validate and update the input arg count
- common::Status UpdateInputArgCount();
-
- void SetFunctionBody(const Function& func);
-
- const Definitions& GetDefinitions() const noexcept { return definitions_; }
- const Relationships& GetRelationships() const noexcept { return relationships_; }
-
- // Node index. Default to impossible value rather than 0.
- NodeIndex index_ = std::numeric_limits<NodeIndex>::max();
-
- // Node name.
- std::string name_;
-
- // Node operator type.
- std::string op_type_;
-
- // OperatorSet domain of op_type_.
- std::string domain_;
-
-#if !defined(ORT_MINIMAL_BUILD)
- // OperatorSchema that <*this> node refers to.
- const ONNX_NAMESPACE::OpSchema* op_ = nullptr;
-#endif
-
- // Execution priority, lower value for higher priority
- int priority_ = 0;
-
- // set from op_->SinceVersion() or via deserialization when OpSchema is not available
- int since_version_ = -1;
-
- Node::Type node_type_ = Node::Type::Primitive;
-
- // The function body is owned by graph_
- const Function* func_body_ = nullptr;
-
- // Node doc string.
- std::string description_;
-
- // input/output defs and arg count
- Definitions definitions_;
-
- // Relationships between this node and others in the graph
- Relationships relationships_;
-
- // Device.
- std::string execution_provider_type_;
-
- // Map from attribute name to attribute.
- // This allows attribute adding and removing.
- NodeAttributes attributes_;
-
- // Graph that contains this Node
- Graph* graph_;
-
- // Map of attribute name to the Graph instance created from the GraphProto attribute
- std::unordered_map<std::string, gsl::not_null<Graph*>> attr_to_subgraph_map_;
-
- // Graph instances for subgraphs that are owned by this Node
- std::vector<std::unique_ptr<Graph>> subgraphs_;
-};
-
-/**
-@class Graph
-The Graph representation containing the graph inputs and outputs, the Node instances,
-and the edges connecting the nodes.
-*/
-class Graph {
- public:
- /** Gets the Graph name. */
- const std::string& Name() const noexcept;
-
- /** Gets the Graph description. */
- const std::string& Description() const noexcept;
-
- /** Gets the path of the owning model, if any. */
- const Path& ModelPath() const;
-
- /** Returns true if this is a subgraph or false if it is a high-level graph. */
- bool IsSubgraph() const { return parent_graph_ != nullptr; }
-
- /** Returns the parent graph if this is a subgraph */
- const Graph* ParentGraph() const { return parent_graph_; }
-
- /** Returns the mutable parent graph if this is a subgraph */
- Graph* MutableParentGraph() { return parent_graph_; }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Sets the Graph name. */
- void SetName(const std::string& name);
-
- /** Gets the Graph description. */
- void SetDescription(const std::string& description);
-
- /** Add an initializer tensor to the Graph. */
- void AddInitializedTensor(const ONNX_NAMESPACE::TensorProto& tensor_proto);
-
- /** Replaces the initializer tensor with the same name as the given initializer tensor.
- The replacement initializer tensor must have the same type and shape as the existing initializer tensor.
-
- Note: This currently has linear time complexity. There is room for improvement but it would likely require changes to
- how initializer tensors are stored and tracked.
- */
- common::Status ReplaceInitializedTensor(const ONNX_NAMESPACE::TensorProto& new_initializer);
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Remove the initializer tensor with the provided name from the Graph. */
- void RemoveInitializedTensor(const std::string& tensor_name);
-
- /** Check if a given name is an initializer tensor's name in this graph. */
- bool IsInitializedTensor(const std::string& name) const;
-
- /** Gets an initializer tensor with the provided name.
- @param[out] value Set to the TensorProto* if the initializer is found, or nullptr if not.
- @returns True if found.
- */
- bool GetInitializedTensor(const std::string& tensor_name, const ONNX_NAMESPACE::TensorProto*& value) const;
-
- /** Gets all the initializer tensors in this Graph. */
- const InitializedTensorSet& GetAllInitializedTensors() const noexcept { return name_to_initial_tensor_; }
-
- /** Removes all initializer tensors from this Graph and releases the memory they were using. */
- void CleanAllInitializedTensors() noexcept;
-
- /** Returns true if an initializer value can be overridden by a graph input with the same name. */
- bool CanOverrideInitializer() const noexcept { return ir_version_ >= 4; }
-
- /** returns the initializer's TensorProto if 'name' is an initializer, is constant and
- cannot be overridden at runtime. If the initializer is not found or is not constant, a nullptr is returned.
- @param check_outer_scope If true and the graph is a subgraph,
- check ancestor graph/s for 'name' if not found in 'graph'.
- @remarks check_outer_scope of true is not supported in a minimal build
- */
- const ONNX_NAMESPACE::TensorProto* GetConstantInitializer(const std::string& name, bool check_outer_scope) const;
-
- /** Gets the Graph inputs excluding initializers.
- These are the required inputs to the Graph as the initializers can be optionally overridden via graph inputs.
- @remarks Contains no nullptr values. */
- const std::vector<const NodeArg*>& GetInputs() const noexcept { return graph_inputs_excluding_initializers_; }
-
- /** Gets the Graph inputs including initializers.
- This is the full set of inputs, in the same order as defined in the GraphProto.
- @remarks Contains no nullptr values. */
- const std::vector<const NodeArg*>& GetInputsIncludingInitializers() const noexcept {
- return graph_inputs_including_initializers_;
- }
-
- /** Return true if "node_arg" is a input or an initializer. Otherwise, returns false. */
- bool IsInputsIncludingInitializers(const NodeArg* node_arg) const noexcept {
- return std::find(graph_inputs_including_initializers_.begin(), graph_inputs_including_initializers_.end(), node_arg) != graph_inputs_including_initializers_.end();
- }
-
- /** Gets the Graph inputs that are initializers
- These are overridable initializers. This is a difference between
- graph_inputs_including_initializers_ and graph_inputs_excluding_initializers_
- @remarks Contains no nullptr values. */
- const std::vector<const NodeArg*>& GetOverridableInitializers() const {
- return graph_overridable_initializers_;
- }
-
- /** Gets the Graph outputs.
- @remarks Contains no nullptr values.*/
- const std::vector<const NodeArg*>& GetOutputs() const noexcept { return graph_outputs_; }
-
- bool IsOutput(const NodeArg* node_arg) const noexcept {
- return std::find(graph_outputs_.begin(), graph_outputs_.end(), node_arg) != graph_outputs_.end();
- }
-
- /** Returns a vector with the indexes of the outputs of the given Node that are also Graph outputs. */
- std::vector<int> GetNodeOutputsInGraphOutputs(const Node& node) const {
- int output_idx = 0;
- std::vector<int> indexes;
- for (auto output_def : node.OutputDefs()) {
- if (std::find(GetOutputs().cbegin(), GetOutputs().cend(), output_def) != GetOutputs().cend()) {
- indexes.push_back(output_idx);
- }
-
- ++output_idx;
- }
-
- return indexes;
- }
-
- /** Gets the NodeArgs that represent value_info instances in the Graph.
- These are the values that are neither Graph inputs nor outputs.
- @remarks Contains no nullptr values. */
- const std::vector<const NodeArg*>& GetValueInfo() const noexcept { return value_info_; }
-
-#if !defined(ORT_MINIMAL_BUILD)
- void AddValueInfo(const NodeArg* new_value_info);
-#endif
-
- /** Gets the Node with the specified node index.
- @returns Node instance if found. nullptr if node_index is invalid or node has been freed.
- */
- const Node* GetNode(NodeIndex node_index) const { return NodeAtIndexImpl(node_index); }
-
- /** Gets the mutable Node with the specified node index.
- @returns Mutable Node instance if found. nullptr if node_index is invalid or node has been freed.
- */
- Node* GetNode(NodeIndex node_index) { return NodeAtIndexImpl(node_index); }
-
- /** Get a GraphNodes instance that provides mutable access to all valid Nodes in the Graph. */
- GraphNodes& Nodes() noexcept { return iterable_nodes_; }
-
- /** Get a GraphNodes instance that provides const access to all valid Nodes in the Graph. */
- const GraphNodes& Nodes() const noexcept { return iterable_nodes_; }
-
- /** Get a ConstGraphNodes instance that provides access to a filtered set of valid Nodes in the Graph.
- @remarks We can't use GraphNodes as that would provide mutable access to the nodes by default, and we can't prevent
- that by returning a const instance of GraphNodes as we're creating a new instance here due to the filter
- being something we don't control (i.e. we have to return a new instance so it can't be const).
- */
- ConstGraphNodes FilteredNodes(GraphNodes::NodeFilterFunc&& filter_func) const noexcept {
- return ConstGraphNodes(nodes_, std::move(filter_func));
- }
-
- /** Gets the maximum NodeIndex value used in the Graph. */
- int MaxNodeIndex() const noexcept { return static_cast<int>(nodes_.size()); } //assume the casting won't overflow
-
- /** Gets the number of valid Nodes in the Graph.
- @remarks This may be smaller than MaxNodeIndex(), as Nodes may be removed during optimization.
- */
- int NumberOfNodes() const noexcept { return num_of_nodes_; }
-
- /** Gets the mutable NodeArg with the provided name.
- @returns Pointer to NodeArg if found, nullptr if not. */
- NodeArg* GetNodeArg(const std::string& name) {
- auto iter = node_args_.find(name);
- if (iter != node_args_.end()) {
- return iter->second.get();
- }
- return nullptr;
- }
-
- /** Gets the const NodeArg with the provided name.
- @returns Pointer to const NodeArg if found, nullptr if not. */
- const NodeArg* GetNodeArg(const std::string& name) const {
- return const_cast<Graph*>(this)->GetNodeArg(name);
- }
-
- // search this and up through any parent_graph_ instance for a NodeArg
- NodeArg* GetNodeArgIncludingParentGraphs(const std::string& node_arg_name);
-
- /** Gets a mutable NodeArg by name. Creates a new NodeArg that is owned by this Graph if not found.
- @param name The NodeArg name.
- @param[in] p_arg_type Optional TypeProto to use if the NodeArg needs to be created.
- @returns NodeArg reference.
- */
- NodeArg& GetOrCreateNodeArg(const std::string& name, const ONNX_NAMESPACE::TypeProto* p_arg_type) {
- auto iter = node_args_.find(name);
- if (iter != node_args_.end()) {
- return *(iter->second);
- }
- auto result = node_args_.insert(std::make_pair(name, onnxruntime::make_unique<NodeArg>(name, p_arg_type)));
- return *(result.first->second);
- }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Generate a unique name in this Graph for a NodeArg */
- std::string GenerateNodeArgName(const std::string& base_name);
-
- /** Generate a unique name in this Graph for a Node */
- std::string GenerateNodeName(const std::string& base_name);
-
- /** Copy a Node and add it to this Graph.
- @param other Node to copy
- @returns Reference to the Node that was created and added to this Graph.
- @remarks Do not call AddNode and Remove Node concurrently as they are not thread-safe.
- */
- Node& AddNode(const Node& other);
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
- /** Add a Node to this Graph.
- @param name The Node name. Must be unique in this Graph.
- @param op_type The operator type. e.g. ONNX operator name.
- @param description Arbitrary description of the Node.
- @param input_args The explicit inputs to this Node.
- @param output_args The outputs from this Node.
- @param attributes Optional NodeAttributes to add.
- @param domain The domain for the op_type.
- @returns Reference to the new Node.
- @remarks Do not call AddNode and Remove Node concurrently as they are not thread-safe.
- */
- Node& AddNode(const std::string& name,
- const std::string& op_type,
- const std::string& description,
- const std::vector<NodeArg*>& input_args,
- const std::vector<NodeArg*>& output_args,
- const NodeAttributes* attributes = nullptr,
- const std::string& domain = "");
-
- /** Remove a Node from this Graph and free it.
- The output edges of this specified node MUST have been removed before removing the node.
- The input edges of this specified node is removed while removing the node. The process of
- removing a node from a graph should be,
- 1. Remove out edges of this specified node.
- 2. Remove this specified node.
- 3. Add new input edges connected with all out nodes.
- @returns true if the node_index was valid
- @remarks Do not call AddNode and Remove Node concurrently as they are not thread-safe.
- */
- bool RemoveNode(NodeIndex node_index);
-
- /** Add an edge between two Nodes.
- @param src_node_index NodeIndex of source Node that is providing output to the destination Node.
- @param dst_node_index NodeIndex of destination Node that is receiving input from the source Node.
- @param src_arg_index node arg index of source node.
- @param dst_arg_index node arg index of destination node.
- */
- void AddEdge(NodeIndex src_node_index, NodeIndex dst_node_index, int src_arg_index, int dst_arg_index);
-
- /** Remove an edge between two Nodes.
- @param src_node_index NodeIndex of source Node to remove an output edge from.
- @param dst_node_index NodeIndex of destination Node to remove an input edge from.
- @param src_arg_index node arg index of source node.
- @param dst_arg_index node arg index of destination node.
- */
- void RemoveEdge(NodeIndex src_node_index, NodeIndex dst_node_index, int src_arg_index, int dst_arg_index);
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD)
- /**
- Add a control edge between two Nodes in this Graph.
- The source Node does not produce output that is directly consumed by the destination Node, however the
- destination Node must execute after the source node. The control edge allows this ordering to occur.
- */
- bool AddControlEdge(NodeIndex src_node_index, NodeIndex dst_node_index);
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Mark the Graph as needing Resolve() to be called.
- This should be done after modifying any aspect of the Graph that changes the Nodes or relationships between them. */
- Graph& SetGraphResolveNeeded() noexcept {
- graph_resolve_needed_ = true;
- return *this;
- }
-
- /** Gets flag indicating whether Graph::Resolve needs to be called before using the Graph. */
- bool GraphResolveNeeded() const noexcept {
- return graph_resolve_needed_;
- }
-
- /** Sets flag that Graph::graph_proto_ needs to be updated to reflect changes in the Graph. */
- Graph& SetGraphProtoSyncNeeded() noexcept {
- graph_proto_sync_needed_ = true;
- return *this;
- }
-
- /** Gets flag indicating whether Graph::graph_proto_ needs to be synchronized with this Graph instance. */
- bool GraphProtoSyncNeeded() const noexcept {
- return graph_proto_sync_needed_;
- }
-
- /** Performs a reverse depth-first search (DFS) traversal from a set of nodes, via their inputs,
- up to their source node/s.
- @param from NodeIndex values for a set of Nodes to traverse from.
- @param enter Visit function that will be invoked on a node when it is visited but its parents haven't been.
- @param leave Visit function invoked on the node after its parents have all been visited.
- @param comp Comparison function to stabilize the traversal order by making Node ordering deterministic.
- */
- void ReverseDFSFrom(const std::vector<NodeIndex>& from,
- const std::function<void(const Node*)>& enter,
- const std::function<void(const Node*)>& leave,
- const std::function<bool(const Node*, const Node*)>& comp = {}) const;
-
- /** Performs a reverse depth-first search (DFS) traversal from a set of nodes, via their inputs,
- up to their source node/s.
- @param from Set of Nodes to traverse from.
- @param enter Visit function that will be invoked on a node when it is visited but its parents haven't been.
- @param leave Visit function invoked on the node after its parents have all been visited.
- @param comp Comparison function to stabilize the traversal order by making Node ordering deterministic.
- */
- void ReverseDFSFrom(const std::vector<const Node*>& from,
- const std::function<void(const Node*)>& enter,
- const std::function<void(const Node*)>& leave,
- const std::function<bool(const Node*, const Node*)>& comp = {}) const;
-
- /** Performs a reverse depth-first search (DFS) traversal from a set of nodes, via their inputs,
- up to their source node/s.
- @param from Set of Nodes to traverse from.
- @param enter Visit function that will be invoked on a node when it is visited but its parents haven't been.
- @param leave Visit function invoked on the node after its parents have all been visited.
- @param stop Stop traversal from node n to input node p if stop(n, p) is true.
- @param comp Comparison function to stabilize the traversal order by making Node ordering deterministic.
- */
- void ReverseDFSFrom(const std::vector<const Node*>& from,
- const std::function<void(const Node*)>& enter,
- const std::function<void(const Node*)>& leave,
- const std::function<bool(const Node*, const Node*)>& comp,
- const std::function<bool(const Node*, const Node*)>& stop) const;
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Performs topological sort with Kahn's algorithm on the graph/s.
- @param enter Visit function that will be invoked on a node when it is visited.
- @param comp Comparison function to stabilize the traversal order by making Node ordering deterministic.
- */
- void KahnsTopologicalSort(const std::function<void(const Node*)>& enter,
- const std::function<bool(const Node*, const Node*)>& comp) const;
-
-#endif
-
- /** Gets the map of operator domains to their opset versions. */
- const std::unordered_map<std::string, int>& DomainToVersionMap() const noexcept {
- return domain_to_version_;
- }
-
-#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
- /**
- Create a single Node that will be the result of the a fusion of multiple nodes in this Graph.
- @param sub_graph A IndexSubGraph instance with details of the nodes to fuse.
- @param fused_node_name The name for the new Node.
- @returns Node with fused subgraph.
- @remarks As a new Graph instance for the fused nodes is not created, a GraphViewer can be constructed with the
- IndexedSubGraph information to provide a view of the subgraph. The original nodes are left in place
- while this is in use.
- Call FinalizeFuseSubGraph to remove them once the fused replacement node is fully created.
- */
- Node& BeginFuseSubGraph(const IndexedSubGraph& sub_graph, const std::string& fused_node_name);
-
- void FinalizeFuseSubGraph(const IndexedSubGraph& sub_graph, Node& fused_node);
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Gets the GraphProto representation of this Graph. */
- const ONNX_NAMESPACE::GraphProto& ToGraphProto();
- ONNX_NAMESPACE::GraphProto ToGraphProto() const;
-
- /** Gets the ISchemaRegistry instances being used with this Graph. */
- IOnnxRuntimeOpSchemaCollectionPtr GetSchemaRegistry() const;
-
- /**
- Create a single Function based Node that is the result of the a fusion of multiple nodes in this Graph.
- A new Graph instance will be created for the fused nodes.
- @param sub_graph A IndexSubGraph instance with details of the nodes to fuse. Ownership is transferred to the new Node
- @param fused_node_name The name for the new Node.
- @returns Function based Node with fused subgraph. The Node body will contain a Function instance.
- */
- Node& FuseSubGraph(const IndexedSubGraph& sub_graph, const std::string& fused_node_name);
-
- /**
- Directly insert the nodes in the function Node provided into this Graph.
- @param node Node with Node::Type of Node::Type::Fused
- @returns Status indicating success or providing an error message.
- */
- Status InlineFunction(Node& node);
-
- /** Initialize function body for the given node */
- void InitFunctionBodyForNode(Node& node);
-
- /** Mark a NodeArg name as coming from the outer scope when programmatically constructing a Graph that will
- be used as a GraphProto attribute in another Node..
- e.g. when creating a Graph instance that will be used as a subgraph in a control flow operator, it is necessary to
- define placeholder NodeArgs for outer scope values. This prevents these values from becoming explicit graph inputs
- when the Graph is resolved.
- */
- void AddOuterScopeNodeArg(const std::string& name) {
- ORT_IGNORE_RETURN_VALUE(outer_scope_node_arg_names_.insert(name));
- }
-
- /** Explicitly set graph inputs.
- @param inputs NodeArgs that represent complete graph inputs which need to be explicitly ordered.
- @remarks Note that the input order matters for subgraphs.
- */
- void SetInputs(const std::vector<const NodeArg*>& inputs);
-
- /** Explicitly set graph outputs.
- @param outputs NodeArgs that represent complete graph outputs which need to be explicitly ordered.
- @remarks Note that the output order matters for subgraphs.
- */
- void SetOutputs(const std::vector<const NodeArg*>& outputs);
-
- /** Sets the type of a NodeArg, replacing existing type/shape if any */
- void SetNodeArgType(NodeArg& arg, const onnx::TypeProto& type_proto);
-
- const Node* GetProducerNode(const std::string& node_arg_name) const {
- return GetProducerNodeImpl(*this, node_arg_name);
- }
-
- Node* GetMutableProducerNode(const std::string& node_arg_name) {
- return GetProducerNodeImpl(*this, node_arg_name);
- }
-
- void UpdateProducerNode(const std::string& node_arg_name, NodeIndex node_index) {
- auto iter = node_arg_to_producer_node_.find(node_arg_name);
-
- if (iter != node_arg_to_producer_node_.end()) {
- iter->second = node_index;
- } else {
- node_arg_to_producer_node_[node_arg_name] = node_index;
- }
- }
-
- std::vector<const Node*> GetConsumerNodes(const std::string& node_arg_name) const {
- return GetConsumerNodesImpl(*this, node_arg_name);
- }
-
- std::vector<Node*> GetMutableConsumerNodes(const std::string& node_arg_name) {
- return GetConsumerNodesImpl(*this, node_arg_name);
- }
-
- void UpdateConsumerNodes(const std::string& node_arg_name, const std::vector<Node*>& nodes) {
- auto iter = node_arg_to_consumer_nodes_.find(node_arg_name);
- if (iter != node_arg_to_consumer_nodes_.end()) {
- node_arg_to_consumer_nodes_.erase(node_arg_name);
- }
- for (Node* node : nodes) {
- node_arg_to_consumer_nodes_[node_arg_name].insert(node->Index());
- }
- }
-
- /** During constant folding it may become possible to infer the shape for a node.
- To avoid running a full Resolve allow an individual node to have the shape inferencing re-run.
- */
- Status UpdateShapeInference(Node& node);
-
- // Options to control Graph::Resolve.
- struct ResolveOptions {
- // Whether to override existing types with inferred types.
- bool override_types = false;
- // Names of initializers to keep even if unused (optional).
- const std::unordered_set<std::string>* initializer_names_to_preserve = nullptr;
- // Whether to set that no proto sync is required after resolving.
- // Useful for resolving right after loading from a GraphProto.
- bool no_proto_sync_required = false;
- };
-
- /**
- Resolve this Graph to ensure it is completely valid, fully initialized, and able to be executed.
- 1. Run through all validation rules.
- a. Node name and node output's names should be unique.
- b. Attribute match between node and op definition.
- c. Input/Output match between node and op definition.
- d. Graph is acyclic and sort nodes in topological order.
- 2. Check & Setup inner nodes' dependency.
- 3. Cleanup function definition lists.
- Note: the weights for training can't be cleaned during resolve.
- @returns common::Status with success or error information.
- */
- common::Status Resolve(const ResolveOptions& options);
-
- common::Status Resolve() {
- ResolveOptions default_options;
- return Resolve(default_options);
- }
-
- common::Status SaveToOrtFormat(flatbuffers::FlatBufferBuilder& builder,
- flatbuffers::Offset<onnxruntime::experimental::fbs::Graph>& fbs_graph) const;
-
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Returns the Node containing the GraphProto for this Graph instance if IsSubgraph is true */
- const Node* ParentNode() const { return parent_node_; }
-
- /** Returns true if the name is for a value that is coming from outer scope */
- bool IsOuterScopeValue(const std::string& name) const {
- if (!parent_node_) return false;
- const auto& implicit_input_defs = parent_node_->ImplicitInputDefs();
- return std::any_of(implicit_input_defs.cbegin(), implicit_input_defs.cend(),
- [&name](const NodeArg* implicit_input) {
- return implicit_input->Name() == name;
- });
- }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Construct a Graph instance for a subgraph that is created from a GraphProto attribute in a Node.
- Inherits some properties from the parent graph.
- @param parent_graph The Graph containing the Node that has the GraphProto attribute.
- @param parent_node The Node that has the GraphProto attribute.
- @param subgraph_proto The GraphProto from the Node attribute.
- */
- Graph(Graph& parent_graph, const Node& parent_node, ONNX_NAMESPACE::GraphProto& subgraph_proto);
-#endif
-
- virtual ~Graph();
-
-#if defined(ENABLE_ORT_FORMAT_LOAD)
- static common::Status LoadFromOrtFormat(
- const onnxruntime::experimental::fbs::Graph& fbs_graph, const Model& owning_model,
- const std::unordered_map<std::string, int>& domain_to_version,
- const logging::Logger& logger, std::unique_ptr<Graph>& graph);
-
- // deserialize a subgraph
- static Status LoadFromOrtFormat(const onnxruntime::experimental::fbs::Graph& fbs_graph,
- Graph& parent_graph, const Node& parent_node,
- const logging::Logger& logger, std::unique_ptr<Graph>& graph);
-#endif
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Graph);
-
- // This friendship relationship should only be used to call Graph::Graph and
- // Graph::LoadGraph All other access should be via the public API.
- friend class Model;
-
- Graph() = delete;
-
- // Create empty Graph instance to re-create from ORT format serialized data.
- Graph(const Model& owning_model,
- const std::unordered_map<std::string, int>& domain_to_version,
- Graph* parent_graph, const Node* parent_node,
- const logging::Logger& logger);
-
-#if defined(ENABLE_ORT_FORMAT_LOAD)
- // Populate Graph instance from ORT format serialized data.
- common::Status LoadFromOrtFormat(const onnxruntime::experimental::fbs::Graph& fbs_graph);
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD)
- // Constructor: Given a <GraphProto> loaded from model file, construct
- // a <Graph> object. Used by Model to create a Graph instance.
- Graph(const Model& owning_model,
- ONNX_NAMESPACE::GraphProto* graph_proto,
- const std::unordered_map<std::string, int>& domain_to_version,
- Version ir_version,
- IOnnxRuntimeOpSchemaCollectionPtr schema_registry,
- const logging::Logger& logger);
-
- // internal use by the Graph class only
- Graph(const Model& owning_model,
- ONNX_NAMESPACE::GraphProto* graph_proto,
- const std::unordered_map<std::string, int>& domain_to_version,
- Version ir_version,
- IOnnxRuntimeOpSchemaCollectionPtr schema_registry,
- Graph* parent_graph,
- const Node* parent_node,
- const logging::Logger& logger);
-
- void InitializeStateFromModelFileGraphProto();
-
- // Add node with specified <node_proto>.
- Node& AddNode(const ONNX_NAMESPACE::NodeProto& node_proto,
- const ArgNameToTypeMap& name_to_type);
-
-#endif
-
- Version IrVersion() const noexcept {
- return ir_version_;
- }
-
- Graph& GraphResolveNeeded(bool needed) noexcept {
- graph_resolve_needed_ = needed;
- return *this;
- }
-
- Graph& GraphProtoSyncNeeded(bool needed) noexcept {
- graph_proto_sync_needed_ = needed;
- return *this;
- }
-
- // During the Resolve of a Graph it is necessary to recursively descend into subgraphs (created from GraphProto
- // Node attributes in the Graph) if present.
- // The ResolveContext holds the collection of values for the current Graph instance, be it the main graph
- // or a subgraph, so that the various operations that are part of the Resolve can work iteratively or
- // recursively as needed.
- struct ResolveContext {
- ResolveContext() = default;
-
- std::unordered_map<std::string, std::pair<Node*, int>> output_args;
- std::unordered_set<std::string> inputs_and_initializers;
- std::unordered_set<std::string> outer_scope_node_args;
- std::unordered_map<std::string, NodeIndex> node_name_to_index;
- std::unordered_set<Node*> nodes_with_subgraphs;
-
- void Clear() {
- output_args.clear();
- inputs_and_initializers.clear();
- outer_scope_node_args.clear();
- node_name_to_index.clear();
- nodes_with_subgraphs.clear();
- }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ResolveContext);
- };
-
- // Initialize all the graph inputs, initializers and outputs
- common::Status InitInputsInitializersOutputs();
-
- // Initialize overridable initializers container
- void ComputeOverridableInitializers();
-
-#if !defined(ORT_MINIMAL_BUILD)
- // Build and verify node connection (edges).
- // Verify NodeArg name/type/shape matching correctly.
- common::Status BuildConnections(std::unordered_set<std::string>& outer_scope_node_args_consumed);
-
- common::Status VerifyNoDuplicateName();
-
- // Check whether <*this> graph is acyclic while performing a topological sort.
- // Depth-first going from bottom up through the graph and checking whether there are any back edges.
- // NodesInTopologicalOrder is updated with the nodes' indexes in topological
- // order if <Status> returned is "OK", otherwise it's undefined.
- common::Status PerformTopologicalSortAndCheckIsAcyclic();
-
- common::Status PerformTypeAndShapeInferencing(const ResolveOptions& options);
-
- // Recursively find all subgraphs including nested subgraphs
- void FindAllSubgraphs(std::vector<Graph*>& subgraphs);
-
- // Iterate this Graph instance and all subgraphs, calling the provided function for each.
- common::Status ForThisAndAllSubgraphs(const std::vector<Graph*>& subgraphs, std::function<Status(Graph&)> func);
-
- common::Status InferAndVerifyTypeMatch(Node& node, const ONNX_NAMESPACE::OpSchema& op, const ResolveOptions& options);
-
- // perform type and shape inferencing on the subgraph and Resolve to validate
- static common::Status InferAndVerifySubgraphTypes(const Node& node, Graph& subgraph,
- const std::vector<const ONNX_NAMESPACE::TypeProto*>& input_types,
- std::vector<const ONNX_NAMESPACE::TypeProto*>& output_types,
- const Graph::ResolveOptions& options);
-
- // Apply type-inference and type-checking to all inputs and initializers:
- common::Status TypeCheckInputsAndInitializers();
-
- // Compute set of input and initializer names and checking for duplicate names
- common::Status VerifyInputAndInitializerNames();
-
- // Infer and set type information across <*this> graph if needed, and verify type/attribute
- // information matches between node and op.
- common::Status VerifyNodeAndOpMatch(const ResolveOptions& options);
-
- // Set graph inputs/outputs when resolving a graph..
- common::Status SetGraphInputsOutputs();
-
- // recursively accumulate and set the outer scope node args in the resolve context for all subgraphs
- // so they can be used to resolve outer scope dependencies when running BuildConnections for the subgraphs.
- common::Status SetOuterScopeNodeArgs(const std::unordered_set<std::string>& outer_scope_node_args);
-
- // Clear all unused initializers
- void CleanUnusedInitializers(const std::unordered_set<std::string>* initializer_names_to_preserve = nullptr);
-
- std::vector<NodeArg*> CreateNodeArgs(const google::protobuf::RepeatedPtrField<std::string>& names,
- const ArgNameToTypeMap& name_to_type_map);
-
- void ToGraphProtoInternal(ONNX_NAMESPACE::GraphProto& graph_proto) const;
-
- template <typename TInstance>
- static auto GetProducerNodeImpl(
- TInstance& instance, const std::string& node_arg_name) -> decltype(instance.GetNode(0)) {
- auto iter = instance.node_arg_to_producer_node_.find(node_arg_name);
- if (iter != instance.node_arg_to_producer_node_.end()) {
- auto node_index = iter->second;
- return instance.GetNode(node_index);
- }
- return nullptr;
- }
-
- template <typename TInstance>
- static auto GetConsumerNodesImpl(
- TInstance& instance, const std::string& node_arg_name) -> std::vector<decltype(instance.GetNode(0))> {
- std::vector<decltype(instance.GetNode(0))> results;
- auto iter = instance.node_arg_to_consumer_nodes_.find(node_arg_name);
- if (iter != instance.node_arg_to_consumer_nodes_.end()) {
- results.reserve(iter->second.size());
- for (auto node_index : iter->second) {
- results.push_back(instance.GetNode(node_index));
- }
- }
- return results;
- }
-
-#endif // !defined(ORT_MINIMAL_BUILD)
-
-#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
- gsl::not_null<Node*> AllocateNode();
-
- // Release the node.
- // @returns false if node_index was invalid.
- bool ReleaseNode(NodeIndex node_index);
-
- Node& CreateFusedSubGraphNode(const IndexedSubGraph& sub_graph, const std::string& fused_node_name);
-#endif
-
- Node* NodeAtIndexImpl(NodeIndex node_index) const {
- // if we are trying to access a node that doesn't exist there's (most
- // likely) either a logic issue or a graph consistency/correctness issue.
- // use ORT_ENFORCE to prove that or uncover scenarios where we actually
- // expect attempts to retrieve a non-existent node.
- ORT_ENFORCE(node_index < nodes_.size(), "Validating no unexpected access using an invalid node_index. Got:",
- node_index, " Max:", nodes_.size());
- return nodes_[node_index].get();
- }
-
- const Model& owning_model_;
-
- // GraphProto to store name, version, initializer.
- // When serializing <*this> Graph to a GraphProto, the nodes and
- // functions in <Graph> will also be fed into <graph_proto_> so that
- // it's consistent with <*this> graph.
- // This pointer is owned by parent model.
- ONNX_NAMESPACE::GraphProto* graph_proto_;
-
- // GraphProto that provides storage for the ONNX proto types deserialized from a flexbuffer/flatbuffer
- ONNX_NAMESPACE::GraphProto deserialized_proto_data_;
-
- InitializedTensorSet name_to_initial_tensor_;
-
- std::unordered_set<std::reference_wrapper<const std::string>,
- std::hash<std::string>, std::equal_to<std::string>>
- sparse_tensor_names_;
-
-#if !defined(ORT_MINIMAL_BUILD)
- IOnnxRuntimeOpSchemaCollectionPtr schema_registry_;
-
- std::vector<std::unique_ptr<onnxruntime::Function>> function_container_;
-#endif
-
- // Graph nodes.
- // Element in <nodes_> may be nullptr due to graph optimization.
- std::vector<std::unique_ptr<Node>> nodes_;
-
- // Wrapper of Graph nodes to provide iteration services that hide nullptr entries
- GraphNodes iterable_nodes_{nodes_};
-
- // Number of nodes.
- // Normally this is smaller than the size of <m_nodes>, as some
- // elements in <m_nodes> may be removed when doing graph optimization,
- // or some elements may be merged, etc.
- int num_of_nodes_ = 0;
-
- // A flag indicates whether <*this> graph needs to be resolved.
- bool graph_resolve_needed_ = false;
-
- bool graph_proto_sync_needed_ = false;
-
- // The topological order of node index used to do node and op match verification temporarily.
- std::vector<NodeIndex> nodes_in_topological_order_;
-
- // Full list of graph inputs. Matches number and order of inputs in the GraphProto.
- std::vector<const NodeArg*> graph_inputs_including_initializers_;
- bool graph_inputs_manually_set_ = false;
-
- // Graph inputs excluding initializers.
- std::vector<const NodeArg*> graph_inputs_excluding_initializers_;
-
- // Overridable Initializers. The difference between graph_inputs_including_initializers_
- // and graph_inputs_excluding_initializers_
- std::vector<const NodeArg*> graph_overridable_initializers_;
-
- // Graph outputs.
- std::vector<const NodeArg*> graph_outputs_;
- bool graph_outputs_manually_set_ = false;
-
- // Graph value_info.
- std::vector<const NodeArg*> value_info_;
-
- // All node args owned by <*this> graph. Key is node arg name.
- std::unordered_map<std::string, std::unique_ptr<NodeArg>> node_args_;
-
-#if !defined(ORT_MINIMAL_BUILD)
- int name_generator_ = 0;
-
- // Strings which have been used as node names.
- // New node name should not conflict with this set.
- std::unordered_set<std::string> generated_node_names_;
-
- // Strings which have been used as node_arg names.
- // New node_arg name should not conflict this this set.
- std::unordered_set<std::string> generated_node_arg_names_;
-
- // node arg to its producer node
- std::unordered_map<std::string, NodeIndex> node_arg_to_producer_node_;
-
- // node arg to its consumer nodes
- std::unordered_map<std::string, std::unordered_set<NodeIndex>> node_arg_to_consumer_nodes_;
-
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- const std::unordered_map<std::string, int> domain_to_version_;
-
- // Model IR version.
- Version ir_version_{ONNX_NAMESPACE::Version::IR_VERSION};
-
- // Is model using latest ONNX opset
- bool using_latest_onnx_opset_{false};
-
- ResolveContext resolve_context_;
-
- // the parent graph if this is a subgraph.
- Graph* parent_graph_;
- // the node containing the graph if parent_graph_ is not nullptr
- const Node* parent_node_;
-
- // NodeArgs that come from outer scope. Used when building a graph so that
- // these don't get recorded as graph inputs in the GraphProto.
- std::unordered_set<std::string> outer_scope_node_arg_names_;
-
- // number of times Resolve has run.
- int num_resolves_ = 0;
-
- const logging::Logger& logger_;
-
- // distinguishes between graph loaded from model file and graph created from scratch
- const bool is_loaded_from_model_file_;
-};
-
-#if !defined(ORT_MINIMAL_BUILD)
-std::ostream& operator<<(std::ostream& out, const Graph& graph);
-#endif
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/graph_nodes.h b/include/onnxruntime/core/graph/graph_nodes.h
deleted file mode 100755
index 422fe95..0000000
--- a/include/onnxruntime/core/graph/graph_nodes.h
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <memory>
-#include <type_traits>
-#include <vector>
-
-namespace onnxruntime {
-
-class Node;
-
-/**
-Class to filter out null entries from either a vector of unique_ptr<Node> or a vector of [const] Node* and
-provide an iterator interface that returns [const] Node& for the valid entries.
-*/
-template <typename TNodesContainer>
-class ValidNodes {
- public:
- template <typename TIterator>
- class NodeIterator;
-
- // optional filtering function to return a subset of nodes
- using NodeFilterFunc = std::function<bool(NodeIndex)>;
-
- /**
- Construct a ValidNodes instance to provide iteration over all valid nodes in the TNodesCollection
- @param[in] nodes Nodes to iterate, skipping invalid entries.
- */
- explicit ValidNodes(TNodesContainer& nodes) noexcept : nodes_(&nodes) {}
-
- explicit ValidNodes(TNodesContainer& nodes, NodeFilterFunc&& filter_node_fn) noexcept
- : nodes_(&nodes), filter_node_fn_{std::move(filter_node_fn)} {}
-
- using ConstNodeIterator = NodeIterator<typename TNodesContainer::const_iterator>;
- using MutableNodeIterator = NodeIterator<typename TNodesContainer::iterator>;
- using ConstReverseNodeIterator = NodeIterator<typename TNodesContainer::const_reverse_iterator>;
-
- ConstNodeIterator cbegin() const noexcept {
- return {nodes_->cbegin(), nodes_->cend(), filter_node_fn_};
- }
-
- ConstNodeIterator cend() const noexcept {
- return {nodes_->cend(), nodes_->cend(), filter_node_fn_};
- }
-
- ConstNodeIterator begin() const noexcept {
- return cbegin();
- }
-
- ConstNodeIterator end() const noexcept {
- return cend();
- }
-
- ConstReverseNodeIterator rbegin() const noexcept {
- return {nodes_->crbegin(), nodes_->crend(), filter_node_fn_};
- }
-
- ConstReverseNodeIterator rend() const noexcept {
- return {nodes_->crend(), nodes_->crend(), filter_node_fn_};
- }
-
- // we only allow mutable access if the container is non-const.
- // we need to templatize the functions for enable_if to work at this level, but mandate T2 being TNodesContainer
- template <typename T2 = TNodesContainer>
- typename std::enable_if<!std::is_const<T2>::value, MutableNodeIterator>::type begin() noexcept {
- static_assert(std::is_same<T2, TNodesContainer>::value, "Explicit specialization is not allowed");
- return MutableNodeIterator(nodes_->begin(), nodes_->end(), filter_node_fn_);
- }
-
- template <typename T2 = TNodesContainer>
- typename std::enable_if<!std::is_const<T2>::value, MutableNodeIterator>::type end() noexcept {
- static_assert(std::is_same<T2, TNodesContainer>::value, "Explicit specialization is not allowed");
- return MutableNodeIterator(nodes_->end(), nodes_->end(), filter_node_fn_);
- }
-
- bool empty() const noexcept { return nodes_->empty(); }
-
- /**
- @class NodeIterator
- Iterator to provide const and non-const access to valid Node instances in a Graph.
- @remarks Skips invalid nodes.
- */
- template <typename TIterator>
- class NodeIterator {
- // get the type being returned by the iterator. can't use TIterator::value_type as that is always non-const
- using IterType = typename std::remove_reference<typename std::iterator_traits<TIterator>::reference>::type;
- // and determine what we will return based on its constness
- using T = typename std::conditional<std::is_const<IterType>::value,
- const Node, // return const Node if this is a const iterator
- Node>::type; // else return Node
-
- public:
- using iterator_category = std::input_iterator_tag;
- using value_type = T;
- using difference_type = typename TIterator::difference_type;
- using pointer = T*;
- using reference = T&;
- using const_reference = const T&;
-
- /** Construct a NodeInterator and move to the first valid node. */
- NodeIterator<TIterator>(const TIterator current, const TIterator end, const NodeFilterFunc& filter_fn) noexcept
- : current_{current}, end_{end}, apply_filter_{filter_fn != nullptr}, filter_func_{&filter_fn} {
- // skip to next valid node, stopping at end if none are found
- while (current_ < end && (*current_ == nullptr ||
- (apply_filter_ && (*filter_func_)((*current_)->Index()) == true))) {
- ++current_;
- }
- }
-
- bool operator==(const NodeIterator<TIterator>& other) const noexcept {
- return (current_ == other.current_);
- }
-
- bool operator!=(const NodeIterator<TIterator>& other) const noexcept {
- return (current_ != other.current_);
- }
-
- void operator++() {
- if (current_ < end_) {
- while (++current_ != end_) {
- if (*current_ != nullptr && (!apply_filter_ || (*filter_func_)((*current_)->Index()) == false))
- break;
- }
- }
- }
-
- NodeIterator<TIterator> operator++(int) {
- NodeIterator<TIterator> tmp{*this};
- ++(*this);
-
- return tmp;
- }
-
- /** Return the current Node&. This will be const if the iterator was returned from a const GraphNodes instance. */
- reference operator*() {
- // if iterator is valid we always have a non-nullptr node
- // if this is a nullptr we're at end_ and this shouldn't be being called
- return **current_;
- }
-
- pointer operator->() {
- return current_->get();
- }
-
- private:
- TIterator current_;
- TIterator end_;
- bool apply_filter_; // store whether filter_func_ is not nullptr and contains a callable
- const NodeFilterFunc* filter_func_; // store as pointer so iterator is copyable
- };
-
- private:
- gsl::not_null<TNodesContainer*> nodes_; // always set by ctor
-
- // no filtering if not set. this instance owns the filter func if set.
- NodeFilterFunc filter_node_fn_;
-};
-
-/**
-Class that provides iteration over all valid nodes in the Graph.
-*/
-class GraphNodes : public ValidNodes<std::vector<std::unique_ptr<Node>>> {
- public:
- GraphNodes(std::vector<std::unique_ptr<Node>>& nodes) : ValidNodes(nodes) {
- }
-};
-
-// Variant that only ever allows const access to nodes and optionally allows filtering of the nodes.
-class ConstGraphNodes : public ValidNodes<const std::vector<std::unique_ptr<Node>>> {
- public:
- ConstGraphNodes(const std::vector<std::unique_ptr<Node>>& nodes) : ValidNodes(nodes) {
- }
-
- ConstGraphNodes(const std::vector<std::unique_ptr<Node>>& nodes,
- GraphNodes::NodeFilterFunc&& filter_func)
- : ValidNodes(nodes, std::move(filter_func)) {
- }
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/graph_viewer.h b/include/onnxruntime/core/graph/graph_viewer.h
deleted file mode 100755
index b2d9ee2..0000000
--- a/include/onnxruntime/core/graph/graph_viewer.h
+++ /dev/null
@@ -1,196 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/graph/graph.h"
-#include "core/framework/session_options.h"
-#include <unordered_set>
-
-namespace onnxruntime {
-class Function;
-struct IndexedSubGraph;
-} // namespace onnxruntime
-
-namespace onnxruntime {
-
-// use value-based compare to make sure transformer output order is consistent
-struct NodeCompare {
- bool operator()(const Node* n1, const Node* n2) const;
-};
-
-/**
-@class GraphViewer
-Class that provides a read-only view of the Graph.
-@remarks If the underlying Graph is changed, GetNodesInTopologicalOrder and GetRootNodes may become invalid.
-*/
-class GraphViewer {
- public:
- /**
- Construct a GraphViewer from the provided Graph instance.
- */
- explicit GraphViewer(const Graph& graph);
-
- /**
- Construct a GraphViewer from the provided Graph instance, filtering to the nodes specified in the IndexedSubGraph
- */
- explicit GraphViewer(const Graph& graph, const IndexedSubGraph& filter_info);
-
- /** Gets the Graph name. */
- const std::string& Name() const noexcept;
-
- /** Gets the Graph description. */
- const std::string& Description() const noexcept;
-
- /** Gets the path of the owning model if any **/
- const Path& ModelPath() const noexcept { return graph_->ModelPath(); }
-
- /**
- Gets a tensor created from an initializer.
- @param tensor_name The tensor name
- @param[out] value Sets the pointer to the TensorProto if found, or nullptr if not.
- @returns True if found. False if not.
- */
- bool GetInitializedTensor(const std::string& tensor_name, const ONNX_NAMESPACE::TensorProto*& value) const;
-
- /** Returns true if an initializer value can be overridden by a graph input with the same name. */
- bool CanOverrideInitializer() const noexcept;
-
- /**
- Gets the Graph inputs, excluding initializers.
- @returns Collection of NodeArg pointers for the graph inputs, excluding inputs that have matching initializers.
- @remarks No nullptr values in the returned collection. The order will be the same as in the GraphProto.
- Inputs are for filter_info_ if set.
- */
- const std::vector<const NodeArg*>& GetInputs() const noexcept;
-
- /**
- Gets the Graph inputs, including any initializers.
- @returns Collection of NodeArg pointers for all the graph inputs.
- @remarks No nullptr values in the returned collection. The order will be the same as in the GraphProto.
- Inputs are for filter_info_ if set.
- */
- const std::vector<const NodeArg*>& GetInputsIncludingInitializers() const noexcept;
-
- /**
- Gets the Graph outputs.
- @returns Collection of NodeArg pointers for all the graph outputs.
- @remarks No nullptr values in the returned collection. The order will be the same as in the GraphProto.
- Outputs are for filter_info_ if set.
- */
- const std::vector<const NodeArg*>& GetOutputs() const noexcept;
-
- /** Gets all ValueInfo NodeArg instances in the Graph.
- @remarks NOT filtered using filter_info_.
- */
- const std::vector<const NodeArg*>& GetValueInfo() const noexcept;
-
- /**
- Gets the Node instance at the specified index.
- @param node_index Index to retrieve Node from.
- @remarks May return nullptr if index no longer points to a valid node due to the node being freed, or if
- node is excluded by filter_info_.
- */
- const Node* GetNode(NodeIndex node_index) const;
-
- /** Gets an iterator over all the valid Nodes in the Graph.
- @remarks Nodes are filtered using filter_info_ if set.
- */
- const ConstGraphNodes& Nodes() const noexcept;
-
- /** Gets the number of valid nodes in the Graph.
- @remarks Returns the number of nodes in filter_info_ if set.
- */
- int NumberOfNodes() const noexcept;
-
- /** Gets the maximum NodeIndex value used by Nodes in the Graph. */
- int MaxNodeIndex() const noexcept;
-
- /** Gets the NodeIndex values for the Graph nodes, sorted into topological order.
- @remarks Filtered using filter_info_ if set.
- */
- const std::vector<NodeIndex>& GetNodesInTopologicalOrder(ExecutionOrder order = ExecutionOrder::DEFAULT) const;
-
- /**
- Gets the NodeIndex values for the root nodes in the Graph.
- The root nodes are the topmost nodes in the Graph that receive inputs from the Graph inputs
- and no other nodes in the Graph.
- @remarks Not supported if filter_info_ is set.
- */
- const std::vector<NodeIndex>& GetRootNodes() const;
-
- /** Gets all tensors created from initializers. */
- const InitializedTensorSet& GetAllInitializedTensors() const noexcept;
-
- /**
- Gets the NodeArg instance for the given name.
- @returns A NodeArg if found, a nullptr if not.
- */
- const NodeArg* GetNodeArg(const std::string& name) const;
-
- /** Gets the map of operator domains to their opset versions. */
- const std::unordered_map<std::string, int>& DomainToVersionMap() const noexcept {
- return graph_->DomainToVersionMap();
- }
-
- /** Checks if this is a Subgraph */
- bool IsSubgraph() const;
-
- /** Get the internal graph*/
- const Graph& GetGraph() const { return *graph_; }
-
- /**
- returns true if 'name' is an initializer, and is constant and cannot be overridden at runtime.
- @param check_outer_scope If true and the 'graph_' is a subgraph, check parent graph/s for 'name'
- if the name is not found in 'graph_'.
- */
- bool IsConstantInitializer(const std::string& name, bool check_outer_scope) const;
-
- /** Get the Node containing this Graph if IsSubgraph is true. Returns nullptr otherwise. */
- const Node* ParentNode() const noexcept { return graph_->ParentNode(); }
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Get the consumer nodes of a node arg */
- std::vector<const Node*> GetConsumerNodes(const std::string& node_arg_name) const {
- return graph_->GetConsumerNodes(node_arg_name);
- }
-
- /** Get the producer node of a node arg */
- const Node* GetProducerNode(const std::string& node_arg_name) const {
- return graph_->GetProducerNode(node_arg_name);
- }
-#endif
-
- /** Get the filter info that restricts the graph viewer to a subset of nodes if set.
- @returns Filter info or nullptr
- */
- const IndexedSubGraph* GetFilterInfo() const { return filter_info_; }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(GraphViewer);
- GraphViewer(const Graph& graph, const IndexedSubGraph* filter_info);
-
- const Graph* graph_;
- ConstGraphNodes graph_nodes_;
-
- // The NodeIndex values of the graph nodes sorted in topological order.
- std::vector<NodeIndex> nodes_in_topological_order_;
-
-#if !defined(ORT_MINIMAL_BUILD)
- // The NodeIndex values of the graph nodes sorted in topological order with priority.
- std::vector<NodeIndex> nodes_in_topological_order_with_priority_;
-#endif
-
- // Graph root nodes.
- std::vector<NodeIndex> root_nodes_;
-
- // if we're limiting the view to an IndexedSubGraph we need to create a few pieces of infrastructure that would
- // usually come from the full graph
- const IndexedSubGraph* filter_info_{nullptr};
- std::unordered_set<NodeIndex> filtered_node_indices_;
- std::vector<const NodeArg*> filtered_node_inputs_;
- std::vector<const NodeArg*> filtered_node_inputs_including_initializers_;
- std::vector<const NodeArg*> filtered_node_outputs_;
- InitializedTensorSet filtered_initializers_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/indexed_sub_graph.h b/include/onnxruntime/core/graph/indexed_sub_graph.h
deleted file mode 100755
index b0485c4..0000000
--- a/include/onnxruntime/core/graph/indexed_sub_graph.h
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "core/graph/basic_types.h"
-#include "core/graph/onnx_protobuf.h"
-
-namespace onnxruntime {
-
-class OpKernel;
-class OpKernelInfo;
-
-/**
-@class IndexedSubGraph
-
-Class containing information about a subgraph of Nodes from a Graph.
-It contains a NodeIndex array of the Nodes covered by the subgraph,
-and the meta definition needed for representing this subgraph as a FunctionProto,
-which could be serialized/saved to a model file.
-*/
-struct IndexedSubGraph {
- struct MetaDef {
- std::string name; ///< Name of customized SubGraph/FunctionProto
- std::string domain; ///< Domain of customized SubGraph/FunctionProto
- int since_version; ///< Since version of customized SubGraph/FunctionProto.
-
- ONNX_NAMESPACE::OperatorStatus status; ///< Status of customized SubGraph/FunctionProto.
-
- std::vector<std::string> inputs; ///< Inputs of customized SubGraph/FunctionProto.
- std::vector<std::string> outputs; ///< Outputs of customized SubGraph/FunctionProto.
- NodeAttributes attributes; ///< Attributes of customized SubGraph/FunctionProto.
-
- std::string doc_string; ///< Doc string of customized SubGraph/FunctionProto.
- };
-
- /** Nodes covered by this subgraph. The NodeIndex values are from the parent Graph.*/
- std::vector<onnxruntime::NodeIndex> nodes;
-
- /** Set the meta definition needed to represent this subgraph as a FunctionProto
- It's needed IF AND ONLY IF there are multiple indexes contained in #nodes. */
- void SetMetaDef(std::unique_ptr<MetaDef>&& meta_def_) {
- meta_def = std::move(meta_def_);
- }
-
- /** Gets the meta definition needed to represent this subgraph as a FunctionProto.
- @returns MetaDef instance if it has been set. nullptr if not. */
- const MetaDef* GetMetaDef() const {
- return meta_def.get();
- }
-
- private:
- // subgraph meta definition.
- std::unique_ptr<MetaDef> meta_def;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/node_arg.h b/include/onnxruntime/core/graph/node_arg.h
deleted file mode 100755
index eeb53d2..0000000
--- a/include/onnxruntime/core/graph/node_arg.h
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/graph/basic_types.h"
-#include "core/graph/onnx_protobuf.h"
-
-namespace onnxruntime {
-
-// Node argument definition, for both input and output,
-// including arg name, arg type (contains both type and shape).
-//
-// Design Question: in my opinion, shape should not be part of type.
-// We may align the protobuf design with our operator registry interface,
-// which has type specified for each operator, but no shape. Well, shape
-// should be inferred with a separate shape inference function given
-// input shapes, or input tensor data sometimes.
-// With shape as part of type (current protobuf design),
-// 1) we'll have to split the "TypeProto" into type and shape in this internal
-// representation interface so that it could be easily used when doing type
-// inference and matching with operator registry.
-// 2) SetType should be always called before SetShape, otherwise, SetShape()
-// will fail. Because shape is located in a TypeProto.
-// Thoughts?
-//
-
-/**
-@class NodeArg
-Class representing a data type that is input or output for a Node, including the shape if it is a Tensor.
-*/
-class NodeArg {
- public:
- /**
- Construct a new NodeArg.
- @param name The name to use.
- @param p_arg_type Optional TypeProto specifying type and shape information.
- */
- NodeArg(const std::string& name,
- const ONNX_NAMESPACE::TypeProto* p_arg_type);
-
- NodeArg(NodeArg&&) = default;
- NodeArg& operator=(NodeArg&& other) = default;
-
- /** Gets the name. */
- const std::string& Name() const noexcept;
-
- /** Gets the data type. */
- ONNX_NAMESPACE::DataType Type() const noexcept;
-
- /** Gets the TypeProto
- @returns TypeProto if type is set. nullptr otherwise. */
- const ONNX_NAMESPACE::TypeProto* TypeAsProto() const noexcept;
-
- /** Gets the shape if NodeArg is for a Tensor.
- @returns TensorShapeProto if shape is set. nullptr if there's no shape specified. */
- const ONNX_NAMESPACE::TensorShapeProto* Shape() const;
-
- /** Return an indicator.
- @returns true if NodeArg is a normal tensor with a non-empty shape or a scalar with an empty shape. Otherwise, returns false. */
- bool HasTensorOrScalarShape() const;
-
-#if !defined(ORT_MINIMAL_BUILD)
- /** Sets the shape.
- @remarks Shape can only be set if the TypeProto was provided to the ctor, or #SetType has been called,
- as the shape information is stored as part of TypeProto. */
- void SetShape(const ONNX_NAMESPACE::TensorShapeProto& shape);
-
- /** Clears shape info.
- @remarks If there is a mismatch during shape inferencing that can't be resolved the shape info may be removed. */
- void ClearShape();
-
- /** Validate and merge type [and shape] info from input_type.
- @param strict If true, the shape update will fail if there are incompatible values.
- If false, will be lenient and merge only shape info that can be validly processed.
- @param override_types If true, resolve the two inputs or two outputs type when different
- @returns Success unless there is existing type or shape info that can't be successfully updated. */
- common::Status UpdateTypeAndShape(const ONNX_NAMESPACE::TypeProto& input_type, bool strict, bool override_types, const logging::Logger& logger);
-
- /** Validate and merge type [and shape] info from node_arg.
- @param strict If true, the shape update will fail if there are incompatible values.
- If false, will be lenient and merge only shape info that can be validly processed.
- @param override_types If true, resolve the two inputs or two outputs type when different
- @returns Success unless there is existing type or shape info that can't be successfully updated. */
- common::Status UpdateTypeAndShape(const NodeArg& node_arg, bool strict, bool override_types, const logging::Logger& logger);
-
-#endif // !defined(ORT_MINIMAL_BUILD)
-
- /** Gets this NodeArg as a ValueInfoProto. */
- const NodeArgInfo& ToProto() const noexcept { return node_arg_info_; }
-
- /** Gets a flag indicating whether this NodeArg exists or not.
- Optional inputs are allowed in ONNX and an empty #Name represents a non-existent input argument. */
- bool Exists() const noexcept;
-
- private:
- ORT_DISALLOW_COPY_AND_ASSIGNMENT(NodeArg);
- friend class Graph;
-
- NodeArg(NodeArgInfo&& node_arg_info);
-
-#if !defined(ORT_MINIMAL_BUILD)
- void SetType(ONNX_NAMESPACE::DataType p_type);
- void SetType(const ONNX_NAMESPACE::TypeProto& type_proto);
-#endif
-
- // Node arg PType.
- ONNX_NAMESPACE::DataType type_;
-
- // Node arg name, type and shape.
- NodeArgInfo node_arg_info_;
-
- // Flag indicates whether <*this> node arg exists or not.
- bool exists_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/graph/onnx_protobuf.h b/include/onnxruntime/core/graph/onnx_protobuf.h
deleted file mode 100755
index 23a601e..0000000
--- a/include/onnxruntime/core/graph/onnx_protobuf.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-//TODO(): delete this file from public interface
-#ifdef __GNUC__
-#include "onnxruntime_config.h"
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wignored-qualifiers"
-#pragma GCC diagnostic ignored "-Wunused-parameter"
-#ifdef HAS_DEPRECATED_DECLARATIONS
-#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-#endif
-#else
-#pragma warning(push)
-#pragma warning(disable : 4018) /*'expression' : signed/unsigned mismatch */
-#pragma warning(disable : 4065) /*switch statement contains 'default' but no 'case' labels*/
-#pragma warning(disable : 4100)
-#pragma warning(disable : 4146) /*unary minus operator applied to unsigned type, result still unsigned*/
-#pragma warning(disable : 4127)
-#pragma warning(disable : 4244) /*'conversion' conversion from 'type1' to 'type2', possible loss of data*/
-#pragma warning(disable : 4251) /*'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'*/
-#pragma warning(disable : 4267) /*'var' : conversion from 'size_t' to 'type', possible loss of data*/
-#pragma warning(disable : 4305) /*'identifier' : truncation from 'type1' to 'type2'*/
-#pragma warning(disable : 4307) /*'operator' : integral constant overflow*/
-#pragma warning(disable : 4309) /*'conversion' : truncation of constant value*/
-#pragma warning(disable : 4334) /*'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?)*/
-#pragma warning(disable : 4355) /*'this' : used in base member initializer list*/
-#pragma warning(disable : 4506) /*no definition for inline function 'function'*/
-#pragma warning(disable : 4800) /*'type' : forcing value to bool 'true' or 'false' (performance warning)*/
-#pragma warning(disable : 4996) /*The compiler encountered a deprecated declaration.*/
-#pragma warning(disable : 6011) /*Dereferencing NULL pointer*/
-#pragma warning(disable : 6387) /*'value' could be '0'*/
-#pragma warning(disable : 26495) /*Variable is uninitialized.*/
-#endif
-
-#if !defined(ORT_MINIMAL_BUILD)
-#include "onnx/defs/schema.h"
-#else
-#include "onnx/defs/data_type_utils.h"
-#endif
-
-#include "onnx/onnx_pb.h"
-#include "onnx/onnx-operators_pb.h"
-
-#ifdef __GNUC__
-#pragma GCC diagnostic pop
-#else
-#pragma warning(pop)
-#endif
diff --git a/include/onnxruntime/core/graph/schema_registry.h b/include/onnxruntime/core/graph/schema_registry.h
deleted file mode 100755
index 0c7b0ce..0000000
--- a/include/onnxruntime/core/graph/schema_registry.h
+++ /dev/null
@@ -1,158 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#include "core/graph/constants.h"
-#include "core/common/common.h"
-#include "core/common/status.h"
-#include "core/graph/onnx_protobuf.h"
-#include "core/platform/ort_mutex.h"
-#include <mutex>
-#include <deque>
-#include "sstream"
-
-namespace onnxruntime {
-using OpName_Domain_Version_Schema_Map = std::unordered_map<
- std::string,
- std::unordered_map<std::string, std::map<ONNX_NAMESPACE::OperatorSetVersion, ONNX_NAMESPACE::OpSchema>>>;
-
-/**
-@struct SchemaRegistryVersion
-onnxruntime schema registry is a supplement to the built-in ONNX schema.
-Every schema registry represent a collection of schema deltas from baseline_opset_version to opset_version
-*/
-struct SchemaRegistryVersion {
- int baseline_opset_version;
- int opset_version;
-};
-
-using DomainToVersionMap = std::unordered_map<std::string, int>;
-using DomainToVersionRangeMap = std::unordered_map<std::string, SchemaRegistryVersion>;
-
-class IOnnxRuntimeOpSchemaCollection : public ONNX_NAMESPACE::ISchemaRegistry {
- public:
- virtual DomainToVersionMap GetLatestOpsetVersions(bool is_onnx_only) const = 0;
-
- using ISchemaRegistry::GetSchema;
-
- const ONNX_NAMESPACE::OpSchema* GetSchema(const std::string& key, const int maxInclusiveVersion,
- const std::string& domain) const final {
- const ONNX_NAMESPACE::OpSchema* latest_schema = nullptr;
- int earliest_opset_where_unchanged = std::numeric_limits<int>::max();
- GetSchemaAndHistory(key, maxInclusiveVersion, domain, &latest_schema, &earliest_opset_where_unchanged);
-
- assert(latest_schema == nullptr || (latest_schema->SinceVersion() <= maxInclusiveVersion &&
- earliest_opset_where_unchanged == latest_schema->SinceVersion()));
-
- return latest_schema;
- }
-
- virtual void GetSchemaAndHistory(
- const std::string& key,
- int maxInclusiveVersion,
- const std::string& domain,
- const ONNX_NAMESPACE::OpSchema** latest_schema,
- int* earliest_opset_where_unchanged) const = 0;
-};
-
-/**
-@class OnnxRuntimeOpSchemaRegistry
-
-OnnxRuntimeOpSchemaRegistry is used to provide supplement for built-in ONNX schemas.
-Each OnnxRuntimeOpSchemaRegistry must register complete opsets delta from a baseline version to max opset version.
-(Please notice that baseline opsets are not include in the delta)
-
-For example, ONNXRuntime is build with ONNX 1.2 which is at opset7, to use ONNX opset8 and opset9,
-user could create a OnnxRuntimeOpSchemaRegistry and config it as {baseline_opset_version = 7, opset_version = 9}
-it means this OnnxRuntimeOpSchemaRegistry contains the complete delta from opset7 to opset9.
-*/
-class OnnxRuntimeOpSchemaRegistry : public IOnnxRuntimeOpSchemaCollection {
- public:
- OnnxRuntimeOpSchemaRegistry() = default;
-
- common::Status SetBaselineAndOpsetVersionForDomain(
- const std::string& domain,
- int baseline_opset_version,
- int opset_version);
-
- DomainToVersionMap GetLatestOpsetVersions(bool is_onnx_only) const override;
-
- // OnnxRuntimeOpSchemaRegistry must register complete delta for a opset.
- common::Status RegisterOpSet(
- std::vector<ONNX_NAMESPACE::OpSchema>& schemas,
- const std::string& domain,
- int baseline_opset_version,
- int opset_version);
-
- using IOnnxRuntimeOpSchemaCollection::GetSchema;
-
- void GetSchemaAndHistory(const std::string& key, int maxInclusiveVersion, const std::string& domain,
- const ONNX_NAMESPACE::OpSchema** latest_schema,
- int* earliest_opset_where_unchanged) const override;
-
- bool empty() const {
- return map_.empty();
- }
-
- private:
- common::Status RegisterOpSchema(ONNX_NAMESPACE::OpSchema&& op_schema);
-
- common::Status RegisterOpSchemaInternal(ONNX_NAMESPACE::OpSchema&& op_schema);
-
- OrtMutex mutex_;
-
- OpName_Domain_Version_Schema_Map map_;
- DomainToVersionRangeMap domain_version_range_map_;
-};
-
-/**
-@class SchemaRegistryManager
-
-SchemaRegistryManager provides a view based on built-in ONNX schema and a list of
-OnnxRuntimeOpSchemaRegistry as supplement.
-
-The user needs to make sure the customized schema registry is valid, otherwise the behavior is undefined.
-
-@todo We may add more consistency checks later.
-*/
-class SchemaRegistryManager : public onnxruntime::IOnnxRuntimeOpSchemaCollection {
- public:
- /**
- Register a new schema registry instance.
- @remarks The schema registry priority is the reverse of registration order. i.e. the last registry added will be
- searched first for a matching OpSchema.
- */
- void RegisterRegistry(std::shared_ptr<IOnnxRuntimeOpSchemaCollection> registry);
-
- /** Gets the latest opset versions.
- @param is_onnx_only If true, return the latest ONNX schemas. If false, return the latest schemas for all domains.
- */
- DomainToVersionMap GetLatestOpsetVersions(bool is_onnx_only) const override;
-
- /** Gets the last released opset versions.
- @param is_onnx_only If true, return ONNX schemas only. If false, return the schemas for all domains.
- */
- DomainToVersionMap GetLastReleasedOpsetVersions(bool is_onnx_only) const ;
- /**
- Gets the OpSchema and its history.
- Searches custom schema registries starting with the last one added. \
- If the OpSchema is not found the default ONNX schema registry is searched.
-
- @param key Operator type.
- @param max_inclusive_version Maximum opset version allowed, inclusive.
- @param domain The domain of the operator.
- @param[out] latest_schema Returns the latest OpSchema if found. nullptr otherwise.
- @param[out] earliest_opset_where_unchanged The earliest opset version preceding max_inclusive_version where the
- operator is known to be unchanged.
- */
- void GetSchemaAndHistory(const std::string& key, int max_inclusive_version, const std::string& domain,
- const ONNX_NAMESPACE::OpSchema** latest_schema,
- int* earliest_opset_where_unchanged) const override;
-
- private:
- void GetDomainToVersionMapForRegistries(DomainToVersionMap& domain_version_map, bool is_onnx_only) const;
-
- std::deque<std::shared_ptr<IOnnxRuntimeOpSchemaCollection>> registries;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/optimizer/graph_transformer.h b/include/onnxruntime/core/optimizer/graph_transformer.h
deleted file mode 100755
index 865a9f3..0000000
--- a/include/onnxruntime/core/optimizer/graph_transformer.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#include <string>
-#include <unordered_set>
-
-#include "core/common/common.h"
-#include "core/graph/graph_viewer.h"
-#include "core/optimizer/graph_transformer_level.h"
-
-namespace onnxruntime {
-
-/**
-@class GraphTransformer
-
-The interface for in-place transformation of a Graph.
-*/
-class GraphTransformer {
- public:
- GraphTransformer(const std::string& name, const std::unordered_set<std::string>& compatible_execution_providers = {})
- : name_(name), compatible_provider_types_(compatible_execution_providers) {
- }
-
- virtual ~GraphTransformer() = default;
-
- /** Gets the name of this graph transformer. */
- const std::string& Name() const noexcept {
- return name_;
- }
-
- const std::unordered_set<std::string>& GetCompatibleExecutionProviders() const noexcept {
- return compatible_provider_types_;
- }
-
- /** Apply the in-place transformation defined by this transformer to the provided Graph instance.
- @param[out] modified Set to true if the Graph was modified.
- @returns Status with success or error information.
- */
- common::Status Apply(Graph& graph, bool& modified, const logging::Logger& logger) const;
-
- virtual bool ShouldOnlyApplyOnce() const { return false; }
-
- protected:
- /** Helper method to call ApplyImpl on any subgraphs in the Node. */
- common::Status Recurse(Node& node, bool& modified, int graph_level, const logging::Logger& logger) const {
- int subgraph_level = ++graph_level;
- for (auto& entry : node.GetAttributeNameToMutableSubgraphMap()) {
- auto& subgraph = *entry.second;
- ORT_RETURN_IF_ERROR(ApplyImpl(subgraph, modified, subgraph_level, logger));
- }
-
- return Status::OK();
- }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(GraphTransformer);
-
- // Apply the transform to the graph.
- // graph_level is 0 for the main graph, and is incremented when descending into the subgraph of a node.
- // You MUST call Recurse for all valid Nodes in the graph to ensure any subgraphs in control flow nodes
- // (Scan/If/Loop) are processed as well.
- // You should avoid calling Graph::Resolve in ApplyImpl unless you are 100% sure it's required. In most cases
- // the call to Graph::Resolve in Apply prior to ApplyImpl being called, and after ApplyImpl fore the main graph
- // completes (if 'modified' is true) should suffice.
- virtual common::Status ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger)
- const = 0;
-
- const std::string name_;
- const std::unordered_set<std::string> compatible_provider_types_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/optimizer/graph_transformer_level.h b/include/onnxruntime/core/optimizer/graph_transformer_level.h
deleted file mode 100755
index cc05b21..0000000
--- a/include/onnxruntime/core/optimizer/graph_transformer_level.h
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/common.h"
-
-namespace onnxruntime {
-
-// Graph transformer level
-// refer to docs/ONNX_Runtime_Graph_Optimizations.md for details
-enum class TransformerLevel : int {
- Default = 0, // required transformers only
- Level1, // basic optimizations
- Level2, // extended optimizations
- Level3, // layout optimizations
- // The max level should always be same as the last level.
- MaxLevel = Level3
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/optimizer/graph_transformer_utils.h b/include/onnxruntime/core/optimizer/graph_transformer_utils.h
deleted file mode 100755
index b5d0287..0000000
--- a/include/onnxruntime/core/optimizer/graph_transformer_utils.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <gsl/gsl>
-
-#include "core/optimizer/graph_transformer.h"
-#include "core/optimizer/rule_based_graph_transformer.h"
-#include "core/optimizer/rewrite_rule.h"
-
-namespace onnxruntime {
-struct FreeDimensionOverride;
-class IExecutionProvider;
-
-namespace optimizer_utils {
-
-/** Generates all predefined rules for this level.
- If rules_to_enable is not empty, it returns the intersection of predefined rules and rules_to_enable.
- TODO: This is visible for testing at the moment, but we should rather make it private. */
-std::vector<std::unique_ptr<RewriteRule>> GenerateRewriteRules(TransformerLevel level,
- const std::vector<std::string>& rules_to_enable = {});
-
-/** Generates all predefined (both rule-based and non-rule-based) transformers for this level.
- If transformers_and_rules_to_enable is not empty, it returns the intersection between the predefined transformers/rules
- and the transformers_and_rules_to_enable. */
-std::vector<std::unique_ptr<GraphTransformer>> GenerateTransformers(TransformerLevel level,
- gsl::span<const FreeDimensionOverride> free_dimension_overrides,
- const IExecutionProvider& execution_provider /*required by constant folding*/,
- const std::vector<std::string>& rules_and_transformers_to_enable = {});
-
-/** Given a TransformerLevel, this method generates a name for the rule-based graph transformer of that level. */
-std::string GenerateRuleBasedTransformerName(TransformerLevel level);
-
-/** Generates all rule-based transformers for this level. */
-std::unique_ptr<RuleBasedGraphTransformer> GenerateRuleBasedGraphTransformer(TransformerLevel level,
- const std::vector<std::string>& rules_to_enable,
- const std::unordered_set<std::string>& compatible_execution_providers);
-
-} // namespace optimizer_utils
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/optimizer/rewrite_rule.h b/include/onnxruntime/core/optimizer/rewrite_rule.h
deleted file mode 100755
index 43e7489..0000000
--- a/include/onnxruntime/core/optimizer/rewrite_rule.h
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/common.h"
-#include "core/graph/graph_viewer.h"
-
-namespace onnxruntime {
-
-/**
-@class RewriteRule
-
-The base class for a rewrite rule. A rewrite rule represents a semantics-preserving transformation of a
-computation graph. It can be used to represent, for example, the elimination of operators that serve as
-no-ops (e.g., dropout during inference), as well as inlining of "function" definitions or the dual operation
-of replacing a complex expression by an equivalent function-call). Unlike the more general GraphTransformer,
-a rewrite rule is a more local transformation that is triggered on a particular node of the graph.
-
-Each rule has a set of conditions and a body. The conditions have to be satisfied for the body of the rule
-to be triggered. Therefore, when creating a new rewrite rule, two main functions have to be implemented:
-- SatisfyCondition defines the condition checks. It is advisable to add the more selective checks first,
- because those will lead to discarding fast rules that cannot be applied on a node.
-- Apply is the actual body of the rule that will be executed if SatisfyCondition returns true for a particular
- node. Note that additional, more complex checks can be included in the Apply if putting them in the
- SatisfyCondition would lead to duplicate work (e.g., when we make a check on a Node attribute but we need
- that attribute to execute the rule too).
-In general, simple fast checks are a better fit for SatisfyCondition, whereas more complex ones can be added
-in the Apply.
-
-In order to avoid evaluating the SatisfyCondition for each rule and each node of the graph, each rewrite rule
-should specify the target op types for which a rule will be evaluated, by overriding the TargetOpTypes() function.
-If the op type of a node is not included in the target op types of a rule, that rule would not be considered at all.
-If the list of op types is left empty, that rule will be triggered for every op type.
-*/
-class RewriteRule {
- public:
- /**
- @class RewriteRuleEffect
-
- Class used to indicate the effect of rule application on a graph's node.
- */
- enum class RewriteRuleEffect : uint8_t {
- kNone, // The rewrite rule has not modified the graph.
- kUpdatedCurrentNode, // The rewrite rule updated (but did not remove) the node on which it was triggered.
- kRemovedCurrentNode, // The rewrite rule removed the node on which it was triggered.
- kModifiedRestOfGraph // The rewrite rule modified nodes other than the one it was triggered on.
- };
-
- RewriteRule(const std::string& name) : name_(name) {}
-
- virtual ~RewriteRule() = default;
-
- /** Gets the name of this rewrite rule. */
- const std::string& Name() const noexcept {
- return name_;
- }
-
- /** Returns the node op types for which this rule will be triggered. If the op type of a node is not included in the
- target op types of a rule, that rule would not be considered at all. Returning an empty list indicates that we
- will attempt to trigger the rule for every op type. */
- virtual std::vector<std::string> TargetOpTypes() const noexcept = 0;
-
- /** Checks if the condition of the rule is satisfied, and if so applies the body of the rule.
- @param[in] graph The Graph.
- @param[in] node The Node to apply the rewrite to.
- @param[out] rule_effect Enum to indicate if and how the graph was modified as a result of the rule application.
- @returns Status indicating success or providing error information */
- common::Status CheckConditionAndApply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect, const logging::Logger& logger) const {
- return SatisfyCondition(graph, node, logger) ? Apply(graph, node, rule_effect, logger) : Status::OK();
- }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(RewriteRule);
-
- const std::string name_;
-
- /** Checks if the Node of the given Graph satisfies the conditions of this rule. The body of the rule will be
- evaluated if this condition function returns true. This can include a more complex pattern matching (conditions
- on the ascending or descending nodes of the node for which this rule was triggered) or some other properties
- of the nodes. */
- virtual bool SatisfyCondition(const Graph& graph, const Node& node, const logging::Logger& logger) const = 0;
-
- /** This is the actual body of the rule that performs the graph transformation. The transformation happens in-place.
- The return-value of node may be different from the input-value due to rewriting.
- The value of "rule_effect" indicates whether and how the graph was modified by the rule. */
- virtual common::Status Apply(Graph& graph, Node& node, RewriteRuleEffect& rule_effect, const logging::Logger& logger) const = 0;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/optimizer/rule_based_graph_transformer.h b/include/onnxruntime/core/optimizer/rule_based_graph_transformer.h
deleted file mode 100755
index 04b5072..0000000
--- a/include/onnxruntime/core/optimizer/rule_based_graph_transformer.h
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include "core/common/common.h"
-#include "core/graph/graph_viewer.h"
-#include "core/optimizer/graph_transformer.h"
-#include "core/optimizer/rewrite_rule.h"
-
-namespace onnxruntime {
-
-/**
-@class RuleBasedGraphTransformer
-
-Rule-based graph transformer that provides an API to register rewrite rules
-and an API to apply all applicable rules to a Graph.
-
-Represents an IGraphTransformer determined by a set of rewrite rules.
-The transformer will apply all the rewrite rules iteratively as determined by the underlying rewriting strategy.
-Several rewriting-strategies are possible when traversing the graph and applying rewrite rules,
-each with different trade offs. At the moment, we define one that performs top-down traversal of nodes.
-
-@TODO: Is a bottom-up traversal more efficient?
-@TODO: Is it worth adding the max number of passes a rule should be applied for?
-@TODO: We need to define a contract about whether a rewrite rule is allowed to leave
- the graph in an inconsistent state (this will determine when and where we will be
- calling Graph::resolve().
-*/
-class RuleBasedGraphTransformer : public GraphTransformer {
- public:
- RuleBasedGraphTransformer(const std::string& name,
- const std::unordered_set<std::string>& compatible_execution_providers = {})
- : GraphTransformer(name, compatible_execution_providers) {}
-
- /** Registers a rewrite rule in this transformer. */
- Status Register(std::unique_ptr<RewriteRule> rule);
-
- /** Gets the list of registered rewrite rules that will be triggered on nodes with the given op type
- by this rule-based transformer.
- @returns a pointer to the vector containing all the registered rewrite rules. */
- const std::vector<std::reference_wrapper<const RewriteRule>>* GetRewriteRulesForOpType(const std::string& op_type) const {
- auto rules = op_type_to_rules_.find(op_type);
- return (rules != op_type_to_rules_.cend()) ? &rules->second : nullptr;
- }
-
- /** Gets the rewrite rules that are evaluated on all nodes irrespective of their op type.
- @returns a pointer to the vector containing all such rewrite rules or nullptr if no such rule. */
- const std::vector<std::reference_wrapper<const RewriteRule>>* GetAnyOpRewriteRules() const {
- return &any_op_type_rules_;
- }
-
- /** Returns the total number of rules that are registered in this transformer. */
- size_t RulesCount() const;
-
- protected:
- /** Applies the given set of rewrite rules on the Node of this Graph.
- @param[in] graph The Graph.
- @param[in] node The Node to apply the rules to.
- @param[in] rules The vector of RewriteRules that will be applied to the Node.
- @param[out] rule_effect Enum that indicates whether and how the graph was modified as a result of
- applying rules on this node.
- @returns Status indicating success or providing error information. */
- common::Status ApplyRulesOnNode(Graph& graph, Node& node,
- const std::vector<std::reference_wrapper<const RewriteRule>>& rules,
- RewriteRule::RewriteRuleEffect& rule_effect, const logging::Logger& logger) const;
-
- private:
- using RuleEffect = RewriteRule::RewriteRuleEffect;
-
- // The list of unique pointers for all rules (so that rules can be registered for several op types).
- std::vector<std::unique_ptr<RewriteRule>> rules_;
- // Map that associates a node's op type with the vector of rules that are registered to be triggered for that node.
- std::unordered_map<std::string, std::vector<std::reference_wrapper<const RewriteRule>>> op_type_to_rules_;
- // Rules that will be evaluated regardless of the op type of the node.
- std::vector<std::reference_wrapper<const RewriteRule>> any_op_type_rules_;
-
- // Performs a single top-down traversal of the graph and applies all registered rules.
- common::Status ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const override;
-};
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/platform/Barrier.h b/include/onnxruntime/core/platform/Barrier.h
deleted file mode 100755
index 915cfc5..0000000
--- a/include/onnxruntime/core/platform/Barrier.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2016 Dmitry Vyukov <[email protected]>
-//
-// This Source Code Form is subject to the terms of the Mozilla
-// Public License v. 2.0. If a copy of the MPL was not distributed
-// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-#include <assert.h>
-
-#include "core/common/spin_pause.h"
-#include "core/platform/ort_mutex.h"
-
-#include <mutex>
-#include <atomic>
-
-namespace onnxruntime {
-class Barrier {
- public:
- explicit Barrier(unsigned int count, bool spin = false)
- : state_(count << 1), notified_(false), spin_(spin) {
- assert(((count << 1) >> 1) == count);
- }
-#ifdef NDEBUG
- ~Barrier() = default;
-#else
- ~Barrier() {
- assert((state_ >> 1) == 0);
- }
-#endif
-
- void Notify(unsigned int c = 1) {
- unsigned int delta = c << 1;
- unsigned int v = state_.fetch_sub(delta, std::memory_order_acq_rel) - delta;
- if (v != 1) {
- // Clear the lowest bit (waiter flag) and check that the original state
- // value was not zero. If it was zero, it means that notify was called
- // more times than the original count.
- assert(((v + delta) & ~1) != 0);
- return; // either count has not dropped to 0, or waiter is not waiting
- }
- std::unique_lock<OrtMutex> l(mu_);
- assert(!notified_);
- notified_ = true;
- cv_.notify_all();
- }
-
- void Wait() {
- if (spin_) {
- while ((state_ >> 1) != 0) {
- onnxruntime::concurrency::SpinPause();
- }
- } else {
- unsigned int v = state_.fetch_or(1, std::memory_order_acq_rel);
- if ((v >> 1) == 0)
- return;
- std::unique_lock<OrtMutex> l(mu_);
- while (!notified_) {
- cv_.wait(l);
- }
- }
- }
-
- private:
- OrtMutex mu_;
- OrtCondVar cv_;
- std::atomic<unsigned int> state_; // low bit is waiter flag
- bool notified_;
- const bool spin_;
-};
-
-// Notification is an object that allows a user to to wait for another
-// thread to signal a notification that an event has occurred.
-//
-// Multiple threads can wait on the same Notification object,
-// but only one caller must call Notify() on the object.
-struct Notification : Barrier {
- Notification() : Barrier(1){};
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/platform/EigenNonBlockingThreadPool.h b/include/onnxruntime/core/platform/EigenNonBlockingThreadPool.h
deleted file mode 100755
index f24a114..0000000
--- a/include/onnxruntime/core/platform/EigenNonBlockingThreadPool.h
+++ /dev/null
@@ -1,1391 +0,0 @@
-// This file is part of Eigen, a lightweight C++ template library
-// for linear algebra.
-//
-// Copyright (C) 2016 Dmitry Vyukov <[email protected]>
-//
-// This Source Code Form is subject to the terms of the Mozilla
-// Public License v. 2.0. If a copy of the MPL was not distributed
-// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-/* Modifications Copyright (c) Microsoft. */
-
-#include <type_traits>
-
-#pragma once
-#include "onnxruntime_config.h"
-// build/external/eigen/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h:162:71:
-// error: ignoring attributes on template argument "Eigen::PacketType<const float, Eigen::DefaultDevice>::type {aka
-// __vector(4) float}" [-Werror=ignored-attributes]
-#if defined(__GNUC__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-parameter"
-#elif defined(_MSC_VER)
-#pragma warning(push)
-#pragma warning(disable : 4127)
-#pragma warning(disable : 4805)
-#endif
-
-#include "unsupported/Eigen/CXX11/ThreadPool"
-
-#if defined(__GNUC__)
-#pragma GCC diagnostic pop
-#elif defined(_MSC_VER)
-#pragma warning(pop)
-#endif
-#include "core/common/denormal.h"
-#include "core/common/make_unique.h"
-#include "core/common/spin_pause.h"
-#include "core/platform/ort_mutex.h"
-#include "core/platform/Barrier.h"
-
-// ORT thread pool overview
-// ------------------------
-//
-// The ORT thread pool implementation is split into two layers. This
-// file provides the low-level component. See the accompanying
-// comments in threadpool.h for the high-level component.
-//
-// The code here is derived from the Eigen non-blocking thread pool,
-// although many parts have been updated over time. The main
-// abstractions used here are:
-//
-// - The thread pool maintains a set of OS threads running
-// ThreadPoolTempl::WorkerLoop.
-//
-// Each thread has its own RunQueue object, holding a queue of tasks
-// that have been pushed to the thread for execution. The main work
-// loop is to pop a task from the head of the queue, and to execute
-// it to completion. If the worker's run queue is empty then it
-// will spin waiting for work, then attempt to steal tasks from
-// other threads' queues, and then block in the OS if it cannot find
-// work.
-//
-// This spin-then-block behavior is configured via a flag provided
-// when creating the thread pool, and by the constant spin_count.
-//
-// - Although all tasks are simple void()->void functions,
-// conceptually there are three different kinds:
-//
-// - One-shot tasks submitted externally via the Schedule() method.
-// These tasks are used to support asynchronous work. These are
-// used in the parallel executor, but otherwise are not widely
-// used outside of test harnesses (see threadpool_test.cc for some
-// examples).
-//
-// - Tasks for running a parallel loop.
-//
-// The tasks themselves are defined in threadpool.cc, and are
-// submitted to the run queues via RunInParallel->SummonWorkers.
-// Each task will loop internally, picking off iterations from the
-// user's code via atoic-fetch-and-add, until the loop is
-// complete.
-//
-// This two-layer approach lets us separate out the
-// super-lightweight per-iteration-batch work from the more
-// costsly per-loop work of managing Task objects.
-//
-// - Tasks for running a parallel section. This is an extension of
-// the approach taken for parallel loops. However, the Tasks are
-// defined in this file, and can pick up iterations from a series
-// of different parallel loops. The tasks are defined in
-// RunInParallelSection->SummonWorkers.
-//
-// The additional layer of parallel sections is a further way to
-// amortize costs: the work done creating the tasks can be
-// performed once, and then exploited over a series of loops.
-//
-// There are a few aspects of the modified Eigen thread pool to
-// highlight:
-//
-// - The run queues follow the usual approach of having push/pop
-// operations on the front/back, and optimizing the PopFront case
-// for single-threaded use by the thread owning the run queue.
-//
-// However, we support an additional Revoke operation to replace an
-// item in the middle of a queue with a tombstone. This operation
-// is used at the end of parallel loops and parallel sections to
-// remove any tasks that were created but not yet executed. Once
-// revoked, a thread can rely on the fact that the task will no
-// longer execute. Revocation helps manage captured state in
-// parallel loops: the alternatives would be (i) waiting for all
-// tasks that captured state to reach the head of their queues and
-// execute, or (ii) use heap-allocated state in tasks, and use a
-// technique such as reference counting to de-allocate it.
-//
-// To support revoation, each thread has a unique "Tag" to identify
-// the items that it adds to the work queues. A thread can revoke
-// an item only if it has the thread's own tag.
-//
-// - The worker threads maintain a best-effort bitmap in
-// good_worker_hints_ of which threads to push work to. A thread
-// controls its status via SetGoodWorkerHint. A thread is a "good"
-// worker when it is actively spinning for work, meaning both that
-// it is not blocked in the OS, and that it is not busy with work
-// already.
-//
-// This heuristic aims to avoid waking additional sleeping threads
-// where possible, and in a series of parallel loops or parallel
-// sections to push the work to the same set of threads each time.
-
-namespace onnxruntime {
-namespace concurrency {
-
-class ThreadPoolParallelSection;
-class ThreadPoolLoop;
-
-// Align to avoid false sharing with prior fields. If required,
-// alignment or padding must be added subsequently to avoid false
-// sharing with later fields. Note that:
-//
-// - The __x86_64__ value is twice the line size (64 bytes). This
-// accounts for 2-line prefetch behavior on some cores.
-//
-// - Ideally, ORT_ALIGN_TO_AVOID_FALSE_SHARING is used. However, the
-// definition of ThreadPoolParallelSection uses naive padding
-// because C++11 does not support alignment constraints on
-// allocation or expose stdlib.h aligned_alloc. C++17 introduces
-// support for aligned allocation which we could use here.
-
-#if defined(__x86_64__)
-#define ORT_FALSE_SHARING_BYTES 128
-#else
-#define ORT_FALSE_SHARING_BYTES 64
-#endif
-
-#define ORT_ALIGN_TO_AVOID_FALSE_SHARING alignas(ORT_FALSE_SHARING_BYTES)
-
-struct PaddingToAvoidFalseSharing {
- char padding[ORT_FALSE_SHARING_BYTES];
-};
-
-// Extended Eigen thread pool interface, avoiding the need to modify
-// the ThreadPoolInterface.h header from the external Eigen
-// repository.
-
-class ExtendedThreadPoolInterface : public Eigen::ThreadPoolInterface {
- public:
- // Start/end a parallel section, within which calls to
- // RunInParallelSection may be made. Parallel sections are
- // non-nesting.
- virtual std::unique_ptr<ThreadPoolParallelSection, void(*)(ThreadPoolParallelSection*)> AllocateParallelSection() = 0;
- virtual void StartParallelSection(ThreadPoolParallelSection &ps) = 0;
- virtual void EndParallelSection(ThreadPoolParallelSection &ps) = 0;
-
- // Run fn with up to n degree-of-parallelism enlisting the thread
- // pool for help. The degree-of-parallelism includes the caller,
- // and so if n==1 then the function will run directly in the caller.
- //
- // The fork-join synchronization is handled in the thread pool, and
- // so any state captured by fn() is safe from concurrent access once
- // RunInParallelSection returns.
- //
- // The parameter idx provides a loop-local thread ID in the range
- // [0,k) where k<=n.
- virtual void RunInParallelSection(ThreadPoolParallelSection &ps,
- std::function<void(unsigned idx)> fn,
- unsigned n) = 0;
-
- // Special case alternative to RunInParallelSection for use without
- // an existing parallel section. Ideally we would use a single
- // iplemenation and a stack-allocated ThreadPoolParallelSection.
- //
- // However, on the BM_ThreadPoolParallelFor microbenchmark I saw
- // ~20% overhead on the resulting single-loop parallel sections.
- // There are some additional costs (~5%) for additional invocations
- // through lambda functions on loop entry. Most significantly, on
- // loop exit, we incurred ~15% cost by no longer being able to
- // overlap clean-up of unused Task objects in EndParallelSection
- // with waiting for loop iterations to complete.
- //
- // [ Note that this 20% overhead is more than paid for when we have
- // two loops execute in series in a parallel section. ]
- virtual void RunInParallel(std::function<void(unsigned idx)> fn,
- unsigned n) = 0;
-};
-
-
-class ThreadPoolParallelSection {
- public:
- // State accessed only by the main thread
- // --------------------------------------
-
- // Tasks successfully submitted to the work queues. This sets the
- // maximum degree of parallelism that the section will support.
- std::vector<std::pair<int,unsigned>> tasks;
-
- // State shared between the main thread and worker threads
- // -------------------------------------------------------
-
- // Flag to signal termination of the parallel section
- std::atomic<bool> active{false};
-
- std::atomic<unsigned> worker_idx{0};
-
- // Count of the number of tasks that completed normally. Other
- // tasks may be running currently, or may be present in work queues,
- // or may have been removed from the queues by
- // RunQueue::RevokeWithTag.
- PaddingToAvoidFalseSharing padding_1;
- std::atomic<unsigned> tasks_finished{0};
- PaddingToAvoidFalseSharing padding_2;
-
- // If non-null, the current loop that tasks should be executing. We
- // need to be careful on access to the contents of current_loop
- // because it can be stack allocated on the thread entering the
- // loop:
- //
- // - Readers increment workers_in_loop and then read current_loop
- //
- // - Writers wishing to deallocate *current_loop must first clear
- // current_loop and then wait for workers_in_loop==0
- std::atomic<ThreadPoolLoop *> current_loop{nullptr};
- std::atomic<unsigned> workers_in_loop{0};
-};
-
-class ThreadPoolLoop {
- public:
- ThreadPoolLoop(std::function<void(unsigned)> f, unsigned t) : fn(std::move(f)), threads_needed(t) {
- }
-
- const std::function<void(unsigned)> fn;
- const unsigned threads_needed;
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ThreadPoolLoop);
-};
-
-template <typename Work, typename Tag, unsigned kSize>
-class RunQueue {
- public:
- RunQueue() : front_(0), back_(0) {
- // require power-of-two for fast masking
- assert((kSize & (kSize - 1)) == 0);
- assert(kSize > 2); // why would you do this?
- assert(kSize <= (64 << 10)); // leave enough space for counter
- for (unsigned i = 0; i < kSize; i++) array_[i].state.store(ElemState::kEmpty, std::memory_order_relaxed);
- }
-
- ~RunQueue() {
- assert(Size() == 0);
- }
-
- // PushFront inserts w at the beginning of the queue.
- // If queue is full returns w, otherwise returns default-constructed Work.
- Work PushFront(Work w) {
- unsigned front = front_.load(std::memory_order_relaxed);
- Elem& e = array_[front & kMask];
- ElemState s = e.state.load(std::memory_order_relaxed);
- if (s != ElemState::kEmpty ||
- !e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
- return w;
- front_.store(front + 1 + (kSize << 1), std::memory_order_relaxed);
- e.w = std::move(w);
- e.tag = Tag();
- e.state.store(ElemState::kReady, std::memory_order_release);
- return Work();
- }
-
- // PopFront removes and returns the first element in the queue.
- // If the queue was empty returns default-constructed Work.
- Work PopFront() {
- unsigned front;
- Elem *e;
- ElemState s;
-
- // Drain revoked items from the front of the queue. CAS to busy to synchronize with
- // any attempt to take the same item from the back of the queue.
- do {
- front = front_.load(std::memory_order_relaxed);
- e = &array_[(front - 1) & kMask];
- s = e->state.load(std::memory_order_relaxed);
- if (s == ElemState::kRevoked &&
- e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
- e->state.store(ElemState::kEmpty, std::memory_order_release);
- front = ((front - 1) & kMask2) | (front & ~kMask2);
- front_.store(front, std::memory_order_relaxed);
- }
- } while (s == ElemState::kRevoked);
-
- // Attempt to take next item. State kEmpty shows the queue is empty, kBusy shows
- // the work is in progress on the item at the front of the queue.
- if (s != ElemState::kReady ||
- !e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
- return Work();
- Work w = std::move(e->w);
- e->tag = Tag();
- e->state.store(ElemState::kEmpty, std::memory_order_release);
- front = ((front - 1) & kMask2) | (front & ~kMask2);
- front_.store(front, std::memory_order_relaxed);
- return w;
- }
-
- // PushBack adds w at the end of the queue.
- // If queue is full returns w, otherwise returns default-constructed Work.
- Work PushBack(Work w) {
- std::unique_lock<OrtMutex> lock(mutex_);
- unsigned back = back_.load(std::memory_order_relaxed);
- Elem& e = array_[(back - 1) & kMask];
- ElemState s = e.state.load(std::memory_order_relaxed);
- if (s != ElemState::kEmpty ||
- !e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
- return w;
- back = ((back - 1) & kMask2) | (back & ~kMask2);
- back_.store(back, std::memory_order_relaxed);
- e.w = std::move(w);
- e.tag = Tag();
- e.state.store(ElemState::kReady, std::memory_order_release);
- return Work();
- }
-
- // PushBackWithTag adds w at the end of the queue. The tag value can be used on a
- // subsequent call to RevokeWithTag to remove the item from the queue in combination
- // with w_idx. Typically the tag will be a per-thread ID to distinguish work
- // submitted from different threads.
- //
- // If the queue is full, returns w, otherwise returns default-constructed work.
- Work PushBackWithTag(Work w, Tag tag, unsigned &w_idx) {
- std::unique_lock<OrtMutex> lock(mutex_);
- unsigned back = back_.load(std::memory_order_relaxed);
- w_idx = (back-1) & kMask;
- Elem& e = array_[w_idx];
- ElemState s = e.state.load(std::memory_order_relaxed);
- if (s != ElemState::kEmpty ||
- !e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
- return w;
- back = ((back - 1) & kMask2) | (back & ~kMask2);
- back_.store(back, std::memory_order_relaxed);
- e.w = std::move(w);
- e.tag = tag;
- e.state.store(ElemState::kReady, std::memory_order_release);
- return Work();
- }
-
- // PopBack removes and returns the last elements in the queue.
- Work PopBack() {
- if (Empty())
- return Work();
- std::unique_lock<OrtMutex> lock(mutex_);
- unsigned back;
- Elem *e;
- ElemState s;
-
- // Drain revoked items from the back of the queue. CAS to busy to synchronize with
- // any attempt to take the same item from the front of the queue.
- do {
- back = back_.load(std::memory_order_relaxed);
- e = &array_[back & kMask];
- s = e->state.load(std::memory_order_relaxed);
- if (s == ElemState::kRevoked &&
- e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
- e->state.store(ElemState::kEmpty, std::memory_order_release);
- back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
- }
- } while (s == ElemState::kRevoked);
-
- if (s != ElemState::kReady ||
- !e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
- return Work();
- Work w = std::move(e->w);
- e->tag = Tag();
- e->state.store(ElemState::kEmpty, std::memory_order_release);
- back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
- return w;
- }
-
- // RevokeItem removes a work item from the queue. Items are identified positionally,
- // and so a tag is used to detect whether the same position is occupied by a
- // different work item at the time of removal. RevokeWithTags lets threads offer work
- // for parallel execution, and then revoke the offer prior to the work executing (for
- // instance if the thread itself completes all of the work). Revoking the work
- // lets the thread deallocate state that might otherwise have been captured by the work item
- // and accessed by it.
- //
- // Return true iff the item is successfully revoked. If the item is not revoked then
- // the caller must assume that it may still execute, for instance because it
- // has been pop'd from the queue concurrent with the revocation request.
-
- bool RevokeWithTag(Tag tag, unsigned w_idx) {
- bool revoked = false;
- std::unique_lock<OrtMutex> lock(mutex_);
- Elem& e = array_[w_idx];
- ElemState s = e.state.load(std::memory_order_relaxed);
-
- // We have acquired a lock on the queue, synchronizing with
- // operations aside from the PopFront fast-path. Synchronize with
- // that by attempting the same kReady->kBusy transition via CAS.
-
- if (s == ElemState::kReady &&
- e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
- if (e.tag == tag) {
- unsigned back = back_.load(std::memory_order_relaxed);
- unsigned back_idx = back & kMask;
- if (back_idx != w_idx) {
- // Item is not at the back of the queue, mark it in-place as revoked
- e.tag = Tag();
- e.w = Work();
- e.state.store(ElemState::kRevoked, std::memory_order_release);
- revoked = true;
- } else {
- // Item being removed as still at the back; shift the back pointer over it,
- // and bump the version number.
- e.tag = Tag();
- e.w = Work();
- e.state.store(ElemState::kEmpty, std::memory_order_release);
- back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
- revoked = true;
- }
- } else {
- // Tag mismatch, i.e. work queue slot re-used
- e.state.store(ElemState::kReady, std::memory_order_release);
- }
- }
- return revoked;
- }
-
- // Size returns current queue size.
- // Can be called by any thread at any time.
- unsigned Size() const {
- return SizeOrNotEmpty<true>();
- }
-
- // Empty tests whether container is empty.
- // Can be called by any thread at any time.
- bool Empty() const {
- return SizeOrNotEmpty<false>() == 0;
- }
-
- // Delete all the elements from the queue.
- void Flush() {
- while (!Empty()) {
- PopFront();
- }
- }
-
- private:
- static const unsigned kMask = kSize - 1;
- static const unsigned kMask2 = (kSize << 1) - 1;
-
- enum class ElemState : uint8_t {
- kEmpty,
- kBusy,
- kReady,
- kRevoked,
- };
-
- // Updates to an element are bracketed by a std::memory_order_acquire
- // load from the state, and a std::memory_order_release store. Accesses
- // to the front/back indices for the work queue use relaxed semantics,
- // with the state of the elements being authoritative.
- //
- // TODO: Revisit whether there is a significant benefit for the current
- // workloads in the complexity here.
- struct Elem {
- std::atomic<ElemState> state;
- Tag tag;
- Work w;
- };
-
- OrtMutex mutex_;
-
- // Low log(kSize) + 1 bits in front_ and back_ contain rolling index of
- // front/back, respectively. The remaining bits contain modification counters
- // that are incremented on Push operations. This allows us to (1) distinguish
- // between empty and full conditions (if we would use log(kSize) bits for
- // position, these conditions would be indistinguishable); (2) obtain
- // consistent snapshot of front_/back_ for Size operation using the
- // modification counters.
- ORT_ALIGN_TO_AVOID_FALSE_SHARING std::atomic<unsigned> front_;
- ORT_ALIGN_TO_AVOID_FALSE_SHARING std::atomic<unsigned> back_;
- ORT_ALIGN_TO_AVOID_FALSE_SHARING Elem array_[kSize];
-
- // SizeOrNotEmpty returns current queue size; if NeedSizeEstimate is false,
- // only whether the size is 0 is guaranteed to be correct.
- // Can be called by any thread at any time.
- template <bool NeedSizeEstimate>
- unsigned SizeOrNotEmpty() const {
- // Emptiness plays critical role in thread pool blocking. So we go to great
- // effort to not produce false positives (claim non-empty queue as empty).
- unsigned front = front_.load(std::memory_order_acquire);
- for (;;) {
- // Capture a consistent snapshot of front/tail.
- unsigned back = back_.load(std::memory_order_acquire);
- unsigned front1 = front_.load(std::memory_order_relaxed);
- if (front != front1) {
- front = front1;
- std::atomic_thread_fence(std::memory_order_acquire);
- continue;
- }
- if (NeedSizeEstimate) {
- return CalculateSize(front, back);
- }
- // This value will be 0 if the queue is empty, and undefined otherwise.
- unsigned maybe_zero = ((front ^ back) & kMask2);
- // Queue size estimate must agree with maybe zero check on the queue
- // empty/non-empty state.
- eigen_assert((CalculateSize(front, back) == 0) == (maybe_zero == 0));
- return maybe_zero;
- }
- }
-
- EIGEN_ALWAYS_INLINE
- unsigned CalculateSize(unsigned front, unsigned back) const {
- int size = (front & kMask2) - (back & kMask2);
- // Fix overflow.
- if (size < 0)
- size += 2 * kSize;
- // Order of modification in push/pop is crafted to make the queue look
- // larger than it is during concurrent modifications. E.g. push can
- // increment size before the corresponding pop has decremented it.
- // So the computed size can be up to kSize + 1, fix it.
- if (size > static_cast<int>(kSize))
- size = kSize;
- return static_cast<unsigned>(size);
- }
-
- RunQueue(const RunQueue&) = delete;
- void operator=(const RunQueue&) = delete;
-};
-
-static std::atomic<uint32_t> next_tag{1};
-
-template <typename Environment>
-class ThreadPoolTempl : public onnxruntime::concurrency::ExtendedThreadPoolInterface {
-
- private:
- struct PerThread;
-
- static unsigned WorkerLoop(int id, Eigen::ThreadPoolInterface* param) {
- // unsafe downcast
- ThreadPoolTempl* this_ptr = (ThreadPoolTempl*)param;
- this_ptr->WorkerLoop(id);
- return 0;
- }
-
- public:
- struct Tag {
- constexpr Tag() : v_(0) {
- }
-
- Tag(uint32_t v) : v_(v) {
- }
-
- // Allocate a new tag to use to identify work items from a given
- // thread in a parallel section. Ideally, threads will have
- // unique tags, but re-use is not incorrect if the counter wraps
- // (for intsance, if a long-running workload is calling into ORT
- // from a fresh thread for each request). We must not re-use the
- // default tag 0 which is used to identify work items added via
- // Schedule as opposed to requests for help in parallel sections.
-
- static Tag GetNext() {
- Tag t = Tag(next_tag++);
- if (t.v_ == 0) {
- t = Tag(next_tag++);
- }
- return t;
- }
-
- uint32_t Get() const {
- return v_;
- }
-
- bool operator==(Tag& other) const {
- return v_ == other.v_;
- }
-
- uint32_t v_ = 0;
- };
-
- typedef std::function<void()> Task;
- typedef RunQueue<Task, Tag, 1024> Queue;
-#ifdef _WIN32
- using CHAR_TYPE = wchar_t;
-#else
- using CHAR_TYPE = char;
-#endif
- ThreadPoolTempl(const CHAR_TYPE* name, int num_threads, bool allow_spinning, Environment& env,
- const ThreadOptions& thread_options)
- : env_(env),
- num_threads_(num_threads),
- allow_spinning_(allow_spinning),
- set_denormal_as_zero_(thread_options.set_denormal_as_zero),
- worker_data_(num_threads),
- all_coprimes_(num_threads),
- blocked_(0),
- done_(false),
- cancelled_(false) {
-
- // Calculate coprimes of all numbers [1, num_threads].
- // Coprimes are used for random walks over all threads in Steal
- // and NonEmptyQueueIndex. Iteration is based on the fact that if we take
- // a random starting thread index t and calculate num_threads - 1 subsequent
- // indices as (t + coprime) % num_threads, we will cover all threads without
- // repetitions (effectively getting a presudo-random permutation of thread
- // indices).
- for (int i = 1; i <= num_threads_; ++i) {
- all_coprimes_.emplace_back(i);
- ComputeCoprimes(i, &all_coprimes_.back());
- }
-
- // Allocate space for per-thread bits to indicate which threads to consider
- // preferable for pushing work. We use a regular array given that a std::vector
- // cannot contain std::atomic.
- num_hint_words_ = static_cast<int>((num_threads_ + bits_per_hint_word_ - 1) / bits_per_hint_word_);
- good_worker_hints_ = onnxruntime::make_unique<std::atomic<uint64_t>[]>(num_hint_words_);
-
- worker_data_.resize(num_threads_);
- for (int i = 0; i < num_threads_; i++) {
- worker_data_[i].thread.reset(env_.CreateThread(name, i, WorkerLoop, this, thread_options));
- }
- }
-
- ~ThreadPoolTempl() override {
- done_ = true;
-
- // Now if all threads block without work, they will start exiting.
- // But note that threads can continue to work arbitrary long,
- // block, submit new work, unblock and otherwise live full life.
- if (!cancelled_) {
- WakeAllWorkersForExit();
- } else {
- // Since we were cancelled, there might be entries in the queues.
- // Empty them to prevent their destructor from asserting.
- for (size_t i = 0; i < worker_data_.size(); i++) {
- worker_data_[i].queue.Flush();
- }
- }
- // Join threads explicitly (by destroying) to avoid destruction order within
- // this class.
- for (size_t i = 0; i < worker_data_.size(); ++i) worker_data_[i].thread.reset();
- }
-
- // Run fn(). Ordinarily, the function will be added to the thread pool and executed
- // by a worker thread. If the thread pool rejects the work then fn() will instead
- // execute synchronously during Schedule(fn). Currently the thread pool will only
- // reject work if the queue of pending work is full.
-
- void Schedule(std::function<void()> fn) override {
- PerThread* pt = GetPerThread();
- if (pt->pool == this) {
- // Worker thread of this pool, push onto the thread's queue.
- Queue& q = worker_data_[pt->thread_id].queue;
- fn = q.PushFront(std::move(fn));
- } else {
- // A free-standing thread (or worker of another pool), push onto a random
- // queue.
- int q_idx = Rand(&pt->rand) % num_threads_;
- WorkerData &td = worker_data_[q_idx];
- Queue& q = td.queue;
- fn = q.PushBack(std::move(fn));
- if (!fn) {
- // The queue accepted the work; ensure that the thread will pick it up
- td.EnsureAwake();
- }
- }
-
- // Run the work directly if the queue rejected the work
- if (fn) fn();
- }
-
-// The thread pool maintains a set of hints for which threads will be good to distribute
-// work to. A thread is considered "good" if it is actively spinning, meaning both that
-// it is not busy with existing work, and that it should respond quickly to the addition
-// of new work.
-
-void SetGoodWorkerHint(int idx, bool is_good) {
- assert(idx >= 0 && idx < num_threads_);
- std::atomic<uint64_t>& u64 = good_worker_hints_[idx / bits_per_hint_word_];
- uint64_t bit = 1ull << (idx % bits_per_hint_word_);
- uint64_t saw, want;
- do {
- saw = u64.load();
- want = is_good ? (saw|bit) : (saw&~bit);
- } while (!u64.compare_exchange_weak(saw, want));
-}
-
-// Retrieve hints for up to n threads to distribute work to. Threads in good_hints
-// pass a best-effort check to identify spinning threads via the good_worker_hints_
-// bitmap. Threads in alt_hint do not pass that test, but are distinct from those in
-// good_hints, letting the caller avoid distributing more than one work item to
-// any individual thread.
-
-void GetGoodWorkerHints(unsigned n, std::vector<unsigned>& good_hints, std::vector<unsigned>& alt_hints) {
- PerThread* pt = GetPerThread();
- unsigned need_alt = n;
- good_hints.clear();
- alt_hints.clear();
-
- // Iterate through the words of hints, starting from a pseudo-randomly chosen
- // base. This aims to distribute work across large machines in cases we
- // have multiple threads scheduling work concurrently.
-
- unsigned base = Rand(&pt->rand) % num_hint_words_;
- for (unsigned i = 0u; n && (i < num_hint_words_); i++) {
- int u64_idx = (base + i) % num_hint_words_;
- std::atomic<uint64_t>* u64 = &good_worker_hints_[u64_idx];
- uint64_t saw = u64->load();
- uint64_t want = saw;
-
- // Pick up to n bits that are set in the current word
- for (unsigned j = 0u; n && (j < bits_per_hint_word_); j++) {
- uint64_t bit = 1ull << j;
- int thread = u64_idx * bits_per_hint_word_ + j;
- if (saw & bit) {
- good_hints.push_back(thread);
- want &= ~bit;
- n--;
- } else if (need_alt && thread < num_threads_) {
- alt_hints.push_back(thread);
- need_alt--;
- }
- }
-
- // Best-effort attempt to remove the hints. We should measure the impact of
- // contention here, but the intuition is that if we conflict on the CAS then the
- // machine is likely to be busy in any case, and we will have queuing on the
- // work items.
- u64->compare_exchange_strong(saw, want);
- }
-}
-
-//......................................................................
-//
-// Parallel sections
-// -----------------
-//
-// Allocate a new ThreadPoolParallelSection, owned by the returned
-// unique_ptr. The explicit deleter avoids the Eigen-specific
-// definition of ThreadPoolParallelSection needing to be avilable in
-// threadpool.h where the user-facing parallel section API is defined.
-
-std::unique_ptr<ThreadPoolParallelSection, void(*)(ThreadPoolParallelSection*)> AllocateParallelSection() override {
- return std::unique_ptr<ThreadPoolParallelSection, void(*)(ThreadPoolParallelSection*)>
- (new ThreadPoolParallelSection,
- [](ThreadPoolParallelSection *tps) {
- delete tps;
- });
-}
-
-// Start a parallel section, using a caller-provided
-// ThreadPoolParallelSection for maintaining the per-section state.
-// Starting a parallel section is just book-keeping; threads are
-// "summoned" to help with the parallel section once it enters
-// parallel loops. The threads are then retained until the end of the
-// section, being re-used over subsequent loops.
-
-void StartParallelSectionInternal(PerThread &pt,
- ThreadPoolParallelSection &ps) {
- assert((!pt.leading_par_section) && "Nested parallelism not supported");
- assert((!ps.active) && "Starting parallel section, but active already");
- pt.leading_par_section = true;
- if (!pt.tag.Get()) {
- pt.tag = Tag::GetNext();
- }
- ps.active = true;
-}
-
-void StartParallelSection(ThreadPoolParallelSection &ps) override {
- PerThread* pt = GetPerThread();
- StartParallelSectionInternal(*pt, ps);
-}
-
-// End a parallel section, waiting for all worker threads to exit from
-// section. Hence, on return, the ThreadPoolParallelSection object
-// can be dealloacted.
-
-void EndParallelSectionInternal(PerThread &pt,
- ThreadPoolParallelSection &ps) {
- assert((pt.leading_par_section) && "Ending parallel section, but none started");
- assert((ps.active) && "Ending parallel section, but not active");
- pt.leading_par_section = false;
-
- // Notify workers to exit from the section
- ps.active = false;
-
- // Attempt to revoke any tasks that were sent to workers but not
- // started.
- unsigned tasks_started = static_cast<unsigned>(ps.tasks.size());
- unsigned tasks_revoked = 0;
- while (!ps.tasks.empty()) {
- const auto& item = ps.tasks.back();
- Queue& q = worker_data_[item.first].queue;
- if (q.RevokeWithTag(pt.tag, item.second)) {
- tasks_revoked++;
- }
- ps.tasks.pop_back();
- }
-
- // Wait for workers to exit ParLoopWorker
- auto tasks_to_wait_for = tasks_started - tasks_revoked;
- while (ps.tasks_finished < tasks_to_wait_for) {
- onnxruntime::concurrency::SpinPause();
- }
-
- // Clear status to allow the ThreadPoolParallelSection to be
- // re-used.
- ps.tasks_finished = 0;
-}
-
-void EndParallelSection(ThreadPoolParallelSection &ps) override {
- PerThread* pt = GetPerThread();
- EndParallelSectionInternal(*pt, ps);
-}
-
-//......................................................................
-//
-// Parallel loops
-// --------------
-//
-// Ensure that the ThreadPoolParallelSection has sufficient workers to
-// execute a loop with degree of parallelism n. We track the number
-// of workers already avaiable to the parallel section, prior to
-// submitting tasks to the work queues to make up the total.
-//
-// Each worker will call in to worker_fn(idx) with a per-worker thread
-// ID. Note there are different levels of indirection here:
-//
-// - In a single-loop parallel section, worker_fn will directly
-// execute the threadpool.cc code that implements the parallel loop.
-//
-// - In a multi-loop parallel section, worker_fn is an intermediate
-// function that is long-lived (i.e., that lasts until the end of
-// the parallel section, as opposed to just a single loop's
-// duration).
-
-void SummonWorkers(PerThread &pt,
- ThreadPoolParallelSection &ps,
- unsigned n,
- const std::function<void(unsigned)> &worker_fn) {
- // Wrap the user's worker function with one that allocates a unique
- // worker index for the loop, and synchronizes (as the last step)
- // with the exit path in EndParallelSection. In principle we could
- // allocate worker IDs during the loop below and capture them by
- // value. However, the costs of creating distinct lambda for each
- // iteration appeared more costly than the cost of synchronization
- // on a shared counter.
- auto call_worker_fn = [&ps, worker_fn]() {
- unsigned my_idx = ++ps.worker_idx;
- worker_fn(my_idx);
- // After the assignment to ps.tasks_finished, the stack-allocated
- // ThreadPoolParallelSection object may be destroyed.
- ps.tasks_finished++;
- };
-
- // Identify whether we need to create additional workers.
- // Throughout the threadpool implementation, degrees of parallelism
- // ("n" here) refer to the total parallelism including the main
- // thread. Hence we consider the number of existing tasks + 1.
- unsigned current_dop = static_cast<unsigned>(ps.tasks.size()) + 1;
- if (n > current_dop) {
- unsigned extra_needed = n - current_dop;
-
- // Obtain hints for which worker threads to push the tasks to.
- // This uses a best-effort assessment of which threads are
- // spinning.
- std::vector<unsigned> good_hints, alt_hints;
- GetGoodWorkerHints(extra_needed, good_hints, alt_hints);
-
- // Create the additional tasks, and push them to workers.
- for (auto i = 0u; i < extra_needed; i++) {
- Task t;
- int q_idx;
- if (i < good_hints.size()) {
- q_idx = good_hints[i];
- } else {
- auto alt_i = i - static_cast<unsigned>(good_hints.size());
- if (alt_i < alt_hints.size()) {
- q_idx = alt_hints[alt_i];
- } else {
- q_idx = Rand(&pt.rand) % num_threads_;
- }
- }
-
- // If the worker's queue accepts the task, then record it in
- // the vector of tasks that we will need to synchronize with on
- // exiting the parallel section. If the queue rejects the task
- // (perhaps because it is full) then we take no further action:
- // in a parallel loop we will always be running work on the
- // main thread, providing progress.
- WorkerData& td = worker_data_[q_idx];
- Queue& q = td.queue;
- unsigned w_idx;
- t = q.PushBackWithTag(call_worker_fn, pt.tag, w_idx);
- if (!t) {
- ps.tasks.push_back({q_idx, w_idx});
- td.EnsureAwake();
- }
- }
- }
-}
-
-// Run a single parallel loop in an existing parallel section. This
-// maps directly onto SummonWorkers to create sufficient worker
-// threads for the desired degree of parallelism, followed by
-// dispatching the loop to those workers.
-
-void RunInParallelSection(ThreadPoolParallelSection &ps,
- std::function<void(unsigned idx)> fn,
- unsigned n) override {
- PerThread* pt = GetPerThread();
- assert(pt->leading_par_section && "RunInParallel, but not in parallel section");
- assert((n > 1) && "Trivial parallel section; should be avoided by caller");
-
- // Publish the work to any existing workers in the parallel
- // section, and ensure it is visible to any new threads created
- // below.
- assert((!ps.current_loop) && "RunInParallelSection, but loop already active");
- ThreadPoolLoop loop{std::move(fn), n};
- ps.current_loop = &loop;
-
- // Increase the worker count if needed. Each worker will pick up
- // loops to execute from the current parallel section.
- const auto worker_fn = [&ps](unsigned my_idx) {
- while (ps.active) {
- if (!ps.current_loop) {
- onnxruntime::concurrency::SpinPause();
- } else {
- ps.workers_in_loop++;
- ThreadPoolLoop *work_item = ps.current_loop;
- if (work_item && my_idx < work_item->threads_needed) {
- work_item->fn(my_idx);
- }
- ps.workers_in_loop--;
- }
- }
- };
- SummonWorkers(*pt, ps, n, worker_fn);
-
- // Run work in the main thread
- loop.fn(0);
-
- // Wait for workers to exit the loop
- ps.current_loop = 0;
- while (ps.workers_in_loop) {
- onnxruntime::concurrency::SpinPause();
- }
-}
-
-// Run a single parallel loop _without_ a parallel section. This is a
-// special case of RunInParallelSection, avoiding code paths for
-// handing off multiple loops to the pool of workers.
-
-void RunInParallel(std::function<void(unsigned idx)> fn, unsigned n) override {
- PerThread *pt = GetPerThread();
- ThreadPoolParallelSection ps;
- StartParallelSectionInternal(*pt, ps);
-
- // Summon workers to run the function (n is the desired maximum
- // degree of parallelism, including the main thread). Unlike the
- // multi-loop RunInParallelSection, this single-loop worker can run
- // fn directly without needing to receive it via ps.current_loop.
- SummonWorkers(*pt, ps, n, fn);
-
- // Run work in the main thread
- fn(0);
-
- // Wait for workers to exit the parallel section and hence to have
- // completed the loop (i.e., ps.tasks_finished matches the number of
- // tasks that have been created less the number successfully
- // revoked).
- EndParallelSectionInternal(*pt, ps);
-}
-
-void Cancel() override {
- cancelled_ = true;
- // If done_ is true, which means this object is being destructing.
- // Therefore worker_data_[i].thread could be NULL.
- if (!done_) {
- done_ = true;
- // Let each thread know it's been cancelled.
- for (size_t i = 0; i < worker_data_.size(); i++) {
- assert(worker_data_[i].thread != nullptr);
- worker_data_[i].thread->OnCancel();
- }
- }
-
- // Wake up the threads without work to let them exit on their own.
- WakeAllWorkersForExit();
-}
-
-int NumThreads() const EIGEN_FINAL {
- return num_threads_;
-}
-
-int CurrentThreadId() const EIGEN_FINAL {
- const PerThread* pt = const_cast<ThreadPoolTempl*>(this)->GetPerThread();
- if (pt->pool == this) {
- return pt->thread_id;
- }
- return -1;
-}
-
- private:
-
-#ifdef NDEBUG
- void AssertBounds(int, int) {
- }
-#else
- void AssertBounds(int start, int end) {
- assert(start >= 0);
- assert(start < end); // non-zero sized partition
- assert(end <= num_threads_);
- }
-#endif
-
- void ComputeCoprimes(int N, Eigen::MaxSizeVector<unsigned>* coprimes) {
- for (int i = 1; i <= N; i++) {
- unsigned a = i;
- unsigned b = N;
- // If GCD(a, b) == 1, then a and b are coprimes.
- while (b != 0) {
- unsigned tmp = a;
- a = b;
- b = tmp % b;
- }
- if (a == 1) {
- coprimes->push_back(i);
- }
- }
- }
-
- typedef typename Environment::EnvThread Thread;
- struct WorkerData;
-
- // PerThread objects are allocated in thread-local storage and allocated
- // on the thread's first call to GetPerThread. The object should
- // remain trivially-destructable, with other state placed in the
- // WorkerData objects that are allocated and cleaned-up explicitly.
- //
- // PerThread objects are allocated for all threads that submit work to
- // the thread pool, in addition to threads within the pool.
- //
- // In contrast, the WorkerData objects are allocated only for the
- // threads in the pool, and their lifetime is managed along with the
- // pool.
-
- struct PerThread {
- constexpr PerThread() : pool(nullptr) {
- }
- ThreadPoolTempl* pool; // Parent pool, or null for normal threads.
- uint64_t rand{0}; // Random generator state.
- int thread_id{-1}; // Worker thread index in pool.
- Tag tag{}; // Work item tag used to identify this thread.
- bool leading_par_section{false}; // Leading a parallel section (used only for asserts)
- };
-
- static_assert(std::is_trivially_destructible<PerThread>::value,
- "Per-thread state should be trivially destructible");
-
- struct WorkerData {
- constexpr WorkerData() : thread(), queue() {
- }
- std::unique_ptr<Thread> thread;
- Queue queue;
-
- // Each thread has a status, available read-only without locking, and protected
- // by the mutex field below for updates. The status is used for three
- // purposes:
- //
- // 1. To identify threads that are good candidates to push work to.
- // We prefer to push work to threads that are actively spinning (no need
- // for an OS wake-up, and no need for current work to finish). After that, we
- // prefer to push work to threads that are blocked (no need to wait for the
- // current work to finish).
- //
- // 2. To identify threads that are good candidates to steal work from. We
- // prefer to steal work from threads that are active outside the worker loop.
- // This avoids "snatching" new work away from a thread that has just been
- // given it but not yet noticed.
- //
- // 3. When pushing work to a thread, we use the status read-only to identify
- // when we need to wake the thread. This read-only check avoids the
- // need for mutex / condvar operations in the case where the thread pool
- // remains busy.
-
- enum class ThreadStatus : uint8_t {
- Spinning, // Spinning in the work loop, and other cases (initialization) where
- // the thread will soon be in the loop
- Active, // Running user code, not waiting for work
- Blocking, // In the process of blocking; may no longer notice work pushed to it
- Blocked, // Blocked on cv
- Waking, // Not yet back in the worker loop, but wake-up notification sent
- };
-
- ThreadStatus GetStatus() const {
- return status;
- }
-
- // State transitions, called from other threads
-
- void EnsureAwake() {
- ThreadStatus seen = status;
- if (seen == ThreadStatus::Blocking ||
- seen == ThreadStatus::Blocked) {
- std::unique_lock<OrtMutex> lk(mutex);
- // Blocking state exists only transiently during the SetBlock() method
- // while holding the lock. We may observe it at the start of this
- // function, but after acquiring the lock then the target thread
- // will either be blocked or not.
- seen = status;
- assert(seen != ThreadStatus::Blocking);
- if (seen == ThreadStatus::Blocked) {
- status = ThreadStatus::Waking;
- cv.notify_one();
- }
- }
- }
-
- // State transitions, called only from the thread itself
-
- void SetActive() {
- std::unique_lock<OrtMutex> lk(mutex);
- status = ThreadStatus::Active;
- }
-
- void SetSpinning() {
- std::unique_lock<OrtMutex> lk(mutex);
- status = ThreadStatus::Spinning;
- }
-
- void SetBlocked(std::function<bool()> should_block,
- std::function<void()> post_block) {
- std::unique_lock<OrtMutex> lk(mutex);
- assert(status == ThreadStatus::Spinning);
- status = ThreadStatus::Blocking;
- if (should_block()) {
- status = ThreadStatus::Blocked;
- while (status == ThreadStatus::Blocked) {
- cv.wait(lk);
- }
- post_block();
- }
- status = ThreadStatus::Spinning;
- }
-
- private:
- std::atomic<ThreadStatus> status{ThreadStatus::Spinning};
- OrtMutex mutex;
- OrtCondVar cv;
- };
-
- Environment& env_;
- const int num_threads_;
- const bool allow_spinning_;
- const bool set_denormal_as_zero_;
- Eigen::MaxSizeVector<WorkerData> worker_data_;
- Eigen::MaxSizeVector<Eigen::MaxSizeVector<unsigned>> all_coprimes_;
- std::atomic<unsigned> blocked_; // Count of blocked workers, used as a termination condition
- std::atomic<bool> done_;
- std::atomic<bool> cancelled_;
-
- // Allow control over how many bits to use in each entry in good_worker_hints_.
- // We reduce this below the full 64-bit word size for two reasons. First, it
- // helps test coverage on machines without 64 vCPUS. Second, it lets us
- // reduce contention by having different threads start work searching for hints
- // at different locations in the bitmap.
-
- static const unsigned bits_per_hint_word_ = 4;
- unsigned num_hint_words_;
- std::unique_ptr<std::atomic<uint64_t>[]> good_worker_hints_;
-
- // Wake any blocked workers so that they can cleanly exit WorkerLoop(). For an
- // abrupt exit, cancelled_==true and threads will exit their worker loops. For
- // a clean exit, each thread will observe (1) done_ set, indicating that the
- // destructor has been called, (2) all threads blocked, and (3) no
- // items in the work queues.
-
- void WakeAllWorkersForExit() {
- for (auto &td: worker_data_) {
- td.EnsureAwake();
- }
- }
-
- // Main worker thread loop.
- void WorkerLoop(int thread_id) {
- PerThread* pt = GetPerThread();
- WorkerData& td = worker_data_[thread_id];
- Queue& q = td.queue;
- bool should_exit = false;
- pt->pool = this;
- pt->rand = GlobalThreadIdHash();
- pt->thread_id = thread_id;
-
- assert(td.GetStatus() == WorkerData::ThreadStatus::Spinning);
- SetGoodWorkerHint(thread_id, true /* Is good */);
-
- const int log2_spin = 20;
- const int spin_count = allow_spinning_ ? (1ull<<log2_spin) : 0;
- const int steal_count = spin_count/100;
-
- SetDenormalAsZero(set_denormal_as_zero_);
-
- while (!cancelled_ && !should_exit) {
- Task t = q.PopFront();
- if (!t) {
- // Spin waiting for work. We indicate, via SetGOodWorkerHint that we are
- // spinning. This will bias other threads toward pushing work to our queue.
- // In addition, priodically make a best-effort attempt to steal from other
- // threads which are not themselves spinning.
-
- SetGoodWorkerHint(thread_id, true);
- for (int i = 0; i < spin_count && !t && !cancelled_ && !done_; i++) {
- t = ((i+1)%steal_count == 0) ? TrySteal() : q.PopFront();
- onnxruntime::concurrency::SpinPause();
- }
- SetGoodWorkerHint(thread_id, false);
-
- if (!t) {
- // No work passed to us while spinning; make a further full attempt to
- // steal work from other threads prior to blocking.
- if (num_threads_ != 1) {
- t = Steal(true /* true => check all queues */);
- }
- if (!t) {
- td.SetBlocked(
- // Pre-block test
- [&]() -> bool {
- bool should_block = true;
- // We already did a best-effort emptiness check when stealing; now
- // do a full check prior to blocking.
- int victim = NonEmptyQueueIndex();
- if (victim != -1) {
- should_block = false;
- if (!cancelled_) {
- t = worker_data_[victim].queue.PopBack();
- }
- }
- // Number of blocked threads is used as termination condition.
- // If we are shutting down and all worker threads blocked without work,
- // that's we are done.
- if (should_block) {
- blocked_++;
- if (done_ && blocked_ == static_cast<unsigned>(num_threads_)) {
- should_block = false;
- // Almost done, but need to re-check queues.
- // Consider that all queues are empty and all worker threads are preempted
- // right after incrementing blocked_ above. Now a free-standing thread
- // submits work and calls destructor (which sets done_). If we don't
- // re-check queues, we will exit leaving the work unexecuted.
- if (NonEmptyQueueIndex() != -1) {
- // Note: we must not pop from queues before we decrement blocked_,
- // otherwise the following scenario is possible. Consider that instead
- // of checking for emptiness we popped the only element from queues.
- // Now other worker threads can start exiting, which is bad if the
- // work item submits other work. So we just check emptiness here,
- // which ensures that all worker threads exit at the same time.
- blocked_--;
- } else {
- should_exit = true;
- }
- }
- }
- return should_block;
- },
- // Post-block update (executed only if we blocked)
- [&]() {
- blocked_--;
- });
- }
- }
- }
- if (t) {
- td.SetActive();
- t();
- td.SetSpinning();
- }
- }
-
- // Whichever thread(s) observe the termination conditions are responsible for waking
- // any other threads that have remained blocked.
- if (should_exit) {
- WakeAllWorkersForExit();
- }
- }
-
- // Steal tries to steal work from other worker threads in the range [start,
- // limit) in best-effort manner. We make two passes over the threads:
- //
- // - round 0 : we attempt to steal from threads that are running in
- // user code (ThreadStatus::Active). The intuition behind this is that
- // the thread is busy with other work, and that by preferring to
- // steel from busy victims we will avoid "snatching" work from a
- // thread which is just about to notice the work itself.
- //
- // - round 1 : we steal work from any thread, including those which claim
- // to be spinning. In these cases, even though the victim thread is
- // looking for work itself, it may have been pre-empted.
-
- Task Steal(bool check_all) {
- PerThread* pt = GetPerThread();
- unsigned size = static_cast<unsigned>(num_threads_);
- unsigned r = Rand(&pt->rand);
- unsigned inc = all_coprimes_[size - 1][r % all_coprimes_[size - 1].size()];
-
- for (int round = 0; round < 2; round++) {
- unsigned victim = r % size;
- for (unsigned i = 0; i < size; i++) {
- assert(victim < size);
- if (round == 1 ||
- worker_data_[victim].GetStatus() == WorkerData::ThreadStatus::Active) {
- Task t = worker_data_[victim].queue.PopBack();
- if (t) {
- return t;
- }
- }
- if (!check_all) {
- return Task();
- }
- victim += inc;
- if (victim >= size) {
- victim -= size;
- }
- }
- }
-
- return Task();
- }
-
- Task TrySteal() {
- return Steal(false);
- }
-
- int NonEmptyQueueIndex() {
- PerThread* pt = GetPerThread();
- const unsigned size = static_cast<unsigned>(worker_data_.size());
- unsigned r = Rand(&pt->rand);
- unsigned inc = all_coprimes_[size - 1][r % all_coprimes_[size - 1].size()];
- unsigned victim = r % size;
- for (unsigned i = 0; i < size; i++) {
- if (!worker_data_[victim].queue.Empty()) {
- return victim;
- }
- victim += inc;
- if (victim >= size) {
- victim -= size;
- }
- }
- return -1;
- }
-
- static EIGEN_STRONG_INLINE uint64_t GlobalThreadIdHash() {
- return std::hash<std::thread::id>()(std::this_thread::get_id());
- }
-
- static EIGEN_STRONG_INLINE PerThread* GetPerThread() {
- static thread_local PerThread per_thread_;
- PerThread* pt = &per_thread_;
- return pt;
- }
-
- static EIGEN_STRONG_INLINE unsigned Rand(uint64_t* state) {
- uint64_t current = *state;
- // Update the internal state
- *state = current * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL;
- // Generate the random output (using the PCG-XSH-RS scheme)
- return static_cast<unsigned>((current ^ (current >> 22)) >> (22 + (current >> 61)));
- }
-};
-
- } // namespace concurrency
-
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/platform/ort_mutex.h b/include/onnxruntime/core/platform/ort_mutex.h
deleted file mode 100755
index e24665f..0000000
--- a/include/onnxruntime/core/platform/ort_mutex.h
+++ /dev/null
@@ -1,189 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#ifdef _WIN32
-#include <Windows.h>
-#include <mutex>
-namespace onnxruntime {
-// Q: Why OrtMutex is better than std::mutex
-// A: OrtMutex supports static initialization but std::mutex doesn't. Static initialization helps us prevent the "static
-// initialization order problem".
-
-// Q: Why std::mutex can't make it?
-// A: VC runtime has to support Windows XP at ABI level. But we don't have such requirement.
-
-// Q: Is OrtMutex faster than std::mutex?
-// A: Sure
-
-class OrtMutex {
- private:
- SRWLOCK data_ = SRWLOCK_INIT;
-
- public:
- constexpr OrtMutex() = default;
- // SRW locks do not need to be explicitly destroyed.
- ~OrtMutex() = default;
- OrtMutex(const OrtMutex&) = delete;
- OrtMutex& operator=(const OrtMutex&) = delete;
- void lock() { AcquireSRWLockExclusive(native_handle()); }
- bool try_lock() noexcept { return TryAcquireSRWLockExclusive(native_handle()) == TRUE; }
- void unlock() noexcept { ReleaseSRWLockExclusive(native_handle()); }
- using native_handle_type = SRWLOCK*;
-
- __forceinline native_handle_type native_handle() { return &data_; }
-};
-
-class OrtCondVar {
- CONDITION_VARIABLE native_cv_object = CONDITION_VARIABLE_INIT;
-
- public:
- constexpr OrtCondVar() noexcept = default;
- ~OrtCondVar() = default;
-
- OrtCondVar(const OrtCondVar&) = delete;
- OrtCondVar& operator=(const OrtCondVar&) = delete;
-
- void notify_one() noexcept { WakeConditionVariable(&native_cv_object); }
- void notify_all() noexcept { WakeAllConditionVariable(&native_cv_object); }
-
- void wait(std::unique_lock<OrtMutex>& lk) {
- if (SleepConditionVariableSRW(&native_cv_object, lk.mutex()->native_handle(), INFINITE, 0) != TRUE) {
- std::terminate();
- }
- }
- template <class _Predicate>
- void wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred);
-
- /**
- * returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns
- * cv_status::no_timeout.
- * @param cond_mutex A unique_lock<OrtMutex> object.
- * @param rel_time A chrono::duration object that specifies the amount of time before the thread wakes up.
- * @return returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns
- * cv_status::no_timeout
- */
- template <class Rep, class Period>
- std::cv_status wait_for(std::unique_lock<OrtMutex>& cond_mutex, const std::chrono::duration<Rep, Period>& rel_time);
- using native_handle_type = CONDITION_VARIABLE*;
-
- native_handle_type native_handle() { return &native_cv_object; }
-
- private:
- void timed_wait_impl(std::unique_lock<OrtMutex>& __lk,
- std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>);
-};
-
-template <class _Predicate>
-void OrtCondVar::wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred) {
- while (!__pred()) wait(__lk);
-}
-
-template <class Rep, class Period>
-std::cv_status OrtCondVar::wait_for(std::unique_lock<OrtMutex>& cond_mutex,
- const std::chrono::duration<Rep, Period>& rel_time) {
- // TODO: is it possible to use nsync_from_time_point_ ?
- using namespace std::chrono;
- if (rel_time <= duration<Rep, Period>::zero())
- return std::cv_status::timeout;
- using SystemTimePointFloat = time_point<system_clock, duration<long double, std::nano> >;
- using SystemTimePoint = time_point<system_clock, nanoseconds>;
- SystemTimePointFloat max_time = SystemTimePoint::max();
- steady_clock::time_point steady_now = steady_clock::now();
- system_clock::time_point system_now = system_clock::now();
- if (max_time - rel_time > system_now) {
- nanoseconds remain = duration_cast<nanoseconds>(rel_time);
- if (remain < rel_time)
- ++remain;
- timed_wait_impl(cond_mutex, system_now + remain);
- } else
- timed_wait_impl(cond_mutex, SystemTimePoint::max());
- return steady_clock::now() - steady_now < rel_time ? std::cv_status::no_timeout : std::cv_status::timeout;
-}
-} // namespace onnxruntime
-#else
-#include "nsync.h"
-#include <mutex> //for unique_lock
-#include <condition_variable> //for cv_status
-namespace onnxruntime {
-
-class OrtMutex {
- nsync::nsync_mu data_ = NSYNC_MU_INIT;
-
- public:
- constexpr OrtMutex() = default;
- ~OrtMutex() = default;
- OrtMutex(const OrtMutex&) = delete;
- OrtMutex& operator=(const OrtMutex&) = delete;
-
- void lock() { nsync::nsync_mu_lock(&data_); }
- bool try_lock() noexcept { return nsync::nsync_mu_trylock(&data_) == 0; }
- void unlock() noexcept { nsync::nsync_mu_unlock(&data_); }
-
- using native_handle_type = nsync::nsync_mu*;
- native_handle_type native_handle() { return &data_; }
-};
-
-class OrtCondVar {
- nsync::nsync_cv native_cv_object = NSYNC_CV_INIT;
-
- public:
- constexpr OrtCondVar() noexcept = default;
-
- ~OrtCondVar() = default;
- OrtCondVar(const OrtCondVar&) = delete;
- OrtCondVar& operator=(const OrtCondVar&) = delete;
-
- void notify_one() noexcept { nsync::nsync_cv_signal(&native_cv_object); }
- void notify_all() noexcept { nsync::nsync_cv_broadcast(&native_cv_object); }
-
- void wait(std::unique_lock<OrtMutex>& lk);
- template <class _Predicate>
- void wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred);
-
- /**
- * returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns
- * cv_status::no_timeout.
- * @param cond_mutex A unique_lock<OrtMutex> object.
- * @param rel_time A chrono::duration object that specifies the amount of time before the thread wakes up.
- * @return returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns
- * cv_status::no_timeout
- */
- template <class Rep, class Period>
- std::cv_status wait_for(std::unique_lock<OrtMutex>& cond_mutex, const std::chrono::duration<Rep, Period>& rel_time);
- using native_handle_type = nsync::nsync_cv*;
- native_handle_type native_handle() { return &native_cv_object; }
-
- private:
- void timed_wait_impl(std::unique_lock<OrtMutex>& __lk,
- std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>);
-};
-
-template <class _Predicate>
-void OrtCondVar::wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred) {
- while (!__pred()) wait(__lk);
-}
-
-template <class Rep, class Period>
-std::cv_status OrtCondVar::wait_for(std::unique_lock<OrtMutex>& cond_mutex,
- const std::chrono::duration<Rep, Period>& rel_time) {
- // TODO: is it possible to use nsync_from_time_point_ ?
- using namespace std::chrono;
- if (rel_time <= duration<Rep, Period>::zero())
- return std::cv_status::timeout;
- using SystemTimePointFloat = time_point<system_clock, duration<long double, std::nano> >;
- using SystemTimePoint = time_point<system_clock, nanoseconds>;
- SystemTimePointFloat max_time = SystemTimePoint::max();
- steady_clock::time_point steady_now = steady_clock::now();
- system_clock::time_point system_now = system_clock::now();
- if (max_time - rel_time > system_now) {
- nanoseconds remain = duration_cast<nanoseconds>(rel_time);
- if (remain < rel_time)
- ++remain;
- timed_wait_impl(cond_mutex, system_now + remain);
- } else
- timed_wait_impl(cond_mutex, SystemTimePoint::max());
- return steady_clock::now() - steady_now < rel_time ? std::cv_status::no_timeout : std::cv_status::timeout;
-}
-}; // namespace onnxruntime
-#endif
diff --git a/include/onnxruntime/core/platform/threadpool.h b/include/onnxruntime/core/platform/threadpool.h
deleted file mode 100755
index 126dd13..0000000
--- a/include/onnxruntime/core/platform/threadpool.h
+++ /dev/null
@@ -1,441 +0,0 @@
-/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-==============================================================================*/
-
-/* Modifications Copyright (c) Microsoft. */
-
-#pragma once
-#include <string>
-#include <vector>
-#include <functional>
-#include <memory>
-#include "core/common/common.h"
-#include "core/platform/env.h"
-
-#include <functional>
-#include <memory>
-
-// ORT thread pool overview
-// ------------------------
-//
-// The ORT thread pool implementation is split into two layers. This
-// file provides the high-level component. See the accompanying
-// comments in EigenNonBlockingThreadPool.h for the low-level
-// component.
-//
-// threadpool.h defines the user-facing functions for use in
-// operators. The main abstraction are parallel loops
-// (ThreadPool::TryParallelFor*), although we also support scheduling
-// of asynchronous tasks (ThreadPool::Schedule), and the construction
-// of multi-loop parallel sections (ThreadPool::ParallelSection).
-//
-// This high level API is accessed via static methods on the
-// ThreadPool class. These methods map the operations onto one of
-// three low-level implementations: (#1) direct execution of the
-// operations if there is no thread pool configured, (#2) execution of
-// the operations using the modified Eigen threadpool, (#3) execution
-// of the operations using OpenMP. Option #1 enables execution in
-// simple settings without needing threads. Option #2 is the
-// preferred approach for use in settings with parallelism.
-//
-// The high-level part of the thread pool is responsible for:
-//
-// - Exposing the desired degree of parallelism to user code, and to
-// libraries such as MLAS. This lets the libraries tailor the
-// extent to which they parallelize work.
-//
-// - Handling trivial cases (such as directly running parallel loops
-// with only a single iteration, or with no iterations at all).
-//
-// - Deciding how to divide work efficiently between the threads
-// available.
-//
-// The ThreadPool::TryParallelFor methods do this based on cost
-// estimates supplied by the caller, and are designed to support
-// loops with small amounts of work per iteration. The loop body is
-// supplied as a function taking a [start,end) range of iterations
-// to execute (avoiding the need for per-iteration std::function
-// calls, or a reliance upon inlining to avoid those calls).
-//
-// ThreadPool::TrySimpleParallelFor uses a simpler single-iteration
-// API based on the assumption that the caller has divided work to
-// an appropriate granularity.
-//
-// - When used with the Eigen-based thread pool, the implementation of
-// all of the loops maps down onto
-// ThreadPool::ParallelForFixedBlockSizeScheduling. This method
-// takes the degree of parallelism (d_of_p) and work distribution
-// block size (from the cost-based heuristics), and creates a set of
-// tasks in the underlying thread pool (via
-// ThreadPool::RunInParallel).
-//
-// These tasks then run a loop which picks off batches of iterations
-// from the user's code. The distribution of these batches is
-// handled dynmamically via LoopCounter::ClaimIterations. This
-// dynamic balancing behavior helps make performance robust to any
-// variability in the execution time across iterations, and to
-// situations such as multiple loops running concurrently on the
-// same thread pool.
-//
-// - When running a series of loops inside a parallel section, the
-// LoopCounter also helps obtain affinity between these loops (i.e.,
-// iteration X of one loop will tend to run on the same thread that
-// ran iteration X of prior loops). This locality helps improve hit
-// rates in per-core caches across the series of short loops used in
-// operators like GRU.
-//
-// There are some known areas for exploration here:
-//
-// - The cost-based heuristics were developed prior to recent changes
-// to the thread pool. The heuristics seem to work well, but we
-// should revisit the tuning periodically.
-//
-// - Can we unify the APIs for the different kinds of parallel loop?
-//
-// In particular, we may be able to replace the current use of
-// TryBatchParallelFor with appropriate costs for each call site,
-// and then use TryParallelFor. This would allow for more dynamic
-// re-balancing of work between threads than the current
-// ThreadPool::PartitionWork function provides.
-//
-// - Given the extensive modifications to original Eigen code, should
-// we separate that out as a new class and remove the dependence on
-// other Eigen components.
-
-// This file use PIMPL to avoid having eigen headers here
-namespace Eigen {
-class Allocator;
-class ThreadPoolInterface;
-} // namespace Eigen
-
-namespace onnxruntime {
-
-struct TensorOpCost {
- double bytes_loaded;
- double bytes_stored;
- double compute_cycles;
-};
-
-
-namespace concurrency {
-
-template <typename Environment>
-class ThreadPoolTempl;
-
-class ExtendedThreadPoolInterface;
-class LoopCounter;
-class ThreadPoolParallelSection;
-
-class ThreadPool {
- public:
-#ifdef _WIN32
- using NAME_CHAR_TYPE = wchar_t;
-#else
- using NAME_CHAR_TYPE = char;
-#endif
- // Constructs a pool for running with with "degree_of_parallelism" threads with
- // specified "name". env->StartThread() is used to create individual threads
- // with the given ThreadOptions. If "low_latency_hint" is true the thread pool
- // implementation may use it as a hint that lower latency is preferred at the
- // cost of higher CPU usage, e.g. by letting one or more idle threads spin
- // wait. Conversely, if the threadpool is used to schedule high-latency
- // operations like I/O the hint should be set to false.
- //
- // REQUIRES: degree_of_parallelism > 0
- ThreadPool(Env* env,
- const ThreadOptions& thread_options,
- const NAME_CHAR_TYPE* name,
- int degree_of_parallelism,
- bool low_latency_hint);
-
- // Waits until all scheduled work has finished and then destroy the
- // set of threads.
- ~ThreadPool();
-
- // Start and end a multi-loop parallel section. Parallel loops can
- // be executed directly (without using this API), but entering a
- // parallel section allows the runtime system to amortize loop
- // entry/exit costs over multiple loops, and allows it to promote
- // affinity between corresponding iterations of different loops.
- //
- // Multi-loop sections would typically be used in cases where a
- // series of loops executes without much code in between them, and
- // where it is impractical to refactor code into a single loop. For
- // instance:
- //
- // {
- // onnxruntime::concurrency::ThreadPoool::ParallelSection ps(tp);
- // for (int x = 0; x < seq_len; x++) {
- // TrySimpleParallelFor(tp, 16, [&]() { ... });
- // }
- // }
- //
- // The parallel section is entered via the constructor of
- // ThreadPool::ParallelSection, and exited via the destructor.
- // Currently, thread-local state is used to track whether or not the
- // current thread is inside a parallel section. In contrast to
- // handling parallel section objects explicitly in user code, this
- // approach allows code such as MLAS to operate with/without the use
- // of parallel sections.
- //
- // Parallel sections are only implemented with the Eigen threadpool.
- // They have no effect when using OpenMP.
- //
- // Parallel sections may not be nested, and may not be used inside
- // parallel loops.
-
- class ParallelSection {
- public:
- explicit ParallelSection(ThreadPool *tp);
- ~ParallelSection();
-
- private:
- friend class ThreadPool;
-
- // Owning reference for the underlying ThreadPoolParallelSection
- // which implements the thread management. We use an explicit
- // deleter here so that the definition of
- // ThreadPoolParallelSection does not need to be available at this
- // point to avoid a dependence on the Eigen headers.
- std::unique_ptr<ThreadPoolParallelSection, void(*)(ThreadPoolParallelSection*)>
- ps_{nullptr, [](ThreadPoolParallelSection*){}};
-#ifndef _OPENMP
- ThreadPool *tp_;
-#endif
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ParallelSection);
-
- // Non-owning reference to the current thread's paralel section
- // (or nullptr outside parallel sections).
- static thread_local ParallelSection *current_parallel_section;
- static_assert(std::is_trivially_destructible<decltype(current_parallel_section)>::value,
- "Per-thread state should be trivially destructible");
- };
-
- // Schedules fn() for execution in the pool of threads. The function may run
- // synchronously if it cannot be enqueued. This will occur if the thread pool's
- // degree-of-parallelism is 1, but it may also occur for implementation-dependent
- // reasons such as if queues used for buffering work are full.
- static void Schedule(ThreadPool* tp,
- std::function<void()> fn) {
- if (tp) {
- tp->Schedule(fn);
- } else {
- fn();
- }
- }
-
- // ParallelFor shards the "total" units of work assuming each unit of work
- // having roughly "cost_per_unit" cost, in cycles. Each unit of work is
- // indexed 0, 1, ..., total - 1. Each shard contains 1 or more units of work
- // and the total cost of each shard is roughly the same.
- //
- // "cost_per_unit" is an estimate of the number of CPU cycles (or nanoseconds
- // if not CPU-bound) to complete a unit of work. Overestimating creates too
- // many shards and CPU time will be dominated by per-shard overhead, such as
- // Context creation. Underestimating may not fully make use of the specified
- // parallelism, and may also cause inefficiencies due to load balancing
- // issues and stragglers.
-
- static void TryParallelFor(ThreadPool* tp, std::ptrdiff_t total, double cost_per_unit,
- const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn) {
- TryParallelFor(tp, total, TensorOpCost{0, 0, static_cast<double>(cost_per_unit)}, fn);
- }
-
- static void TryParallelFor(ThreadPool* tp, std::ptrdiff_t total, const TensorOpCost& cost_per_unit,
- const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn);
-
- // Directly schedule the 'total' tasks to the underlying threadpool, without
- // cutting them by halves
-
- inline static void TrySimpleParallelFor(ThreadPool* tp, std::ptrdiff_t total,
- const std::function<void(std::ptrdiff_t)>& fn) {
-#ifdef _OPENMP
- ORT_UNUSED_PARAMETER(tp);
-#pragma omp parallel for
- for (std::ptrdiff_t i = 0; i < total; ++i) {
- fn(i);
- }
-#else
- if (tp != nullptr) {
- tp->SimpleParallelFor(total, fn);
- } else {
- for (std::ptrdiff_t i = 0; i < total; ++i) {
- // In many cases, fn can be inlined here.
- fn(i);
- }
- }
-#endif
- }
-
- /**
- * Tries to call the given function in parallel, with calls split into (num_batches) batches.
- *\param num_batches If it is zero, it will be replaced to the value of DegreeOfParallelism().
- *\param fn A std::function or STL style functor with signature of "void f(int32_t);"
- * Pitfall: Caller should cap `num_batches` to a reasonable value based on the cost of `fn` and the value of `total`.
- *For example, if fn is as simple as: int sum=0; fn = [&](int i){sum +=i;} and `total` is 100, then num_batches should
- *be just 1.
- *
- * ```
- **/
- template <typename F>
- inline static void TryBatchParallelFor(ThreadPool* tp, std::ptrdiff_t total, F&& fn, std::ptrdiff_t num_batches) {
-#ifdef _OPENMP
- ORT_UNUSED_PARAMETER(tp);
- ORT_UNUSED_PARAMETER(num_batches);
-#pragma omp parallel for
- for (std::ptrdiff_t i = 0; i < total; ++i) {
- fn(i);
- }
-#else
- if (tp == nullptr) {
- for (std::ptrdiff_t i = 0; i < total; ++i) {
- // In many cases, fn can be inlined here.
- fn(i);
- }
- return;
- }
- if (total <= 0)
- return;
-
- if (total == 1) {
- fn(0);
- return;
- }
-
- if (num_batches <= 0) {
- num_batches = std::min<ptrdiff_t>(total, DegreeOfParallelism(tp));
- }
-
- if (num_batches <= 1) {
- for (int i = 0; i < total; i++) {
- fn(i);
- }
- return;
- }
-
- tp->SimpleParallelFor(num_batches, [&](std::ptrdiff_t batch_index) {
- auto work = PartitionWork(batch_index, num_batches, total);
- for (std::ptrdiff_t i = work.start; i < work.end; i++) {
- fn(i);
- }
- });
-#endif
- }
-
- struct WorkInfo {
- std::ptrdiff_t start;
- std::ptrdiff_t end;
- };
-
- /** Calculate the start and end offsets for a batch.
- @remarks Based on MlasPartitionWork
- */
- static WorkInfo PartitionWork(std::ptrdiff_t batch_idx, std::ptrdiff_t num_batches, std::ptrdiff_t total_work) {
- const std::ptrdiff_t work_per_batch = total_work / num_batches;
- const std::ptrdiff_t work_per_batch_extra = total_work % num_batches;
-
- WorkInfo info;
- if (batch_idx < work_per_batch_extra) {
- info.start = (work_per_batch + 1) * batch_idx;
- info.end = info.start + work_per_batch + 1;
- } else {
- info.start = work_per_batch * batch_idx + work_per_batch_extra;
- info.end = info.start + work_per_batch;
- }
-
- return info;
- }
-
- //......................................................................
- //
- // The following static methods take into account whether OpenMP is
- // enabled/disabled, and if the thread pool pointer is nullptr
- // during sequential execution.
-
- // Provide a hint to the caller for whether or not to parallelize
- // work. This lets a caller switch to a sequential version of an
- // algorithm rather than using calls via the ParallelFor functions.
-
- static bool ShouldParallelize(const ThreadPool* tp);
-
- // Return the degree of parallelism that code should assume when using the thread pool.
- // It decouples the degree of parallelism for use with the thread pool from
- // the implementation choice of whether this matches the number of threads created in
- // the pool.
- //
- // Currently, a loop with degree-of-parallelism N is supported by a pool of N-1 threads
- // working in combination with the thread initiating the loop.
- static int DegreeOfParallelism(const ThreadPool* tp);
-
- ORT_DISALLOW_COPY_AND_ASSIGNMENT(ThreadPool);
-
- private:
- friend class LoopCounter;
-
- // Returns the number of threads created in the pool. This may be different from the
- // value returned by DegreeOfParallelism to code using the pool.
- int NumThreads() const;
-
- // Returns current thread id between 0 and NumThreads() - 1, if called from a
- // thread in the pool. Returns -1 otherwise.
- int CurrentThreadId() const;
-
- // Run fn with up to n degree-of-parallelism enlisting the thread pool for
- // help. The degree-of-parallelism includes the caller, and so if n==1
- // then the function will run directly in the caller. The fork-join
- // synchronization is handled in the thread pool, and so any state captured
- // by fn() is safe from concurrent access once RunWithHelp returns.
- void RunInParallel(std::function<void(unsigned idx)> fn, unsigned n);
-
- // Divides the work represented by the range [0, total) into k shards.
- // Calls fn(i*block_size, (i+1)*block_size) from the ith shard (0 <= i < k).
- // Each shard may be executed on a different thread in parallel, depending on
- // the number of threads available in the pool.
- // When (i+1)*block_size > total, fn(i*block_size, total) is called instead.
- // Requires 0 < block_size <= total.
- void ParallelForFixedBlockSizeScheduling(std::ptrdiff_t total, std::ptrdiff_t block_size,
- const std::function<void(std::ptrdiff_t, std::ptrdiff_t)>& fn);
-
- // Return whether or not the calling thread should run a loop of
- // num_iterations divided in chunks of block_size in parallel. If not,
- // the caller should run the loop sequentially.
- bool ShouldParallelizeLoop(const std::ptrdiff_t num_iterations,
- const std::ptrdiff_t block_size = 1) const;
-
- // Internal (non-static) parallel loop methods. Unlike the public static methods,
- // these will not handle the cases of OpenMP builds. or builds without a threadpool.
- void ParallelFor(std::ptrdiff_t total, double cost_per_unit,
- const std::function<void(std::ptrdiff_t first, std::ptrdiff_t last)>& fn);
-
- void ParallelFor(std::ptrdiff_t total, const TensorOpCost& cost_per_unit,
- const std::function<void(std::ptrdiff_t first, std::ptrdiff_t)>& fn);
-
- void SimpleParallelFor(std::ptrdiff_t total, const std::function<void(std::ptrdiff_t)>& fn);
-
- void Schedule(std::function<void()> fn);
-
- ThreadOptions thread_options_;
-
- // If a thread pool is created with degree_of_parallelism != 1 then an underlying
- // EigenThreadPool is used to create OS threads and handle work distribution to them.
- // If degree_of_parallelism == 1 then underlying_threadpool_ is left as nullptr
- // and parallel work is run directly by the caller.
- ExtendedThreadPoolInterface* underlying_threadpool_ = nullptr;
-
- // If used, underlying_threadpool_ is instantiated and owned by the ThreadPool.
- std::unique_ptr<ThreadPoolTempl<Env> > extended_eigen_threadpool_;
-};
-
-} // namespace concurrency
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/platform/tracing.h b/include/onnxruntime/core/platform/tracing.h
deleted file mode 100755
index fb61632..0000000
--- a/include/onnxruntime/core/platform/tracing.h
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <windows.h>
-#include <TraceLoggingProvider.h>
-
-TRACELOGGING_DECLARE_PROVIDER(telemetry_provider_handle);
diff --git a/include/onnxruntime/core/platform/windows/TraceLoggingConfig.h b/include/onnxruntime/core/platform/windows/TraceLoggingConfig.h
deleted file mode 100755
index 2ee92a8..0000000
--- a/include/onnxruntime/core/platform/windows/TraceLoggingConfig.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/* ++
-Module Name:
- TraceLoggingConfig.h
-Abstract:
- Macro definitions used by this project's TraceLogging ETW providers:
- - Configuration macros that select the ETW Provider Groups to be used by
- this project.
- - Constants for tags that are commonly used in Microsoft's
- TraceLogging-based ETW.
- Different versions of this file use different definitions for the
- TraceLoggingOption configuration macros. The definitions in this file are
- empty. As a result, providers using this configuration file will not join
- any ETW Provider Groups and will not be given any special treatment by
- group-sensitive ETW listeners.
-Environment:
- User mode or kernel mode.
---*/
-
-#pragma once
-
-// Configuration macro for use in TRACELOGGING_DEFINE_PROVIDER. The definition
-// in this file configures the provider as a normal (non-telemetry) provider.
-#ifndef TraceLoggingOptionMicrosoftTelemetry
-#define TraceLoggingOptionMicrosoftTelemetry() \
- TraceLoggingOptionGroup(0000000000, 00000, 00000, 0000, 0000, 0000, 0000, 0000, 000, 0000, 0000)
- // Empty definition for TraceLoggingOptionMicrosoftTelemetry
-#endif
-
-// Configuration macro for use in TRACELOGGING_DEFINE_PROVIDER. The definition
-// in this file configures the provider as a normal (non-telemetry) provider.
-#define TraceLoggingOptionWindowsCoreTelemetry() \
- // Empty definition for TraceLoggingOptionWindowsCoreTelemetry
-
-// Event privacy tags. Use the PDT macro values for the tag parameter, e.g.:
-// TraceLoggingWrite(...,
-// TelemetryPrivacyDataTag(PDT_BrowsingHistory | PDT_ProductAndServiceUsage),
-// ...);
-#define TelemetryPrivacyDataTag(tag) TraceLoggingUInt64((tag), "PartA_PrivTags")
-#define PDT_BrowsingHistory 0x0000000000000002u
-#define PDT_DeviceConnectivityAndConfiguration 0x0000000000000800u
-#define PDT_InkingTypingAndSpeechUtterance 0x0000000000020000u
-#define PDT_ProductAndServicePerformance 0x0000000001000000u
-#define PDT_ProductAndServiceUsage 0x0000000002000000u
-#define PDT_SoftwareSetupAndInventory 0x0000000080000000u
-
-// Event categories specified via keywords, e.g.:
-// TraceLoggingWrite(...,
-// TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
-// ...);
-#define MICROSOFT_KEYWORD_CRITICAL_DATA 0x0000800000000000 // Bit 47
-#define MICROSOFT_KEYWORD_MEASURES 0x0000400000000000 // Bit 46
-#define MICROSOFT_KEYWORD_TELEMETRY 0x0000200000000000 // Bit 45
-#define MICROSOFT_KEYWORD_RESERVED_44 0x0000100000000000 // Bit 44 (reserved for future assignment)
-
-// Event categories specified via event tags, e.g.:
-// TraceLoggingWrite(...,
-// TraceLoggingEventTag(MICROSOFT_EVENTTAG_REALTIME_LATENCY),
-// ...);
-#define MICROSOFT_EVENTTAG_DROP_USER_IDS 0x00008000
-#define MICROSOFT_EVENTTAG_AGGREGATE 0x00010000
-#define MICROSOFT_EVENTTAG_DROP_PII_EXCEPT_IP 0x00020000
-#define MICROSOFT_EVENTTAG_COSTDEFERRED_LATENCY 0x00040000
-#define MICROSOFT_EVENTTAG_CORE_DATA 0x00080000
-#define MICROSOFT_EVENTTAG_INJECT_XTOKEN 0x00100000
-#define MICROSOFT_EVENTTAG_REALTIME_LATENCY 0x00200000
-#define MICROSOFT_EVENTTAG_NORMAL_LATENCY 0x00400000
-#define MICROSOFT_EVENTTAG_CRITICAL_PERSISTENCE 0x00800000
-#define MICROSOFT_EVENTTAG_NORMAL_PERSISTENCE 0x01000000
-#define MICROSOFT_EVENTTAG_DROP_PII 0x02000000
-#define MICROSOFT_EVENTTAG_HASH_PII 0x04000000
-#define MICROSOFT_EVENTTAG_MARK_PII 0x08000000
-
-// Field categories specified via field tags, e.g.:
-// TraceLoggingWrite(...,
-// TraceLoggingString(szUser, "UserName", "User's name", MICROSOFT_FIELDTAG_HASH_PII),
-// ...);
-#define MICROSOFT_FIELDTAG_DROP_PII 0x04000000
-#define MICROSOFT_FIELDTAG_HASH_PII 0x08000000
diff --git a/include/onnxruntime/core/platform/windows/readme.txt b/include/onnxruntime/core/platform/windows/readme.txt
deleted file mode 100755
index f1a436f..0000000
--- a/include/onnxruntime/core/platform/windows/readme.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-copied from minkernel/published/internal/telemetry/open_source/TraceLoggingConfig.h
-this is the official open source edition for these configuration settings
\ No newline at end of file
diff --git a/include/onnxruntime/core/providers/acl/acl_provider_factory.h b/include/onnxruntime/core/providers/acl/acl_provider_factory.h
deleted file mode 100755
index 0dc0ec2..0000000
--- a/include/onnxruntime/core/providers/acl/acl_provider_factory.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param use_arena zero: false. non-zero: true.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ACL, _In_ OrtSessionOptions* options, int use_arena)
-ORT_ALL_ARGS_NONNULL;
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/armnn/armnn_provider_factory.h b/include/onnxruntime/core/providers/armnn/armnn_provider_factory.h
deleted file mode 100755
index 35276db..0000000
--- a/include/onnxruntime/core/providers/armnn/armnn_provider_factory.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param use_arena zero: false. non-zero: true.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ArmNN, _In_ OrtSessionOptions* options, int use_arena)
-ORT_ALL_ARGS_NONNULL;
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/cpu/cpu_provider_factory.h b/include/onnxruntime/core/providers/cpu/cpu_provider_factory.h
deleted file mode 100755
index 66f2589..0000000
--- a/include/onnxruntime/core/providers/cpu/cpu_provider_factory.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param use_arena zero: false. non-zero: true.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena)
-ORT_ALL_ARGS_NONNULL;
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/cuda/cuda_provider_factory.h b/include/onnxruntime/core/providers/cuda/cuda_provider_factory.h
deleted file mode 100755
index 81b5477..0000000
--- a/include/onnxruntime/core/providers/cuda/cuda_provider_factory.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param device_id cuda device id, starts from zero.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/dml/dml_provider_factory.h b/include/onnxruntime/core/providers/dml/dml_provider_factory.h
deleted file mode 100755
index 071e7f0..0000000
--- a/include/onnxruntime/core/providers/dml/dml_provider_factory.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma warning(push)
-#pragma warning(disable : 4201) // nonstandard extension used: nameless struct/union
-#include <d3d12.h>
-#pragma warning(pop)
-
-#ifdef __cplusplus
- #include <DirectML.h>
-#else
- struct IDMLDevice;
- typedef struct IDMLDevice IDMLDevice;
-#endif
-
-// Windows pollutes the macro space, causing a build break in constants.h.
-#undef OPTIONAL
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Creates a DirectML Execution Provider which executes on the hardware adapter with the given device_id, also known as
- * the adapter index. The device ID corresponds to the enumeration order of hardware adapters as given by
- * IDXGIFactory::EnumAdapters. A device_id of 0 always corresponds to the default adapter, which is typically the
- * primary display GPU installed on the system. A negative device_id is invalid.
-*/
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_DML, _In_ OrtSessionOptions* options, int device_id);
-
-/**
- * Creates a DirectML Execution Provider using the given DirectML device, and which executes work on the supplied D3D12
- * command queue. The DirectML device and D3D12 command queue must have the same parent ID3D12Device, or an error will
- * be returned. The D3D12 command queue must be of type DIRECT or COMPUTE (see D3D12_COMMAND_LIST_TYPE). If this
- * function succeeds, the inference session maintains a strong reference on both the dml_device and the command_queue
- * objects.
- * See also: DMLCreateDevice
- * See also: ID3D12Device::CreateCommandQueue
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProviderEx_DML, _In_ OrtSessionOptions* options,
- _In_ IDMLDevice* dml_device, _In_ ID3D12CommandQueue* cmd_queue);
-
-#ifdef __cplusplus
-}
-#endif
\ No newline at end of file
diff --git a/include/onnxruntime/core/providers/dnnl/dnnl_provider_factory.h b/include/onnxruntime/core/providers/dnnl/dnnl_provider_factory.h
deleted file mode 100755
index b87780c..0000000
--- a/include/onnxruntime/core/providers/dnnl/dnnl_provider_factory.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param use_arena zero: false. non-zero: true.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/migraphx/migraphx_provider_factory.h b/include/onnxruntime/core/providers/migraphx/migraphx_provider_factory.h
deleted file mode 100755
index 8f8219f..0000000
--- a/include/onnxruntime/core/providers/migraphx/migraphx_provider_factory.h
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2019 AMD AMDMIGraphX
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id);
-
-#ifdef __cplusplus
-}
-#endif
-
-
diff --git a/include/onnxruntime/core/providers/nnapi/nnapi_provider_factory.h b/include/onnxruntime/core/providers/nnapi/nnapi_provider_factory.h
deleted file mode 100755
index 1da88b1..0000000
--- a/include/onnxruntime/core/providers/nnapi/nnapi_provider_factory.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-#pragma once
-
-#include "onnxruntime_c_api.h"
-
-// NNAPIFlags are bool options we want to set for NNAPI EP
-// This enum is defined as bit flats, and cannot have negative value
-// To generate an uint32_t nnapi_flags for using with OrtSessionOptionsAppendExecutionProvider_Nnapi below,
-// uint32_t nnapi_flags = 0;
-// nnapi_flags |= NNAPI_FLAG_USE_FP16;
-enum NNAPIFlags {
- NNAPI_FLAG_USE_NONE = 0x000,
-
- // Using fp16 relaxation in NNAPI EP, this may improve perf but may also reduce precision
- NNAPI_FLAG_USE_FP16 = 0x001,
-
- // Use NCHW layout in NNAPI EP, this is only available after Android API level 29
- // Please note for now, NNAPI perform worse using NCHW compare to using NHWC
- NNAPI_FLAG_USE_NCHW = 0x002,
-
- // Keep NNAPI_FLAG_MAX at the end of the enum definition
- // And assign the last NNAPIFlag to it
- NNAPI_FLAG_LAST = NNAPI_FLAG_USE_NCHW,
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Nnapi, _In_ OrtSessionOptions* options, uint32_t nnapi_flags);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/nuphar/nuphar_provider_factory.h b/include/onnxruntime/core/providers/nuphar/nuphar_provider_factory.h
deleted file mode 100755
index ec574f7..0000000
--- a/include/onnxruntime/core/providers/nuphar/nuphar_provider_factory.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-#pragma once
-#include "core/session/onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-/**
- * \param device_id nuphar device id, starts from zero.
- * \param settings_str Nuphar settings string.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Nuphar, _In_ OrtSessionOptions* options, int allow_unaligned_buffers, _In_ const char* settings_str);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/openvino/openvino_provider_factory.h b/include/onnxruntime/core/providers/openvino/openvino_provider_factory.h
deleted file mode 100755
index 7646644..0000000
--- a/include/onnxruntime/core/providers/openvino/openvino_provider_factory.h
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright(C) 2019 Intel Corporation
-// Licensed under the MIT License
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-struct ProviderInfo_OpenVINO {
- virtual std::vector<std::string> GetAvailableDevices() const = 0;
-};
-
-extern "C" {
-#endif
-
-/**
- * \param device_type openvino device type and precision. Could be any of
- * CPU_FP32, GPU_FP32, GPU_FP16, MYRIAD_FP16, VAD-M_FP16 or VAD-F_FP32.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_OpenVINO,
- _In_ OrtSessionOptions* options, _In_ const char* device_type);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/providers.h b/include/onnxruntime/core/providers/providers.h
deleted file mode 100755
index 2cfd5ac..0000000
--- a/include/onnxruntime/core/providers/providers.h
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-namespace onnxruntime {
-class IExecutionProvider;
-
-struct IExecutionProviderFactory {
- virtual ~IExecutionProviderFactory() = default;
- virtual std::unique_ptr<IExecutionProvider> CreateProvider() = 0;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/providers/rknpu/rknpu_provider_factory.h b/include/onnxruntime/core/providers/rknpu/rknpu_provider_factory.h
deleted file mode 100755
index 832171e..0000000
--- a/include/onnxruntime/core/providers/rknpu/rknpu_provider_factory.h
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2020 rock-chips.com Inc.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Rknpu,
- _In_ OrtSessionOptions* options);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/rocm/rocm_provider_factory.h b/include/onnxruntime/core/providers/rocm/rocm_provider_factory.h
deleted file mode 100755
index 6152883..0000000
--- a/include/onnxruntime/core/providers/rocm/rocm_provider_factory.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param device_id hip device id, starts from zero.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id, size_t hip_mem_limit);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/tensorrt/tensorrt_provider_factory.h b/include/onnxruntime/core/providers/tensorrt/tensorrt_provider_factory.h
deleted file mode 100755
index 44debc9..0000000
--- a/include/onnxruntime/core/providers/tensorrt/tensorrt_provider_factory.h
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/vitisai/vitisai_provider_factory.h b/include/onnxruntime/core/providers/vitisai/vitisai_provider_factory.h
deleted file mode 100755
index eb4765b..0000000
--- a/include/onnxruntime/core/providers/vitisai/vitisai_provider_factory.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Xilinx Inc.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * \param use_arena zero: false. non-zero: true.
- */
-ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_VITISAI, _In_ OrtSessionOptions* options, const char *backend_type, int device_id);
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/providers/winml/winml_provider_factory.h b/include/onnxruntime/core/providers/winml/winml_provider_factory.h
deleted file mode 100755
index b08b42e..0000000
--- a/include/onnxruntime/core/providers/winml/winml_provider_factory.h
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#include "onnxruntime_c_api.h"
-
-struct WinmlAdapterApi;
-typedef struct WinmlAdapterApi WinmlAdapterApi;
-
-ORT_EXPORT const WinmlAdapterApi* ORT_API_CALL OrtGetWinMLAdapter(_In_ const OrtApi* ort_api) NO_EXCEPTION;
\ No newline at end of file
diff --git a/include/onnxruntime/core/session/automl_data_containers.h b/include/onnxruntime/core/session/automl_data_containers.h
deleted file mode 100755
index 249e42a..0000000
--- a/include/onnxruntime/core/session/automl_data_containers.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-// This header contains shared definitions for reading and writing
-// via C/C++ API Opaque data types that are registered within ORT
-#pragma once
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-// This structure is used to initialize and read
-// OrtValue of opaque(com.microsoft.featurizers,DateTimeFeaturizer_TimePoint)
-struct DateTimeFeaturizerTimePointData {
- int32_t year;
- uint8_t month;
- uint8_t day;
- uint8_t hour;
- uint8_t minute;
- uint8_t second;
- uint8_t dayOfWeek;
- uint16_t dayOfYear;
- uint8_t quarterOfYear;
- uint8_t weekOfMonth;
-};
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
diff --git a/include/onnxruntime/core/session/environment.h b/include/onnxruntime/core/session/environment.h
deleted file mode 100755
index 5f7f6e2..0000000
--- a/include/onnxruntime/core/session/environment.h
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-#include <atomic>
-#include <memory>
-#include "core/common/common.h"
-#include "core/common/status.h"
-#include "core/platform/threadpool.h"
-#include "core/common/logging/logging.h"
-#include "core/framework/allocator.h"
-
-struct OrtThreadingOptions;
-namespace onnxruntime {
-/** TODO: remove this class
- Provides the runtime environment for onnxruntime.
- Create one instance for the duration of execution.
-*/
-class Environment {
- public:
- /**
- Create and initialize the runtime environment.
- @param logging manager instance that will enable per session logger output using
- session_options.session_logid as the logger id in messages.
- If nullptr, the default LoggingManager MUST have been created previously as it will be used
- for logging. This will use the default logger id in messages.
- See core/common/logging/logging.h for details, and how LoggingManager::DefaultLogger works.
- @param tp_options optional set of parameters controlling the number of intra and inter op threads for the global
- threadpools.
- @param create_global_thread_pools determine if this function will create the global threadpools or not.
- */
- static Status Create(std::unique_ptr<logging::LoggingManager> logging_manager,
- std::unique_ptr<Environment>& environment,
- const OrtThreadingOptions* tp_options = nullptr,
- bool create_global_thread_pools = false);
-
- logging::LoggingManager* GetLoggingManager() const {
- return logging_manager_.get();
- }
-
- void SetLoggingManager(std::unique_ptr<onnxruntime::logging::LoggingManager> logging_manager) {
- logging_manager_ = std::move(logging_manager);
- }
-
- onnxruntime::concurrency::ThreadPool* GetIntraOpThreadPool() const {
- return intra_op_thread_pool_.get();
- }
-
- onnxruntime::concurrency::ThreadPool* GetInterOpThreadPool() const {
- return inter_op_thread_pool_.get();
- }
-
- bool EnvCreatedWithGlobalThreadPools() const {
- return create_global_thread_pools_;
- }
-
- /**
- * Registers an allocator for sharing between multiple sessions.
- * Return an error if an allocator with the same OrtMemoryInfo is already registered.
- */
- Status RegisterAllocator(AllocatorPtr allocator);
-
- /**
- * Creates and registers an allocator for sharing between multiple sessions.
- * Return an error if an allocator with the same OrtMemoryInfo is already registered.
- */
- Status CreateAndRegisterAllocator(const OrtMemoryInfo& mem_info, const OrtArenaCfg* arena_cfg = nullptr);
-
- /**
- * Returns the list of registered allocators in this env.
- */
- const std::vector<AllocatorPtr>& GetRegisteredSharedAllocators() const {
- return shared_allocators_;
- }
-
- private:
- ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Environment);
-
- Environment() = default;
- Status Initialize(std::unique_ptr<logging::LoggingManager> logging_manager,
- const OrtThreadingOptions* tp_options = nullptr,
- bool create_global_thread_pools = false);
-
- std::unique_ptr<logging::LoggingManager> logging_manager_;
- std::unique_ptr<onnxruntime::concurrency::ThreadPool> intra_op_thread_pool_;
- std::unique_ptr<onnxruntime::concurrency::ThreadPool> inter_op_thread_pool_;
- bool create_global_thread_pools_{false};
- std::vector<AllocatorPtr> shared_allocators_;
-};
-} // namespace onnxruntime
diff --git a/include/onnxruntime/core/session/experimental_onnxruntime_cxx_api.h b/include/onnxruntime/core/session/experimental_onnxruntime_cxx_api.h
deleted file mode 100755
index 6efb20a..0000000
--- a/include/onnxruntime/core/session/experimental_onnxruntime_cxx_api.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-// Summary: The experimental Ort C++ API is a wrapper around the Ort C++ API.
-//
-// This C++ API further simplifies usage and provides support for modern C++ syntax/features
-// at the cost of some overhead (i.e. using std::string over char *).
-//
-// Where applicable, default memory allocator options are used unless explicitly set.
-//
-// Experimental components are designed as drop-in replacements of the regular API, requiring
-// minimal code modifications to use.
-//
-// Example: Ort::Session -> Ort::Experimental::Session
-//
-// NOTE: Experimental API components are subject to change based on feedback and provide no
-// guarantee of backwards compatibility in future releases.
-
-#pragma once
-#include "onnxruntime_cxx_api.h"
-
-namespace Ort {
-namespace Experimental {
-
-struct Session : Ort::Session {
- Session(Env& env, std::basic_string<ORTCHAR_T>& model_path, SessionOptions& options)
- : Ort::Session(env, model_path.data(), options){};
- Session(Env& env, void* model_data, size_t model_data_length, SessionOptions& options)
- : Ort::Session(env, model_data, model_data_length, options){};
-
- // overloaded Run() with sensible defaults
- std::vector<Ort::Value> Run(const std::vector<std::string>& input_names,
- const std::vector<Ort::Value>& input_values,
- const std::vector<std::string>& output_names,
- const RunOptions& run_options = RunOptions());
- void Run(const std::vector<std::string>& input_names,
- const std::vector<Ort::Value>& input_values,
- const std::vector<std::string>& output_names,
- std::vector<Ort::Value>& output_values,
- const RunOptions& run_options = RunOptions());
-
- // convenience methods that simplify common lower-level API calls
- std::vector<std::string> GetInputNames() const;
- std::vector<std::string> GetOutputNames() const;
- std::vector<std::string> GetOverridableInitializerNames() const;
-
- // NOTE: shape dimensions may have a negative value to indicate a symbolic/unknown dimension.
- std::vector<std::vector<int64_t> > GetInputShapes() const;
- std::vector<std::vector<int64_t> > GetOutputShapes() const;
- std::vector<std::vector<int64_t> > GetOverridableInitializerShapes() const;
-};
-
-struct Value : Ort::Value {
- Value(OrtValue* p)
- : Ort::Value(p){};
-
- template <typename T>
- static Ort::Value CreateTensor(T* p_data, size_t p_data_element_count, const std::vector<int64_t>& shape);
- static Ort::Value CreateTensor(void* p_data, size_t p_data_byte_count, const std::vector<int64_t>& shape, ONNXTensorElementDataType type);
-
- template <typename T>
- static Ort::Value CreateTensor(const std::vector<int64_t>& shape);
- static Ort::Value CreateTensor(const std::vector<int64_t>& shape, ONNXTensorElementDataType type);
-};
-
-}
-}
-
-#include "experimental_onnxruntime_cxx_inline.h"
diff --git a/include/onnxruntime/core/session/experimental_onnxruntime_cxx_inline.h b/include/onnxruntime/core/session/experimental_onnxruntime_cxx_inline.h
deleted file mode 100755
index 075de83..0000000
--- a/include/onnxruntime/core/session/experimental_onnxruntime_cxx_inline.h
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-// Do not include this file directly. Please include "experimental_onnxruntime_cxx_api.h" instead.
-//
-// These are the inline implementations of the C++ header APIs. They are in this separate file as to not clutter
-// the main C++ file with implementation details.
-namespace Ort {
-namespace Experimental {
-
-inline std::vector<Ort::Value> Session::Run(const std::vector<std::string>& input_names, const std::vector<Ort::Value>& input_values,
- const std::vector<std::string>& output_names, const RunOptions& run_options) {
- size_t output_names_count = GetOutputNames().size();
- std::vector<Ort::Value> output_values;
- for (size_t i = 0; i < output_names_count; i++) output_values.emplace_back(nullptr);
- Run(input_names, input_values, output_names, output_values, run_options);
- return output_values;
-}
-
-inline void Session::Run(const std::vector<std::string>& input_names, const std::vector<Ort::Value>& input_values,
- const std::vector<std::string>& output_names, std::vector<Ort::Value>& output_values, const RunOptions& run_options) {
- size_t input_names_count = input_names.size();
- size_t output_names_count = output_names.size();
- std::vector<const char*> input_names_(input_names_count, nullptr);
- size_t i = 0;
- for (auto it = input_names.begin(); it != input_names.end(); it++) input_names_[i++] = (*it).c_str();
- std::vector<const char*> output_names_(output_names_count, nullptr);
- i = 0;
- for (auto it = output_names.begin(); it != output_names.end(); it++) output_names_[i++] = (*it).c_str();
- Ort::Session::Run(run_options, input_names_.data(), input_values.data(), input_names_count, output_names_.data(), output_values.data(), output_names_count);
-}
-
-inline std::vector<std::string> Session::GetInputNames() const {
- Ort::AllocatorWithDefaultOptions allocator;
- size_t node_count = GetInputCount();
- std::vector<std::string> out(node_count);
- for (size_t i = 0; i < node_count; i++) {
- char* tmp = GetInputName(i, allocator);
- out[i] = tmp;
- allocator.Free(tmp); // prevent memory leak
- }
- return out;
-}
-
-inline std::vector<std::string> Session::GetOutputNames() const {
- Ort::AllocatorWithDefaultOptions allocator;
- size_t node_count = GetOutputCount();
- std::vector<std::string> out(node_count);
- for (size_t i = 0; i < node_count; i++) {
- char* tmp = GetOutputName(i, allocator);
- out[i] = tmp;
- allocator.Free(tmp); // prevent memory leak
- }
- return out;
-}
-
-inline std::vector<std::string> Session::GetOverridableInitializerNames() const {
- Ort::AllocatorWithDefaultOptions allocator;
- size_t init_count = GetOverridableInitializerCount();
- std::vector<std::string> out(init_count);
- for (size_t i = 0; i < init_count; i++) {
- char* tmp = GetOverridableInitializerName(i, allocator);
- out[i] = tmp;
- allocator.Free(tmp); // prevent memory leak
- }
- return out;
-}
-
-inline std::vector<std::vector<int64_t>> Session::GetInputShapes() const {
- size_t node_count = GetInputCount();
- std::vector<std::vector<int64_t>> out(node_count);
- for (size_t i = 0; i < node_count; i++) out[i] = GetInputTypeInfo(i).GetTensorTypeAndShapeInfo().GetShape();
- return out;
-}
-
-inline std::vector<std::vector<int64_t>> Session::GetOutputShapes() const {
- size_t node_count = GetOutputCount();
- std::vector<std::vector<int64_t>> out(node_count);
- for (size_t i = 0; i < node_count; i++) out[i] = GetOutputTypeInfo(i).GetTensorTypeAndShapeInfo().GetShape();
- return out;
-}
-
-inline std::vector<std::vector<int64_t>> Session::GetOverridableInitializerShapes() const {
- size_t init_count = GetOverridableInitializerCount();
- std::vector<std::vector<int64_t>> out(init_count);
- for (size_t i = 0; i < init_count; i++) out[i] = GetOverridableInitializerTypeInfo(i).GetTensorTypeAndShapeInfo().GetShape();
- return out;
-}
-
-template <typename T>
-inline Ort::Value Value::CreateTensor(T* p_data, size_t p_data_element_count, const std::vector<int64_t>& shape) {
- return CreateTensor(p_data, p_data_element_count * sizeof(T), shape, TypeToTensorType<T>::type);
-}
-
-inline Ort::Value Value::CreateTensor(void* p_data, size_t p_data_byte_count, const std::vector<int64_t>& shape, ONNXTensorElementDataType type) {
- Ort::MemoryInfo info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
- return Ort::Value::CreateTensor(info, p_data, p_data_byte_count, shape.data(), shape.size(), type);
-}
-
-template <typename T>
-inline Ort::Value Value::CreateTensor(const std::vector<int64_t>& shape) {
- return CreateTensor(shape, TypeToTensorType<T>::type);
-}
-
-inline Ort::Value Value::CreateTensor(const std::vector<int64_t>& shape, ONNXTensorElementDataType type) {
- Ort::AllocatorWithDefaultOptions allocator;
- return Ort::Value::CreateTensor(allocator, shape.data(), shape.size(), type);
-}
-
-}
-}
diff --git a/include/onnxruntime/core/session/onnxruntime_c_api.h b/include/onnxruntime/core/session/onnxruntime_c_api.h
deleted file mode 100755
index ab8b65c..0000000
--- a/include/onnxruntime/core/session/onnxruntime_c_api.h
+++ /dev/null
@@ -1,1193 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-
-// This value is used in structures passed to ORT so that a newer version of ORT will still work with them
-#define ORT_API_VERSION 7
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// SAL2 Definitions
-#ifndef _WIN32
-#define _In_
-#define _In_z_
-#define _In_opt_
-#define _In_opt_z_
-#define _Out_
-#define _Outptr_
-#define _Out_opt_
-#define _Inout_
-#define _Inout_opt_
-#define _Frees_ptr_opt_
-#define _Ret_maybenull_
-#define _Ret_notnull_
-#define _Check_return_
-#define _Outptr_result_maybenull_
-#define _In_reads_(X)
-#define _Inout_updates_all_(X)
-#define _Out_writes_bytes_all_(X)
-#define _Out_writes_all_(X)
-#define _Success_(X)
-#define _Outptr_result_buffer_maybenull_(X)
-#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull))
-#else
-#include <specstrings.h>
-#define ORT_ALL_ARGS_NONNULL
-#endif
-
-#ifdef _WIN32
-// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort.
-// dllexport is not used, we use a .def file.
-#ifdef ORT_DLL_IMPORT
-#define ORT_EXPORT __declspec(dllimport)
-#else
-#define ORT_EXPORT
-#endif
-#define ORT_API_CALL _stdcall
-#define ORT_MUST_USE_RESULT
-#define ORTCHAR_T wchar_t
-#else
-#define ORT_EXPORT
-#define ORT_API_CALL
-#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result))
-#define ORTCHAR_T char
-#endif
-
-#ifndef ORT_TSTR
-#ifdef _WIN32
-#define ORT_TSTR(X) L##X
-#else
-#define ORT_TSTR(X) X
-#endif
-#endif
-
-// Any pointer marked with _In_ or _Out_, cannot be NULL.
-
-// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation
-// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that.
-// for ReleaseXXX(...) functions, they can accept NULL pointer.
-
-#ifdef __cplusplus
-// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept.
-// Such complex condition is needed because compilers set __cplusplus value differently.
-#ifndef __has_feature
-#define __has_feature(x) 0
-#endif
-#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept)))
-#define NO_EXCEPTION noexcept
-#else
-#define NO_EXCEPTION throw()
-#endif
-#else
-#define NO_EXCEPTION
-#endif
-
-// Copied from TensorProto::DataType
-// Currently, Ort doesn't support complex64, complex128
-typedef enum ONNXTensorElementDataType {
- ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED,
- ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float
- ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string
- ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL,
- ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16,
- ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double
- ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t
- ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components
- ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components
- ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16 // Non-IEEE floating-point format based on IEEE754 single-precision
-} ONNXTensorElementDataType;
-
-// Synced with onnx TypeProto oneof
-typedef enum ONNXType {
- ONNX_TYPE_UNKNOWN,
- ONNX_TYPE_TENSOR,
- ONNX_TYPE_SEQUENCE,
- ONNX_TYPE_MAP,
- ONNX_TYPE_OPAQUE,
- ONNX_TYPE_SPARSETENSOR,
-} ONNXType;
-
-typedef enum OrtLoggingLevel {
- ORT_LOGGING_LEVEL_VERBOSE,
- ORT_LOGGING_LEVEL_INFO,
- ORT_LOGGING_LEVEL_WARNING,
- ORT_LOGGING_LEVEL_ERROR,
- ORT_LOGGING_LEVEL_FATAL,
-} OrtLoggingLevel;
-
-typedef enum OrtErrorCode {
- ORT_OK,
- ORT_FAIL,
- ORT_INVALID_ARGUMENT,
- ORT_NO_SUCHFILE,
- ORT_NO_MODEL,
- ORT_ENGINE_ERROR,
- ORT_RUNTIME_EXCEPTION,
- ORT_INVALID_PROTOBUF,
- ORT_MODEL_LOADED,
- ORT_NOT_IMPLEMENTED,
- ORT_INVALID_GRAPH,
- ORT_EP_FAIL,
-} OrtErrorCode;
-
-#define ORT_RUNTIME_CLASS(X) \
- struct Ort##X; \
- typedef struct Ort##X Ort##X;
-
-// The actual types defined have an Ort prefix
-ORT_RUNTIME_CLASS(Env);
-ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success
-ORT_RUNTIME_CLASS(MemoryInfo);
-ORT_RUNTIME_CLASS(IoBinding);
-ORT_RUNTIME_CLASS(Session); //Don't call OrtReleaseSession from Dllmain (because session owns a thread pool)
-ORT_RUNTIME_CLASS(Value);
-ORT_RUNTIME_CLASS(RunOptions);
-ORT_RUNTIME_CLASS(TypeInfo);
-ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo);
-ORT_RUNTIME_CLASS(SessionOptions);
-ORT_RUNTIME_CLASS(CustomOpDomain);
-ORT_RUNTIME_CLASS(MapTypeInfo);
-ORT_RUNTIME_CLASS(SequenceTypeInfo);
-ORT_RUNTIME_CLASS(ModelMetadata);
-ORT_RUNTIME_CLASS(ThreadPoolParams);
-ORT_RUNTIME_CLASS(ThreadingOptions);
-ORT_RUNTIME_CLASS(ArenaCfg);
-
-#ifdef _WIN32
-typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr;
-#else
-typedef OrtStatus* OrtStatusPtr;
-#endif
-
-// __VA_ARGS__ on Windows and Linux are different
-#define ORT_API(RETURN_TYPE, NAME, ...) ORT_EXPORT RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION
-
-#define ORT_API_STATUS(NAME, ...) \
- ORT_EXPORT _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT
-
-// XXX: Unfortunately, SAL annotations are known to not work with function pointers
-#define ORT_API2_STATUS(NAME, ...) \
- _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT
-
-// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT
-#define ORT_API_STATUS_IMPL(NAME, ...) \
- _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION
-
-#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input)
-
-// When passing in an allocator to any ORT function, be sure that the allocator object
-// is not destroyed until the last allocated object using it is freed.
-typedef struct OrtAllocator {
- uint32_t version; // Initialize to ORT_API_VERSION
- void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size);
- void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p);
- const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_);
-} OrtAllocator;
-
-typedef void(ORT_API_CALL* OrtLoggingFunction)(
- void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location,
- const char* message);
-
-// Set Graph optimization level.
-// Refer https://github.com/microsoft/onnxruntime/blob/master/docs/ONNX_Runtime_Graph_Optimizations.md
-// for in-depth undersrtanding of Graph Optimizations in ORT
-typedef enum GraphOptimizationLevel {
- ORT_DISABLE_ALL = 0,
- ORT_ENABLE_BASIC = 1,
- ORT_ENABLE_EXTENDED = 2,
- ORT_ENABLE_ALL = 99
-} GraphOptimizationLevel;
-
-typedef enum ExecutionMode {
- ORT_SEQUENTIAL = 0,
- ORT_PARALLEL = 1,
-} ExecutionMode;
-
-// Set the language projection, default is C, which means it will classify the language not in the list to C also.
-typedef enum OrtLanguageProjection {
- ORT_PROJECTION_C = 0, // default
- ORT_PROJECTION_CPLUSPLUS = 1,
- ORT_PROJECTION_CSHARP = 2,
- ORT_PROJECTION_PYTHON = 3,
- ORT_PROJECTION_JAVA = 4,
- ORT_PROJECTION_WINML = 5,
- ORT_PROJECTION_NODEJS = 6,
-} OrtLanguageProjection;
-
-struct OrtKernelInfo;
-typedef struct OrtKernelInfo OrtKernelInfo;
-struct OrtKernelContext;
-typedef struct OrtKernelContext OrtKernelContext;
-struct OrtCustomOp;
-typedef struct OrtCustomOp OrtCustomOp;
-
-typedef enum OrtAllocatorType {
- Invalid = -1,
- OrtDeviceAllocator = 0,
- OrtArenaAllocator = 1
-} OrtAllocatorType;
-
-/**
- * memory types for allocator, exec provider specific types should be extended in each provider
- * Whenever this struct is updated, please also update the MakeKey function in onnxruntime/core/framework/execution_provider.cc
-*/
-typedef enum OrtMemType {
- OrtMemTypeCPUInput = -2, // Any CPU memory used by non-CPU execution provider
- OrtMemTypeCPUOutput = -1, // CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED
- OrtMemTypeCPU = OrtMemTypeCPUOutput, // temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED
- OrtMemTypeDefault = 0, // the default allocator for execution provider
-} OrtMemType;
-
-typedef enum OrtCudnnConvAlgoSearch {
- EXHAUSTIVE, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx
- HEURISTIC, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7
- DEFAULT, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM
-} OrtCudnnConvAlgoSearch;
-
-/// <summary>
-/// Options for the CUDA provider that are passed to SessionOptionsAppendExecutionProvider_CUDA
-/// </summary>
-typedef struct OrtCUDAProviderOptions {
- int device_id; // cuda device with id=0 as default device.
- OrtCudnnConvAlgoSearch cudnn_conv_algo_search; // cudnn conv algo search option
- size_t cuda_mem_limit; // default cuda memory limitation to maximum finite value of size_t.
- int arena_extend_strategy; // default area extend strategy to KNextPowerOfTwo.
- int do_copy_in_default_stream;
-} OrtCUDAProviderOptions;
-
-/// <summary>
-/// Options for the OpenVINO provider that are passed to SessionOptionsAppendExecutionProvider_OpenVINO
-/// </summary>
-typedef struct OrtOpenVINOProviderOptions {
-#ifdef __cplusplus
- OrtOpenVINOProviderOptions() : device_type{}, enable_vpu_fast_compile{}, device_id{}, num_of_threads{} {}
-#endif
- const char* device_type; // CPU_FP32, GPU_FP32, GPU_FP16, MYRIAD_FP16, VAD-M_FP16 or VAD-F_FP32
- unsigned char enable_vpu_fast_compile; // 0 = false, nonzero = true
- const char* device_id;
- size_t num_of_threads; // 0 uses default number of threads
-} OrtOpenVINOProviderOptions;
-
-struct OrtApi;
-typedef struct OrtApi OrtApi;
-
-struct OrtApiBase {
- const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; // Pass in ORT_API_VERSION
- // nullptr will be returned if the version is unsupported, for example when using a runtime older than this header file
-
- const char*(ORT_API_CALL* GetVersionString)() NO_EXCEPTION;
-};
-typedef struct OrtApiBase OrtApiBase;
-
-ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION;
-
-struct OrtApi {
- /**
-* \param msg A null-terminated string. Its content will be copied into the newly created OrtStatus
-*/
- OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
-
- OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
-
- /**
- * \param status must not be NULL
- * \return The error message inside the `status`. Do not free the returned value.
- */
- const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
-
- /**
- * \param out Should be freed by `OrtReleaseEnv` after use
- */
- ORT_API2_STATUS(CreateEnv, OrtLoggingLevel logging_level, _In_ const char* logid, _Outptr_ OrtEnv** out);
-
- /**
- * \param out Should be freed by `OrtReleaseEnv` after use
- */
- ORT_API2_STATUS(CreateEnvWithCustomLogger, OrtLoggingFunction logging_function, _In_opt_ void* logger_param,
- OrtLoggingLevel logging_level, _In_ const char* logid, _Outptr_ OrtEnv** out);
-
- // Platform telemetry events are on by default since they are lightweight. You can manually turn them off.
- ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env);
- ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env);
-
- // TODO: document the path separator convention? '/' vs '\'
- // TODO: should specify the access characteristics of model_path. Is this read only during the
- // execution of CreateSession, or does the OrtSession retain a handle to the file/directory
- // and continue to access throughout the OrtSession lifetime?
- // What sort of access is needed to model_path : read or read/write?
- ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path,
- _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out);
-
- ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, _In_ const void* model_data, size_t model_data_length,
- _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out);
-
- ORT_API2_STATUS(Run, _Inout_ OrtSession* sess, _In_opt_ const OrtRunOptions* run_options,
- _In_reads_(input_len) const char* const* input_names,
- _In_reads_(input_len) const OrtValue* const* input, size_t input_len,
- _In_reads_(output_names_len) const char* const* output_names1, size_t output_names_len,
- _Inout_updates_all_(output_names_len) OrtValue** output);
-
- /**
- * \return A pointer of the newly created object. The pointer should be freed by OrtReleaseSessionOptions after use
- */
- ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options);
-
- // Set filepath to save optimized model after graph level transformations.
- ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options,
- _In_ const ORTCHAR_T* optimized_model_filepath);
-
- // create a copy of an existing OrtSessionOptions
- ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options,
- _Outptr_ OrtSessionOptions** out_options);
-
- // Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model
- // has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance.
- // See [docs/ONNX_Runtime_Perf_Tuning.md] for more details.
- ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode);
-
- // Enable profiling for this session.
- ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix);
- ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options);
-
- // Enable the memory pattern optimization.
- // The idea is if the input shapes are the same, we could trace the internal memory allocation
- // and generate a memory pattern for future request. So next time we could just do one allocation
- // with a big chunk for all the internal memory allocation.
- // Note: memory pattern optimization is only available when SequentialExecution enabled.
- ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options);
- ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options);
-
- // Enable the memory arena on CPU
- // Arena may pre-allocate memory for future usage.
- // set this option to false if you don't want it.
- ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options);
- ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options);
-
- // < logger id to use for session output
- ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid);
-
- // < applies to session load, initialization, etc
- ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level);
- ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level);
-
- ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options,
- GraphOptimizationLevel graph_optimization_level);
-
- // Sets the number of threads used to parallelize the execution within nodes
- // A value of 0 means ORT will pick a default
- // Note: If you've built ORT with OpenMP, this API has no effect on the number of threads used. In this case
- // use the OpenMP env variables to configure the number of intra op num threads.
- ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads);
-
- // Sets the number of threads used to parallelize the execution of the graph (across nodes)
- // If sequential execution is enabled this value is ignored
- // A value of 0 means ORT will pick a default
- ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads);
-
- /*
- Create a custom op domain. After all sessions using it are released, call OrtReleaseCustomOpDomain
- */
- ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out);
-
- /*
- * Add custom ops to the OrtCustomOpDomain
- * Note: The OrtCustomOp* pointer must remain valid until the OrtCustomOpDomain using it is released
- */
- ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op);
-
- /*
- * Add a custom op domain to the OrtSessionOptions
- * Note: The OrtCustomOpDomain* must not be deleted until the sessions using it are released
- */
- ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain);
-
- /*
- * Loads a DLL named 'library_path' and looks for this entry point:
- * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api);
- * It then passes in the provided session options to this function along with the api base.
- * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in
- * session options are destroyed, or if an error occurs and it is non null.
- */
- ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path,
- void** library_handle);
-
- /**
- * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these
- * functions to enable them in the session:
- * OrtSessionOptionsAppendExecutionProvider_CPU
- * OrtSessionOptionsAppendExecutionProvider_CUDA
- * OrtSessionOptionsAppendExecutionProvider_<remaining providers...>
- * The order they are called indicates the preference order as well. In other words call this method
- * on your most preferred execution provider first followed by the less preferred ones.
- * If none are called Ort will use its internal CPU execution provider.
- */
-
- ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* sess, _Out_ size_t* out);
- ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* sess, _Out_ size_t* out);
- ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* sess, _Out_ size_t* out);
-
- /**
- * \param out should be freed by OrtReleaseTypeInfo after use
- */
- ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* sess, size_t index, _Outptr_ OrtTypeInfo** type_info);
-
- /**
- * \param out should be freed by OrtReleaseTypeInfo after use
- */
- ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* sess, size_t index,
- _Outptr_ OrtTypeInfo** type_info);
-
- /**
- * \param out should be freed by OrtReleaseTypeInfo after use
- */
- ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* sess, size_t index,
- _Outptr_ OrtTypeInfo** type_info);
-
- /**
- * \param value is set to a null terminated string allocated using 'allocator'. The caller is responsible for freeing it.
- */
- ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* sess, size_t index, _Inout_ OrtAllocator* allocator,
- _Outptr_ char** value);
- ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* sess, size_t index, _Inout_ OrtAllocator* allocator,
- _Outptr_ char** value);
- ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* sess, size_t index,
- _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
-
- /**
- * \return A pointer to the newly created object. The pointer should be freed by OrtReleaseRunOptions after use
- */
- ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out);
-
- ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int value);
- ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int value);
- ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions*, _In_ const char* run_tag);
-
- ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, _Out_ int* out);
- ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* out);
- ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions*, _Out_ const char** out);
-
- // Set a flag so that ALL incomplete OrtRun calls that are using this instance of OrtRunOptions
- // will exit as soon as possible.
- ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options);
- // Unset the terminate flag to enable this OrtRunOptions instance being used in new OrtRun calls.
- ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options);
-
- /**
- * Create a tensor from an allocator. OrtReleaseValue will also release the buffer inside the output value
- * \param out Should be freed by calling OrtReleaseValue
- * \param type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx
- */
- ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len,
- ONNXTensorElementDataType type, _Outptr_ OrtValue** out);
-
- /**
- * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after.
- * p_data is owned by caller. OrtReleaseValue won't release p_data.
- * \param out Should be freed by calling OrtReleaseValue
- */
- ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data,
- size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type,
- _Outptr_ OrtValue** out);
-
- /**
- * \Sets *out to 1 iff an OrtValue is a tensor, 0 otherwise
- */
- ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out);
-
- // This function doesn't work with string tensor
- // this is a no-copy method whose pointer is only valid until the backing OrtValue is free'd.
- ORT_API2_STATUS(GetTensorMutableData, _Inout_ OrtValue* value, _Outptr_ void** out);
-
- /**
- * \param value A tensor created from OrtCreateTensor... function.
- * \param s each A string array. Each string in this array must be null terminated.
- * \param s_len length of s
- */
- ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len);
-
- /**
- * \param value A tensor created from OrtCreateTensor... function.
- * \param len total data length, not including the trailing '\0' chars.
- */
- ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len);
-
- /**
- * \param s string contents. Each string is NOT null-terminated.
- * \param value A tensor created from OrtCreateTensor... function.
- * \param s_len total data length, get it from OrtGetStringTensorDataLength
- */
- ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s,
- size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len);
-
- /**
- * Don't free the 'out' value
- */
- ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo*,
- _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out);
-
- /**
- * Return OnnxType from OrtTypeInfo
- */
- ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo*, _Out_ enum ONNXType* out);
-
- /**
- * The 'out' value should be released by calling OrtReleaseTensorTypeAndShapeInfo
- */
- ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out);
-
- ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo*, enum ONNXTensorElementDataType type);
-
- /**
- * \param info Created from CreateTensorTypeAndShapeInfo() function
- * \param dim_values An array with length of `dim_count`. Its elements can contain negative values.
- * \param dim_count length of dim_values
- */
- ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count);
-
- ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo*,
- _Out_ enum ONNXTensorElementDataType* out);
- ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out);
- ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values,
- size_t dim_values_length);
- ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info,
- _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length);
-
- /**
- * Return the number of elements specified by the tensor shape.
- * Return a negative value if unknown (i.e., any dimension is negative.)
- * e.g.
- * [] -> 1
- * [1,3,4] -> 12
- * [2,0,4] -> 0
- * [-1,3,4] -> -1
- */
- ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out);
-
- /**
- * \param out Should be freed by OrtReleaseTensorTypeAndShapeInfo after use
- */
- ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out);
-
- /**
- * Get the type information of an OrtValue
- * \param value
- * \param out The returned value should be freed by OrtReleaseTypeInfo after use
- */
- ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out);
-
- ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out);
-
- ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name1, enum OrtAllocatorType type, int id1,
- enum OrtMemType mem_type1, _Outptr_ OrtMemoryInfo** out);
-
- /**
- * Convenience function for special case of CreateMemoryInfo, for the CPU allocator. Uses name = "Cpu" and id = 0.
- */
- ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type1,
- _Outptr_ OrtMemoryInfo** out);
-
- /**
- * Test if two memory info are equal
- * \Sets 'out' to 0 if equal, -1 if not equal
- */
- ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out);
-
- /**
- * Do not free the returned value
- */
- ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out);
- ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out);
- ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out);
- ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out);
-
- ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ptr, size_t size, _Outptr_ void** out);
- ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ptr, void* p);
- ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ptr, _Outptr_ const struct OrtMemoryInfo** out);
-
- // The returned pointer doesn't have to be freed.
- // Always returns the same instance on every invocation.
- // Please note that this is a non-arena based allocator.
- ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out);
-
- // Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable
- // optimizations that can take advantage of fixed values (such as memory planning, etc)
- ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation,
- _In_ int64_t dim_value);
-
- /**
- * APIs to support non-tensor types - map and sequence.
- * Currently only the following types are supported
- * Note: the following types should be kept in sync with data_types.h
- * Map types
- * =========
- * std::map<std::string, std::string>
- * std::map<std::string, int64_t>
- * std::map<std::string, float>
- * std::map<std::string, double>
- * std::map<int64_t, std::string>
- * std::map<int64_t, int64_t>
- * std::map<int64_t, float>
- * std::map<int64_t, double>
- *
- * Sequence types
- * ==============
- * std::vector<std::string>
- * std::vector<int64_t>
- * std::vector<float>
- * std::vector<double>
- * std::vector<std::map<std::string, float>>
- * std::vector<std::map<int64_t, float>
- */
-
- /**
- * If input OrtValue represents a map, you need to retrieve the keys and values
- * separately. Use index=0 to retrieve keys and index=1 to retrieve values.
- * If input OrtValue represents a sequence, use index to retrieve the index'th element
- * of the sequence.
- */
- ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator,
- _Outptr_ OrtValue** out);
-
- /**
- * Returns 2 for type map and N for sequence where N is the number of elements
- * in the sequence.
- */
- ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out);
-
- /**
- * To construct a map, use num_values = 2 and 'in' should be an arrary of 2 OrtValues
- * representing keys and values.
- * To construct a sequence, use num_values = N where N is the number of the elements in the
- * sequence. 'in' should be an arrary of N OrtValues.
- * \value_type should be either map or sequence.
- */
- ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values,
- enum ONNXType value_type, _Outptr_ OrtValue** out);
-
- /**
- * Construct OrtValue that contains a value of non-standard type created for
- * experiments or while awaiting standardization. OrtValue in this case would contain
- * an internal representation of the Opaque type. Opaque types are distinguished between
- * each other by two strings 1) domain and 2) type name. The combination of the two
- * must be unique, so the type representation is properly identified internally. The combination
- * must be properly registered from within ORT at both compile/run time or by another API.
- *
- * To construct the OrtValue pass domain and type names, also a pointer to a data container
- * the type of which must be know to both ORT and the client program. That data container may or may
- * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for
- * verification purposes.
- *
- * \domain_name - domain name for the Opaque type, null terminated.
- * \type_name - type name for the Opaque type, null terminated.
- * \data_contianer - data to populate OrtValue
- * \data_container_size - sizeof() of the data container. Must match the sizeof() of the expected
- * data_container size internally.
- */
- ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name,
- _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out);
-
- /**
- * Fetch data from an OrtValue that contains a value of non-standard type created for
- * experiments or while awaiting standardization.
- * \domain_name - domain name for the Opaque type, null terminated.
- * \type_name - type name for the Opaque type, null terminated.
- * \data_contianer - data to populate OrtValue
- * \data_container_size - sizeof() of the data container. Must match the sizeof() of the expected
- * data_container size internally.
- */
-
- ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in,
- _Out_ void* data_container, size_t data_container_size);
-
- ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name,
- _Out_ float* out);
- ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name,
- _Out_ int64_t* out);
- ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out,
- _Inout_ size_t* size);
-
- ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out);
- ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out);
- ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index,
- _Out_ const OrtValue** out);
- ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index,
- _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out);
-
- ORT_CLASS_RELEASE(Env);
- ORT_CLASS_RELEASE(Status); // nullptr for Status* indicates success
- ORT_CLASS_RELEASE(MemoryInfo);
- ORT_CLASS_RELEASE(Session); //Don't call OrtReleaseSession from Dllmain (because session owns a thread pool)
- ORT_CLASS_RELEASE(Value);
- ORT_CLASS_RELEASE(RunOptions);
- ORT_CLASS_RELEASE(TypeInfo);
- ORT_CLASS_RELEASE(TensorTypeAndShapeInfo);
- ORT_CLASS_RELEASE(SessionOptions);
- ORT_CLASS_RELEASE(CustomOpDomain);
-
- // End of Version 1 - DO NOT MODIFY ABOVE (see above text for more information)
-
- // Version 2 - In development, feel free to add/remove/rearrange here
-
- /**
- * GetDenotationFromTypeInfo
- * This api augments OrtTypeInfo to return denotations on the type.
- * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor.
- */
- ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo*, _Out_ const char** const denotation,
- _Out_ size_t* len);
-
- // OrtTypeInfo Casting methods
-
- /**
- * CastTypeInfoToMapTypeInfo
- * This api augments OrtTypeInfo to return an OrtMapTypeInfo when the type is a map.
- * The OrtMapTypeInfo has additional information about the map's key type and value type.
- * This is used by WinML to support model reflection APIs.
- * This is used by WinML to support model reflection APIs.
- *
- * Don't free the 'out' value
- */
- ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info,
- _Outptr_result_maybenull_ const OrtMapTypeInfo** out);
-
- /**
- * CastTypeInfoToSequenceTypeInfo
- * This api augments OrtTypeInfo to return an OrtSequenceTypeInfo when the type is a sequence.
- * The OrtSequenceTypeInfo has additional information about the sequence's element type.
- * This is used by WinML to support model reflection APIs.
- *
- * Don't free the 'out' value
- */
- ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info,
- _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out);
-
- // OrtMapTypeInfo Accessors
-
- /**
- * GetMapKeyType
- * This api augments get the key type of a map. Key types are restricted to being scalar types and use ONNXTensorElementDataType.
- * This is used by WinML to support model reflection APIs.
- */
- ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out);
-
- /**
- * GetMapValueType
- * This api augments get the value type of a map.
- */
- ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info);
-
- // OrtSequenceTypeInfo Accessors
-
- /**
- * GetSequenceElementType
- * This api augments get the element type of a sequence.
- * This is used by WinML to support model reflection APIs.
- */
- ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info,
- _Outptr_ OrtTypeInfo** type_info);
-
- ORT_CLASS_RELEASE(MapTypeInfo);
- ORT_CLASS_RELEASE(SequenceTypeInfo);
-
- /**
- * \param out is set to a null terminated string allocated using 'allocator'. The caller is responsible for freeing it.
- * Profiling is turned ON automatically if enabled for the particular session by invoking EnableProfiling()
- * on the SessionOptions instance used to create the session.
- */
- ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* sess, _Inout_ OrtAllocator* allocator, _Outptr_ char** out);
-
- /**
- * \param out is a pointer to the newly created object. The pointer should be freed by calling ReleaseModelMetadata after use.
- */
- ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* sess, _Outptr_ OrtModelMetadata** out);
-
- /**
- * \param value is set to a null terminated string allocated using 'allocator'. The caller is responsible for freeing it.
- */
- ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
- ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
- ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator,
- _Outptr_ char** value);
- ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
- /**
- * \param value is set to a null terminated string allocated using 'allocator'. The caller is responsible for freeing it.
- * 'value' will be a nullptr if the given key is not found in the custom metadata map.
- */
- ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value);
-
- ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value);
-
- ORT_CLASS_RELEASE(ModelMetadata);
-
- /*
- * Creates an environment with global threadpools that will be shared across sessions.
- * Use this in conjunction with DisablePerSessionThreads API or else the session will use
- * its own thread pools.
- */
- ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel logging_level, _In_ const char* logid,
- _In_ const OrtThreadingOptions* t_options, _Outptr_ OrtEnv** out);
-
- /*
- * Calling this API will make the session use the global threadpools shared across sessions.
- * This API should be used in conjunction with CreateEnvWithGlobalThreadPools API.
- */
- ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options);
-
- ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out);
-
- ORT_CLASS_RELEASE(ThreadingOptions);
-
- /**
- * \param num_keys contains the number of keys in the custom metadata map
- * \param keys is an array of null terminated strings (array count = num_keys) allocated using 'allocator'.
- * The caller is responsible for freeing each string and the pointer array.
- * 'keys' will be a nullptr if custom metadata map is empty.
- */
- ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys);
-
- // Override symbolic dimensions (by specific name strings) with actual values
- // if known at session initialization time to enable optimizations that can
- // take advantage of fixed values (such as memory planning, etc)
- ORT_API2_STATUS(AddFreeDimensionOverrideByName,
- _Inout_ OrtSessionOptions* options, _In_ const char* dim_name,
- _In_ int64_t dim_value);
-
- /**
- * \param out_ptr will hold a pointer to the array of char *
- * representing available providers.
- * \param provider_length is a pointer to an int variable where
- * the number of available providers will be added.
- * The caller is responsible for freeing each char * and the pointer
- * array by calling ReleaseAvailableProviders().
- */
- ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr,
- _In_ int* provider_length);
-
- /**
- * \param ptr is the pointer to an array of available providers you
- * get after calling GetAvailableProviders().
- * \param providers_length is the number of available providers.
- */
- ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr,
- _In_ int providers_length);
-
- /**
- * \param value - A tensor created from OrtCreateTensor... function.
- * \param index - index of string tensor element, length of element at index will be returned.
- * \param out - number of UTF-8 bytes that the string contains
- */
- ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out);
-
- /**
- * \param s string element contents in UTF-8 encoding. The string is NOT null-terminated.
- * \param value A tensor created from OrtCreateTensor... function.
- * \param s_len element length, get it from OrtGetStringTensorElementLength.
- * \param index offset of element of tensor to return.
- */
- ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s);
-
- /**
- * \param value - A tensor created from OrtCreateTensor... function.
- * \param s - A null terminated UTF-8 encoded string.
- * \param index - index of string tensor element to fill
- */
- ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index);
-
- /**
- * Set a single session configuration entry as a pair of strings
- * If a configuration with same key exists, this will overwrite the configuration with the given config_value
- * \param config_key A null terminated string representation of the config key
- * \param config_value A null terminated string representation of the config value
- * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h
- */
- ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options,
- _In_z_ const char* config_key, _In_z_ const char* config_value);
-
- /**
- * \param sess valid OrtSession instance
- * \param mem_info - valid OrtMemoryInfo instance
- * \param - out a ptr to a new instance of OrtAllocator according to the spec within mem_info
- * if successful
- * \return OrtStatus or nullptr if successful
- */
- ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* sess, _In_ const OrtMemoryInfo* mem_info,
- _Outptr_ OrtAllocator** out);
-
- // Release instance of OrtAllocator obtained from CreateAllocator API
- ORT_CLASS_RELEASE(Allocator);
-
- ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* sess, _In_opt_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr);
-
- // Creates an IoBinding instance that allows one to bind pre-allocated OrtValues
- // to input names. Thus if you want to use a raw on device buffer as input or output
- // you can avoid extra copy during runtime.
- ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* sess, _Outptr_ OrtIoBinding** out);
-
- // Release instance or OrtIoBinding obtained from CreateIoBinding API
- ORT_CLASS_RELEASE(IoBinding);
-
- /**
- * The function will bind the OrtValue to a specified input name.
- * The OrtValue must be a Tensor. ORT would use that value in place of input for the specified name.
- * \param binding_ptr - an instance of OrtIoBinding created by CreateIoBinding()
- * \param name - name for the model input
- * \param val_ptr - OrtValue of Tensor type.
- * \return OrtStatus instance on error which the caller is responsible to free or nullptr on success
- */
- ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr);
-
- /**
- * The function will bind the OrtValue to the specified output name.
- * The OrtValue must be a Tensor. ORT would use that value in place of output for the specified name.
- *
- * \param binding_ptr - an instance of OrtIoBinding created by CreateIoBinding()
- * \param name - name for the model output
- * \param val_ptr - OrtValue of Tensor type.
- * \return OrtStatus instance on error which the caller is responsible to free or nullptr on success
- */
- ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr);
-
- /**
- * The function will bind the OrtValue to a device which specification is contained within OrtMemoryInfo
- * You can either create an instance of OrtMemoryInfo with a device id or obtain one from the allocator that you are created/using
- * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocated and bind a chunk of
- * memory within OrtValue ahead of time.
- *
- * \param binding_ptr - an instance of OrtIoBinding created by CreateIoBinding()
- * \param name - name for the model output
- * \param mem_info_ptr - OrtMemoryInfo
- * \return OrtStatus instance on error which the caller is responsible to free or nullptr on success
- */
- ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* val_ptr);
-
- /**
- * The function returns the names of the outputs in the order they were bound. This is useful after running the model
- * with bound outputs because the returned names are in order in which output OrtValues are returned. This API is optional
- * to use. If you knew the order of outputs and its names you used for binding you would not need to use this API.
- *
- * \param binding_ptr - a ptr to an instance of OrtIoBinding created obtained from CreateIoBinding()
- * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions()
- * the specified allocator will be used to allocate continuous buffers for output strings and lengths.
- * \param buffer - pointer to a continuous buffer of non-zero terminated UTF-8 encoded strings. The number of strings stored is returned count parameter.
- * this buffer will be allocated with the specified allocator and must be freed after it is no longer needed.
- * \param lengths - a pointer to a continuous buffer of size_t lengths of strings returned in the buffer. The number of items is returned
- * in the count. This buffer is allocated with the specified allocator and must be freed after it is no longer needed.
- * \para count - is the number of strings returned. If the instance of OrtIoBiding has no bound outputs, zero is returned,
- * no memory allocation is performed and buffer and lengths are nullptr on return.
- */
- ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator,
- _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count);
-
- /**
- * The function returns an array of pointers to individually allocated OrtValues that contain results of a model execution with RunWithBinding()
- * The array contains the same number of OrtValues and they are in the same order as they were bound with BindOutput()
- * or BindOutputToDevice().
- * The returned OrtValues must be individually released after they are no longer needed.
- * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after
- * all the OrtValues contained therein are individually released.
- *
- * \param binding_ptr - instance of OrtIoBidning
- * \param allocator - instance of allocator to allocate output array
- * \param output - pointer to the allocated buffer. Returns nullptr if no outputs.
- * \param output_count - pointer to the number of OrtValues returned. Zero if no outputs.
- */
- ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator,
- _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count);
-
- /** Clears any previously specified bindings for inputs/outputs
- */
- void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
- void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
-
- /**
- * Provides element-level access into a tensor.
- * \param location_values a pointer to an array of index values that specify an element's location in the tensor data blob
- * \param location_values_count length of location_values
- * \param out a pointer to the element specified by location_values
- * e.g.
- * Given a tensor with overall shape [3,224,224], an element at
- * location [2,150,128] can be accessed directly.
- *
- * This function only works for numeric tensors.
- * This is a no-copy method whose pointer is only valid until the backing OrtValue is free'd.
- */
- ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out);
-
- /**
- * Creates an allocator instance and registers it with the env to enable
- * sharing between multiple sessions that use the same env instance.
- * Lifetime of the created allocator will be valid for the duration of the environment.
- * Returns an error if an allocator with the same OrtMemoryInfo is already registered.
- * \param mem_info must be non-null.
- * \param arena_cfg if nullptr defaults will be used.
- * See docs/C_API.md for details.
- */
- ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info,
- _In_ const OrtArenaCfg* arena_cfg);
-
- /**
- * Set the language projection for collecting telemetry data when Env is created
- * \param projection the source projected language.
- */
- ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection);
-
- /**
- * On some platforms, this timer may not be as precise as nanoseconds
- * For instance, on Windows and MacOS, the precision will be ~100ns
- * \param out is set to the nanoseconds of profiling's start time
- */
- ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* sess, _Outptr_ uint64_t* out);
-
- /**
- * Use this API to configure the global thread pool options to be used in the call to CreateEnvWithGlobalThreadPools.
- * A value of 0 means ORT will pick the default.
- * A value of 1 means the invoking thread will be used; no threads will be created in the thread pool.
- */
- ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads);
- ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads);
-
- /**
- * Use this API to configure the global thread pool options to be used in the call to CreateEnvWithGlobalThreadPools.
- * Allow spinning of thread pools when their queues are empty. This API will set the value for both
- * inter_op and intra_op threadpools.
- * \param allow_spinning valid values are 1 and 0.
- * 1: threadpool will spin to wait for queue to become non-empty, 0: it won't spin.
- * Prefer a value of 0 if your CPU usage is very high.
- */
- ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning);
-
- /**
- * Add a pre-allocated initializer to a session. If a model contains an initializer with a name
- * that is same as the name passed to this API call, ORT will use this initializer instance
- * instead of deserializing one from the model file. This is useful when you want to share
- * the same initializer across sessions.
- * \param name name of the initializer
- * \param val OrtValue containing the initializer. Lifetime of 'val' and the underlying initializer buffer must be
- * managed by the user (created using the CreateTensorWithDataAsOrtValue API) and it must outlive the session object
- * to which it is added.
- */
- ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name,
- _In_ const OrtValue* val);
-
- /**
- * Creates a custom environment with global threadpools and logger that will be shared across sessions.
- * Use this in conjunction with DisablePerSessionThreads API or else the session will use
- * its own thread pools.
- *
- * \param out should be freed by `OrtReleaseEnv` after use
- */
- ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel logging_level,
- _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out);
-
- /**
- * Append CUDA execution provider to the session options
- * If CUDA is not available (due to a non cuda enabled build), this function will return failure.
- */
- ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA,
- _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options);
-
- /**
- * Append OpenVINO execution provider to the session options
- * If OpenVINO is not available (due to the OpenVINO provider shared library or its dependencies not being installed), this function will fail.
- */
- ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO,
- _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options);
-
- /**
- * Use this API to configure the global thread pool options to be used in the call to CreateEnvWithGlobalThreadPools.
- * When this API is called, flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool.
- * Note that an alternative way not using this option at runtime is to train and export a model without denormals
- * and that's recommended because turning this option on may hurt model accuracy.
- */
- ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options);
-
- /**
- * Use this API to create the configuration of an arena that can eventually be used to define
- * an arena based allocator's behavior
- * \param max_mem - use 0 to allow ORT to choose the default
- * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested
- * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default
- * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default
- * \param out - a pointer to an OrtArenaCfg instance
- * \return a nullptr in case of success or a pointer to an OrtStatus instance in case of failure
- * See docs/C_API.md for details on what the following parameters mean and how to choose these values
- */
- ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes,
- int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out);
-
- ORT_CLASS_RELEASE(ArenaCfg);
-
- /**
- * Use this API to obtain the description of the graph present in the model
- * (doc_string field of the GraphProto message within the ModelProto message).
- * If it doesn't exist, an empty string will be returned.
- * \param model_metadata - an instance of OrtModelMetadata
- * \param allocator - allocator used to allocate the string that will be returned back
- * \param value - is set to a null terminated string allocated using 'allocator'.
- The caller is responsible for freeing it.
- */
- ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata,
- _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
-};
-
-/*
- * Steps to use a custom op:
- * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops
- * 2 Create an OrtCustomOp structure for each op and add them to the domain
- * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options
-*/
-#define OrtCustomOpApi OrtApi
-
-/*
- * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by
- * the implementor of the custom op.
-*/
-struct OrtCustomOp {
- uint32_t version; // Initialize to ORT_API_VERSION
-
- // This callback creates the kernel, which is a user defined parameter that is passed to the Kernel* callbacks below.
- void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api,
- _In_ const OrtKernelInfo* info);
-
- // Returns the name of the op
- const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op);
-
- // Returns the type of the execution provider, return nullptr to use CPU execution provider
- const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op);
-
- // Returns the count and types of the input & output tensors
- ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
- size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op);
- ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
- size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op);
-
- // Op kernel callbacks
- void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context);
- void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel);
-};
-
-/*
- * END EXPERIMENTAL
-*/
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/include/onnxruntime/core/session/onnxruntime_cxx_api.h b/include/onnxruntime/core/session/onnxruntime_cxx_api.h
deleted file mode 100755
index d5aa79a..0000000
--- a/include/onnxruntime/core/session/onnxruntime_cxx_api.h
+++ /dev/null
@@ -1,633 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-// Summary: The Ort C++ API is a header only wrapper around the Ort C API.
-//
-// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors
-// and automatically releasing resources in the destructors.
-//
-// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers.
-// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};).
-//
-// Only move assignment between objects is allowed, there are no copy constructors. Some objects have explicit 'Clone'
-// methods for this purpose.
-
-#pragma once
-#include "onnxruntime_c_api.h"
-#include <cstddef>
-#include <array>
-#include <memory>
-#include <stdexcept>
-#include <string>
-#include <vector>
-#include <utility>
-#include <type_traits>
-
-#ifdef ORT_NO_EXCEPTIONS
-#include <iostream>
-#endif
-
-namespace Ort {
-
-// All C++ methods that can fail will throw an exception of this type
-struct Exception : std::exception {
- Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {}
-
- OrtErrorCode GetOrtErrorCode() const { return code_; }
- const char* what() const noexcept override { return message_.c_str(); }
-
- private:
- std::string message_;
- OrtErrorCode code_;
-};
-
-#ifdef ORT_NO_EXCEPTIONS
-#define ORT_CXX_API_THROW(string, code) \
- do { \
- std::cerr << Ort::Exception(string, code) \
- .what() \
- << std::endl; \
- abort(); \
- } while (false)
-#else
-#define ORT_CXX_API_THROW(string, code) \
- throw Ort::Exception(string, code)
-#endif
-
-// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, it's in a template so that we can define a global variable in a header and make
-// it transparent to the users of the API.
-template <typename T>
-struct Global {
- static const OrtApi* api_;
-};
-
-// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it.
-
-template <typename T>
-#ifdef ORT_API_MANUAL_INIT
-const OrtApi* Global<T>::api_{};
-inline void InitApi() { Global<void>::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); }
-#else
-const OrtApi* Global<T>::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION);
-#endif
-
-// This returns a reference to the OrtApi interface in use, in case someone wants to use the C API functions
-inline const OrtApi& GetApi() { return *Global<void>::api_; }
-
-// This is a C++ wrapper for GetAvailableProviders() C API and returns
-// a vector of strings representing the available execution providers.
-std::vector<std::string> GetAvailableProviders();
-
-// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type
-// This can't be done in the C API since C doesn't have function overloading.
-#define ORT_DEFINE_RELEASE(NAME) \
- inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); }
-
-ORT_DEFINE_RELEASE(Allocator);
-ORT_DEFINE_RELEASE(MemoryInfo);
-ORT_DEFINE_RELEASE(CustomOpDomain);
-ORT_DEFINE_RELEASE(Env);
-ORT_DEFINE_RELEASE(RunOptions);
-ORT_DEFINE_RELEASE(Session);
-ORT_DEFINE_RELEASE(SessionOptions);
-ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo);
-ORT_DEFINE_RELEASE(SequenceTypeInfo);
-ORT_DEFINE_RELEASE(MapTypeInfo);
-ORT_DEFINE_RELEASE(TypeInfo);
-ORT_DEFINE_RELEASE(Value);
-ORT_DEFINE_RELEASE(ModelMetadata);
-ORT_DEFINE_RELEASE(ThreadingOptions);
-ORT_DEFINE_RELEASE(IoBinding);
-ORT_DEFINE_RELEASE(ArenaCfg);
-
-/*! \class Ort::Float16_t
- * \brief it is a structure that represents float16 data.
- * \details It is necessary for type dispatching to make use of C++ API
- * The type is implicitly convertible to/from uint16_t.
- * The size of the structure should align with uint16_t and one can freely cast
- * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data.
- *
- * Generally, you can feed any of your types as float16/blfoat16 data to create a tensor
- * on top of it, providing it can form a continuous buffer with 16-bit elements with no padding.
- * And you can also feed a array of uint16_t elements directly. For example,
- *
- * \code{.unparsed}
- * uint16_t values[] = { 15360, 16384, 16896, 17408, 17664};
- * constexpr size_t values_length = sizeof(values) / sizeof(values[0]);
- * std::vector<int64_t> dims = {values_length}; // one dimensional example
- * Ort::MemoryInfo info("Cpu", OrtDeviceAllocator, 0, OrtMemTypeDefault);
- * // Note we are passing bytes count in this api, not number of elements -> sizeof(values)
- * auto float16_tensor = Ort::Value::CreateTensor(info, values, sizeof(values),
- * dims.data(), dims.size(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16);
- * \endcode
- *
- * Here is another example, a little bit more elaborate. Let's assume that you use your own float16 type and you want to use
- * a templated version of the API above so the type is automatically set based on your type. You will need to supply an extra
- * template specialization.
- *
- * \code{.unparsed}
- * namespace yours { struct half {}; } // assume this is your type, define this:
- * namespace Ort {
- * template<>
- * struct TypeToTensorType<yours::half> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };
- * } //namespace Ort
- *
- * std::vector<yours::half> values;
- * std::vector<int64_t> dims = {values.size()}; // one dimensional example
- * Ort::MemoryInfo info("Cpu", OrtDeviceAllocator, 0, OrtMemTypeDefault);
- * // Here we are passing element count -> values.size()
- * auto float16_tensor = Ort::Value::CreateTensor<yours::half>(info, values.data(), values.size(), dims.data(), dims.size());
- *
- * \endcode
- */
-struct Float16_t {
- uint16_t value;
- constexpr Float16_t() noexcept : value(0) {}
- constexpr Float16_t(uint16_t v) noexcept : value(v) {}
- constexpr operator uint16_t() const noexcept { return value; }
- constexpr bool operator==(const Float16_t& rhs) const noexcept { return value == rhs.value; };
- constexpr bool operator!=(const Float16_t& rhs) const noexcept { return value != rhs.value; };
-};
-
-static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match");
-
-/*! \class Ort::BFloat16_t
- * \brief is a structure that represents bfloat16 data.
- * \details It is necessary for type dispatching to make use of C++ API
- * The type is implicitly convertible to/from uint16_t.
- * The size of the structure should align with uint16_t and one can freely cast
- * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data.
- *
- * See also code examples for Float16_t above.
- */
-struct BFloat16_t {
- uint16_t value;
- constexpr BFloat16_t() noexcept : value(0) {}
- constexpr BFloat16_t(uint16_t v) noexcept : value(v) {}
- constexpr operator uint16_t() const noexcept { return value; }
- constexpr bool operator==(const BFloat16_t& rhs) const noexcept { return value == rhs.value; };
- constexpr bool operator!=(const BFloat16_t& rhs) const noexcept { return value != rhs.value; };
-};
-
-static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match");
-
-// This is used internally by the C++ API. This is the common base class used by the wrapper objects.
-template <typename T>
-struct Base {
- using contained_type = T;
-
- Base() = default;
- Base(T* p) : p_{p} {
- if (!p)
- ORT_CXX_API_THROW("Allocation failure", ORT_FAIL);
- }
- ~Base() { OrtRelease(p_); }
-
- operator T*() { return p_; }
- operator const T*() const { return p_; }
-
- T* release() {
- T* p = p_;
- p_ = nullptr;
- return p;
- }
-
- protected:
- Base(const Base&) = delete;
- Base& operator=(const Base&) = delete;
- Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; }
- void operator=(Base&& v) noexcept {
- OrtRelease(p_);
- p_ = v.p_;
- v.p_ = nullptr;
- }
-
- T* p_{};
-
- template <typename>
- friend struct Unowned; // This friend line is needed to keep the centos C++ compiler from giving an error
-};
-
-template <typename T>
-struct Base<const T> {
- using contained_type = const T;
-
- Base() = default;
- Base(const T* p) : p_{p} {
- if (!p)
- ORT_CXX_API_THROW("Invalid instance ptr", ORT_INVALID_ARGUMENT);
- }
- ~Base() = default;
-
- operator const T*() const { return p_; }
-
- protected:
- Base(const Base&) = delete;
- Base& operator=(const Base&) = delete;
- Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; }
- void operator=(Base&& v) noexcept {
- p_ = v.p_;
- v.p_ = nullptr;
- }
-
- const T* p_{};
-};
-
-template <typename T>
-struct Unowned : T {
- Unowned(decltype(T::p_) p) : T{p} {}
- Unowned(Unowned&& v) : T{v.p_} {}
- ~Unowned() { this->release(); }
-};
-
-struct AllocatorWithDefaultOptions;
-struct MemoryInfo;
-struct Env;
-struct TypeInfo;
-struct Value;
-struct ModelMetadata;
-
-struct Env : Base<OrtEnv> {
- Env(std::nullptr_t) {}
- Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = "");
- Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = "");
- Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param);
- Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param,
- OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = "");
- explicit Env(OrtEnv* p) : Base<OrtEnv>{p} {}
-
- Env& EnableTelemetryEvents();
- Env& DisableTelemetryEvents();
-
- Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg);
-
- static const OrtApi* s_api;
-};
-
-struct CustomOpDomain : Base<OrtCustomOpDomain> {
- explicit CustomOpDomain(std::nullptr_t) {}
- explicit CustomOpDomain(const char* domain);
-
- void Add(OrtCustomOp* op);
-};
-
-struct RunOptions : Base<OrtRunOptions> {
- RunOptions(std::nullptr_t) {}
- RunOptions();
-
- RunOptions& SetRunLogVerbosityLevel(int);
- int GetRunLogVerbosityLevel() const;
-
- RunOptions& SetRunLogSeverityLevel(int);
- int GetRunLogSeverityLevel() const;
-
- RunOptions& SetRunTag(const char* run_tag);
- const char* GetRunTag() const;
-
- // terminate ALL currently executing Session::Run calls that were made using this RunOptions instance
- RunOptions& SetTerminate();
- // unset the terminate flag so this RunOptions instance can be used in a new Session::Run call
- RunOptions& UnsetTerminate();
-};
-
-struct SessionOptions : Base<OrtSessionOptions> {
- explicit SessionOptions(std::nullptr_t) {}
- SessionOptions();
- explicit SessionOptions(OrtSessionOptions* p) : Base<OrtSessionOptions>{p} {}
-
- SessionOptions Clone() const;
-
- SessionOptions& SetIntraOpNumThreads(int intra_op_num_threads);
- SessionOptions& SetInterOpNumThreads(int inter_op_num_threads);
- SessionOptions& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level);
-
- SessionOptions& EnableCpuMemArena();
- SessionOptions& DisableCpuMemArena();
-
- SessionOptions& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file);
-
- SessionOptions& EnableProfiling(const ORTCHAR_T* profile_file_prefix);
- SessionOptions& DisableProfiling();
-
- SessionOptions& EnableMemPattern();
- SessionOptions& DisableMemPattern();
-
- SessionOptions& SetExecutionMode(ExecutionMode execution_mode);
-
- SessionOptions& SetLogId(const char* logid);
- SessionOptions& SetLogSeverityLevel(int level);
-
- SessionOptions& Add(OrtCustomOpDomain* custom_op_domain);
-
- SessionOptions& DisablePerSessionThreads();
-
- SessionOptions& AddConfigEntry(const char* config_key, const char* config_value);
- SessionOptions& AddInitializer(const char* name, const OrtValue* ort_val);
-
- SessionOptions& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options);
- SessionOptions& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options);
-};
-
-struct ModelMetadata : Base<OrtModelMetadata> {
- explicit ModelMetadata(std::nullptr_t) {}
- explicit ModelMetadata(OrtModelMetadata* p) : Base<OrtModelMetadata>{p} {}
-
- char* GetProducerName(OrtAllocator* allocator) const;
- char* GetGraphName(OrtAllocator* allocator) const;
- char* GetDomain(OrtAllocator* allocator) const;
- char* GetDescription(OrtAllocator* allocator) const;
- char* GetGraphDescription(OrtAllocator* allocator) const;
- char** GetCustomMetadataMapKeys(OrtAllocator* allocator, _Out_ int64_t& num_keys) const;
- char* LookupCustomMetadataMap(const char* key, OrtAllocator* allocator) const;
- int64_t GetVersion() const;
-};
-
-struct Session : Base<OrtSession> {
- explicit Session(std::nullptr_t) {}
- Session(Env& env, const ORTCHAR_T* model_path, const SessionOptions& options);
- Session(Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options);
-
- // Run that will allocate the output values
- std::vector<Value> Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
- const char* const* output_names, size_t output_count);
- // Run for when there is a list of preallocated outputs
- void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
- const char* const* output_names, Value* output_values, size_t output_count);
-
- void Run(const RunOptions& run_options, const struct IoBinding&);
-
- size_t GetInputCount() const;
- size_t GetOutputCount() const;
- size_t GetOverridableInitializerCount() const;
-
- char* GetInputName(size_t index, OrtAllocator* allocator) const;
- char* GetOutputName(size_t index, OrtAllocator* allocator) const;
- char* GetOverridableInitializerName(size_t index, OrtAllocator* allocator) const;
- char* EndProfiling(OrtAllocator* allocator) const;
- uint64_t GetProfilingStartTimeNs() const;
- ModelMetadata GetModelMetadata() const;
-
- TypeInfo GetInputTypeInfo(size_t index) const;
- TypeInfo GetOutputTypeInfo(size_t index) const;
- TypeInfo GetOverridableInitializerTypeInfo(size_t index) const;
-};
-
-struct TensorTypeAndShapeInfo : Base<OrtTensorTypeAndShapeInfo> {
- explicit TensorTypeAndShapeInfo(std::nullptr_t) {}
- explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : Base<OrtTensorTypeAndShapeInfo>{p} {}
-
- ONNXTensorElementDataType GetElementType() const;
- size_t GetElementCount() const;
-
- size_t GetDimensionsCount() const;
- void GetDimensions(int64_t* values, size_t values_count) const;
- void GetSymbolicDimensions(const char** values, size_t values_count) const;
-
- std::vector<int64_t> GetShape() const;
-};
-
-struct SequenceTypeInfo : Base<OrtSequenceTypeInfo> {
- explicit SequenceTypeInfo(std::nullptr_t) {}
- explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : Base<OrtSequenceTypeInfo>{p} {}
-
- TypeInfo GetSequenceElementType() const;
-};
-
-struct MapTypeInfo : Base<OrtMapTypeInfo> {
- explicit MapTypeInfo(std::nullptr_t) {}
- explicit MapTypeInfo(OrtMapTypeInfo* p) : Base<OrtMapTypeInfo>{p} {}
-
- ONNXTensorElementDataType GetMapKeyType() const;
- TypeInfo GetMapValueType() const;
-};
-
-struct TypeInfo : Base<OrtTypeInfo> {
- explicit TypeInfo(std::nullptr_t) {}
- explicit TypeInfo(OrtTypeInfo* p) : Base<OrtTypeInfo>{p} {}
-
- Unowned<TensorTypeAndShapeInfo> GetTensorTypeAndShapeInfo() const;
- Unowned<SequenceTypeInfo> GetSequenceTypeInfo() const;
- Unowned<MapTypeInfo> GetMapTypeInfo() const;
-
- ONNXType GetONNXType() const;
-};
-
-struct Value : Base<OrtValue> {
- template <typename T>
- static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len);
- static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, const int64_t* shape, size_t shape_len,
- ONNXTensorElementDataType type);
- template <typename T>
- static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len);
- static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type);
-
- static Value CreateMap(Value& keys, Value& values);
- static Value CreateSequence(std::vector<Value>& values);
-
- template <typename T>
- static Value CreateOpaque(const char* domain, const char* type_name, const T&);
-
- template <typename T>
- void GetOpaqueData(const char* domain, const char* type_name, T&) const;
-
- explicit Value(std::nullptr_t) {}
- explicit Value(OrtValue* p) : Base<OrtValue>{p} {}
- Value(Value&&) = default;
- Value& operator=(Value&&) = default;
-
- bool IsTensor() const;
- size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements
- Value GetValue(int index, OrtAllocator* allocator) const;
-
- size_t GetStringTensorDataLength() const;
- void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const;
-
- template <typename T>
- T* GetTensorMutableData();
-
- template <typename T>
- const T* GetTensorData() const;
-
- template <typename T>
- T& At(const std::vector<int64_t>& location);
-
- TypeInfo GetTypeInfo() const;
- TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const;
-
- size_t GetStringTensorElementLength(size_t element_index) const;
- void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const;
-
- void FillStringTensor(const char* const* s, size_t s_len);
- void FillStringTensorElement(const char* s, size_t index);
-};
-
-// Represents native memory allocation
-struct MemoryAllocation {
- MemoryAllocation(OrtAllocator* allocator, void* p, size_t size);
- ~MemoryAllocation();
- MemoryAllocation(const MemoryAllocation&) = delete;
- MemoryAllocation& operator=(const MemoryAllocation&) = delete;
- MemoryAllocation(MemoryAllocation&&);
- MemoryAllocation& operator=(MemoryAllocation&&);
-
- void* get() { return p_; }
- size_t size() const { return size_; }
-
- private:
- OrtAllocator* allocator_;
- void* p_;
- size_t size_;
-};
-
-struct AllocatorWithDefaultOptions {
- AllocatorWithDefaultOptions();
-
- operator OrtAllocator*() { return p_; }
- operator const OrtAllocator*() const { return p_; }
-
- void* Alloc(size_t size);
- // The return value will own the allocation
- MemoryAllocation GetAllocation(size_t size);
- void Free(void* p);
-
- const OrtMemoryInfo* GetInfo() const;
-
- private:
- OrtAllocator* p_{};
-};
-
-template <typename B>
-struct BaseMemoryInfo : B {
- BaseMemoryInfo() = default;
- explicit BaseMemoryInfo(typename B::contained_type* p) : B(p) {}
- ~BaseMemoryInfo() = default;
- BaseMemoryInfo(BaseMemoryInfo&&) = default;
- BaseMemoryInfo& operator=(BaseMemoryInfo&&) = default;
-
- std::string GetAllocatorName() const;
- OrtAllocatorType GetAllocatorType() const;
- int GetDeviceId() const;
- OrtMemType GetMemoryType() const;
- template <typename U>
- bool operator==(const BaseMemoryInfo<U>& o) const;
-};
-
-struct UnownedMemoryInfo : BaseMemoryInfo<Base<const OrtMemoryInfo> > {
- explicit UnownedMemoryInfo(std::nullptr_t) {}
- explicit UnownedMemoryInfo(const OrtMemoryInfo* p) : BaseMemoryInfo(p) {}
-};
-
-struct MemoryInfo : BaseMemoryInfo<Base<OrtMemoryInfo> > {
- static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1);
-
- explicit MemoryInfo(std::nullptr_t) {}
- explicit MemoryInfo(OrtMemoryInfo* p) : BaseMemoryInfo(p) {}
- MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type);
-};
-
-struct Allocator : public Base<OrtAllocator> {
- Allocator(const Session& session, const MemoryInfo&);
-
- void* Alloc(size_t size) const;
- // The return value will own the allocation
- MemoryAllocation GetAllocation(size_t size);
- void Free(void* p) const;
- UnownedMemoryInfo GetInfo() const;
-};
-
-struct IoBinding : public Base<OrtIoBinding> {
- private:
- std::vector<std::string> GetOutputNamesHelper(OrtAllocator*) const;
- std::vector<Value> GetOutputValuesHelper(OrtAllocator*) const;
-
- public:
- explicit IoBinding(Session& session);
- void BindInput(const char* name, const Value&);
- void BindOutput(const char* name, const Value&);
- void BindOutput(const char* name, const MemoryInfo&);
- std::vector<std::string> GetOutputNames() const;
- std::vector<std::string> GetOutputNames(Allocator&) const;
- std::vector<Value> GetOutputValues() const;
- std::vector<Value> GetOutputValues(Allocator&) const;
- void ClearBoundInputs();
- void ClearBoundOutputs();
-};
-
-/*! \struct Ort::ArenaCfg
- * \brief it is a structure that represents the configuration of an arena based allocator
- * \details Please see docs/C_API.md for details
- */
-struct ArenaCfg : Base<OrtArenaCfg> {
- explicit ArenaCfg(std::nullptr_t) {}
- /**
- * \param max_mem - use 0 to allow ORT to choose the default
- * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested
- * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default
- * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default
- * \return an instance of ArenaCfg
- * See docs/C_API.md for details on what the following parameters mean and how to choose these values
- */
- ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk);
-};
-
-//
-// Custom OPs (only needed to implement custom OPs)
-//
-
-struct CustomOpApi {
- CustomOpApi(const OrtApi& api) : api_(api) {}
-
- template <typename T> // T is only implemented for float, int64_t, and string
- T KernelInfoGetAttribute(_In_ const OrtKernelInfo* info, _In_ const char* name);
-
- OrtTensorTypeAndShapeInfo* GetTensorTypeAndShape(_In_ const OrtValue* value);
- size_t GetTensorShapeElementCount(_In_ const OrtTensorTypeAndShapeInfo* info);
- ONNXTensorElementDataType GetTensorElementType(const OrtTensorTypeAndShapeInfo* info);
- size_t GetDimensionsCount(_In_ const OrtTensorTypeAndShapeInfo* info);
- void GetDimensions(_In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, size_t dim_values_length);
- void SetDimensions(OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count);
-
- template <typename T>
- T* GetTensorMutableData(_Inout_ OrtValue* value);
- template <typename T>
- const T* GetTensorData(_Inout_ const OrtValue* value);
-
- std::vector<int64_t> GetTensorShape(const OrtTensorTypeAndShapeInfo* info);
- void ReleaseTensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* input);
- size_t KernelContext_GetInputCount(const OrtKernelContext* context);
- const OrtValue* KernelContext_GetInput(const OrtKernelContext* context, _In_ size_t index);
- size_t KernelContext_GetOutputCount(const OrtKernelContext* context);
- OrtValue* KernelContext_GetOutput(OrtKernelContext* context, _In_ size_t index, _In_ const int64_t* dim_values, size_t dim_count);
-
- void ThrowOnError(OrtStatus* result);
-
- private:
- const OrtApi& api_;
-};
-
-template <typename TOp, typename TKernel>
-struct CustomOpBase : OrtCustomOp {
- CustomOpBase() {
- OrtCustomOp::version = ORT_API_VERSION;
- OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast<const TOp*>(this_)->CreateKernel(*api, info); };
- OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast<const TOp*>(this_)->GetName(); };
-
- OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast<const TOp*>(this_)->GetExecutionProviderType(); };
-
- OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast<const TOp*>(this_)->GetInputTypeCount(); };
- OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast<const TOp*>(this_)->GetInputType(index); };
-
- OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast<const TOp*>(this_)->GetOutputTypeCount(); };
- OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast<const TOp*>(this_)->GetOutputType(index); };
-
- OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { static_cast<TKernel*>(op_kernel)->Compute(context); };
- OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast<TKernel*>(op_kernel); };
- }
-
- // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider
- const char* GetExecutionProviderType() const { return nullptr; }
-};
-
-} // namespace Ort
-
-#include "onnxruntime_cxx_inline.h"
diff --git a/include/onnxruntime/core/session/onnxruntime_cxx_inline.h b/include/onnxruntime/core/session/onnxruntime_cxx_inline.h
deleted file mode 100755
index a5ce821..0000000
--- a/include/onnxruntime/core/session/onnxruntime_cxx_inline.h
+++ /dev/null
@@ -1,985 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead.
-// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead.
-//
-// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter
-// the main C++ file with implementation details.
-
-namespace Ort {
-
-inline void ThrowOnError(const OrtApi& ort, OrtStatus* status) {
- if (status) {
- std::string error_message = ort.GetErrorMessage(status);
- OrtErrorCode error_code = ort.GetErrorCode(status);
- ort.ReleaseStatus(status);
- ORT_CXX_API_THROW(std::move(error_message), error_code);
- }
-}
-
-inline void ThrowOnError(OrtStatus* status) {
- ThrowOnError(GetApi(), status);
-}
-
-// This template converts a C++ type into it's ONNXTensorElementDataType
-template <typename T>
-struct TypeToTensorType;
-template <>
-struct TypeToTensorType<float> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; };
-template <>
-struct TypeToTensorType<Float16_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };
-template <>
-struct TypeToTensorType<BFloat16_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; };
-template <>
-struct TypeToTensorType<double> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; };
-template <>
-struct TypeToTensorType<int8_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; };
-template <>
-struct TypeToTensorType<int16_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; };
-template <>
-struct TypeToTensorType<int32_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; };
-template <>
-struct TypeToTensorType<int64_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; };
-template <>
-struct TypeToTensorType<uint8_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; };
-template <>
-struct TypeToTensorType<uint16_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; };
-template <>
-struct TypeToTensorType<uint32_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; };
-template <>
-struct TypeToTensorType<uint64_t> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; };
-template <>
-struct TypeToTensorType<bool> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; };
-
-inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size)
- : allocator_(allocator), p_(p), size_(size) {
-}
-
-inline MemoryAllocation::~MemoryAllocation() {
- if (p_ != nullptr) {
- // We do not throw out of destructor
- auto ret = GetApi().AllocatorFree(allocator_, p_);
- static_cast<void>(ret);
- }
-}
-
-inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) : allocator_(nullptr), p_(nullptr), size_(0) {
- *this = std::move(o);
-}
-
-inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) {
- OrtAllocator* alloc = nullptr;
- void* p = nullptr;
- size_t sz = 0;
-
- // Swap out this
- std::swap(alloc, allocator_);
- std::swap(p, p_);
- std::swap(sz, size_);
-
- // Swap with incoming
- std::swap(allocator_, o.allocator_);
- std::swap(p_, o.p_);
- std::swap(size_, o.size_);
-
- // Destroy this instance if needed
- MemoryAllocation this_alloc(alloc, p, sz);
- return *this;
-}
-
-inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() {
- ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&p_));
-}
-
-inline void* AllocatorWithDefaultOptions::Alloc(size_t size) {
- void* out;
- ThrowOnError(GetApi().AllocatorAlloc(p_, size, &out));
- return out;
-}
-
-inline MemoryAllocation Ort::AllocatorWithDefaultOptions::GetAllocation(size_t size) {
- void* out;
- ThrowOnError(GetApi().AllocatorAlloc(p_, size, &out));
- MemoryAllocation result(p_, out, size);
- return result;
-}
-
-inline void AllocatorWithDefaultOptions::Free(void* p) {
- ThrowOnError(GetApi().AllocatorFree(p_, p));
-}
-
-inline const OrtMemoryInfo* AllocatorWithDefaultOptions::GetInfo() const {
- const OrtMemoryInfo* out;
- ThrowOnError(GetApi().AllocatorGetInfo(p_, &out));
- return out;
-}
-
-template <typename B>
-inline std::string BaseMemoryInfo<B>::GetAllocatorName() const {
- const char* name = nullptr;
- ThrowOnError(GetApi().MemoryInfoGetName(*this, &name));
- return std::string(name);
-}
-
-template <typename B>
-inline OrtAllocatorType BaseMemoryInfo<B>::GetAllocatorType() const {
- OrtAllocatorType type;
- ThrowOnError(GetApi().MemoryInfoGetType(*this, &type));
- return type;
-}
-
-template <typename B>
-int BaseMemoryInfo<B>::GetDeviceId() const {
- int id = 0;
- ThrowOnError(GetApi().MemoryInfoGetId(*this, &id));
- return id;
-}
-
-template <typename B>
-inline OrtMemType BaseMemoryInfo<B>::GetMemoryType() const {
- OrtMemType type;
- ThrowOnError(GetApi().MemoryInfoGetMemType(*this, &type));
- return type;
-}
-
-template <typename B>
-template <typename U>
-inline bool BaseMemoryInfo<B>::operator==(const BaseMemoryInfo<U>& o) const {
- int comp_result = 0;
- ThrowOnError(Ort::GetApi().CompareMemoryInfo(*this, o, &comp_result));
- return comp_result == 0;
-}
-
-inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) {
- OrtMemoryInfo* p;
- ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p));
- return MemoryInfo(p);
-}
-
-inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) {
- ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &p_));
-}
-
-inline Allocator::Allocator(const Session& sess, const MemoryInfo& mem_info) {
- ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &p_));
-}
-
-inline void* Allocator::Alloc(size_t size) const {
- void* out = nullptr;
- ThrowOnError(GetApi().AllocatorAlloc(p_, size, &out));
- return out;
-}
-
-inline MemoryAllocation Ort::Allocator::GetAllocation(size_t size) {
- void* out = nullptr;
- ThrowOnError(GetApi().AllocatorAlloc(p_, size, &out));
- MemoryAllocation result(p_, out, size);
- return result;
-}
-
-inline void Allocator::Free(void* p) const {
- ThrowOnError(GetApi().AllocatorFree(p_, p));
-}
-
-inline UnownedMemoryInfo Allocator::GetInfo() const {
- const OrtMemoryInfo* out = nullptr;
- ThrowOnError(GetApi().AllocatorGetInfo(p_, &out));
- return UnownedMemoryInfo(out);
-}
-
-inline IoBinding::IoBinding(Session& session) {
- ThrowOnError(GetApi().CreateIoBinding(session, &p_));
-}
-
-inline void IoBinding::BindInput(const char* name, const Value& value) {
- ThrowOnError(GetApi().BindInput(p_, name, value));
-}
-
-inline void IoBinding::BindOutput(const char* name, const Value& value) {
- ThrowOnError(GetApi().BindOutput(p_, name, value));
-}
-
-inline void IoBinding::BindOutput(const char* name, const MemoryInfo& mem_info) {
- ThrowOnError(GetApi().BindOutputToDevice(p_, name, mem_info));
-}
-
-inline std::vector<std::string> IoBinding::GetOutputNamesHelper(OrtAllocator* allocator) const {
- std::vector<std::string> result;
- auto free_fn = [allocator](void* p) { if (p) allocator->Free(allocator, p); };
- using Ptr = std::unique_ptr<void, decltype(free_fn)>;
-
- char* buffer = nullptr;
- size_t* lengths = nullptr;
- size_t count = 0;
- ThrowOnError(GetApi().GetBoundOutputNames(p_, allocator, &buffer, &lengths, &count));
-
- if (count == 0) {
- return result;
- }
-
- Ptr buffer_g(buffer, free_fn);
- Ptr lengths_g(lengths, free_fn);
-
- result.reserve(count);
- for (size_t i = 0; i < count; ++i) {
- auto sz = *lengths;
- result.emplace_back(buffer, sz);
- buffer += sz;
- ++lengths;
- }
- return result;
-}
-
-inline std::vector<std::string> IoBinding::GetOutputNames() const {
- AllocatorWithDefaultOptions allocator;
- return GetOutputNamesHelper(allocator);
-}
-
-inline std::vector<std::string> IoBinding::GetOutputNames(Allocator& allocator) const {
- return GetOutputNamesHelper(allocator);
-}
-
-inline std::vector<Value> Ort::IoBinding::GetOutputValuesHelper(OrtAllocator* allocator) const {
- std::vector<Value> result;
- size_t owned = 0;
- size_t output_count = 0;
- // Lambda to release the buffer when no longer needed and
- // make sure that we destroy all instances on exception
- auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) {
- if (buffer) {
- while (owned < output_count) {
- auto* p = buffer + owned++;
- GetApi().ReleaseValue(*p);
- }
- allocator->Free(allocator, buffer);
- }
- };
- using Ptr = std::unique_ptr<OrtValue*, decltype(free_fn)>;
-
- OrtValue** output_buffer = nullptr;
- ThrowOnError(GetApi().GetBoundOutputValues(p_, allocator, &output_buffer, &output_count));
- if (output_count == 0) {
- return result;
- }
-
- Ptr buffer_g(output_buffer, free_fn);
-
- result.reserve(output_count);
- for (size_t i = 0; i < output_count; ++i) {
- result.emplace_back(output_buffer[i]);
- ++owned;
- }
- return result;
-}
-
-inline std::vector<Value> Ort::IoBinding::GetOutputValues(Allocator& allocator) const {
- return GetOutputValuesHelper(allocator);
-}
-
-inline std::vector<Value> Ort::IoBinding::GetOutputValues() const {
- AllocatorWithDefaultOptions allocator;
- return GetOutputValuesHelper(allocator);
-}
-
-inline void IoBinding::ClearBoundInputs() {
- GetApi().ClearBoundInputs(p_);
-}
-
-inline void IoBinding::ClearBoundOutputs() {
- GetApi().ClearBoundOutputs(p_);
-}
-
-inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) {
- ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_));
-}
-
-inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) {
- ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_));
- if (strcmp(logid, "onnxruntime-node") == 0) {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
- } else {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
- }
-}
-
-inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) {
- ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_));
- if (strcmp(logid, "onnxruntime-node") == 0) {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
- } else {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
- }
-}
-
-inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) {
- ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_));
- if (strcmp(logid, "onnxruntime-node") == 0) {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
- } else {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
- }
-}
-
-inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param,
- OrtLoggingLevel logging_level, _In_ const char* logid) {
- ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_));
- if (strcmp(logid, "onnxruntime-node") == 0) {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
- } else {
- ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
- }
-}
-
-inline Env& Env::EnableTelemetryEvents() {
- ThrowOnError(GetApi().EnableTelemetryEvents(p_));
- return *this;
-}
-
-inline Env& Env::DisableTelemetryEvents() {
- ThrowOnError(GetApi().DisableTelemetryEvents(p_));
- return *this;
-}
-
-inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) {
- ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg));
- return *this;
-}
-
-inline CustomOpDomain::CustomOpDomain(const char* domain) {
- ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_));
-}
-
-inline void CustomOpDomain::Add(OrtCustomOp* op) {
- ThrowOnError(GetApi().CustomOpDomain_Add(p_, op));
-}
-
-inline RunOptions::RunOptions() {
- ThrowOnError(GetApi().CreateRunOptions(&p_));
-}
-
-inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) {
- ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level));
- return *this;
-}
-
-inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) {
- ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level));
- return *this;
-}
-
-inline int RunOptions::GetRunLogVerbosityLevel() const {
- int out;
- ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out));
- return out;
-}
-
-inline RunOptions& RunOptions::SetRunTag(const char* run_tag) {
- ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag));
- return *this;
-}
-
-inline const char* RunOptions::GetRunTag() const {
- const char* out;
- ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out));
- return out;
-}
-
-inline RunOptions& RunOptions::SetTerminate() {
- ThrowOnError(GetApi().RunOptionsSetTerminate(p_));
- return *this;
-}
-
-inline RunOptions& RunOptions::UnsetTerminate() {
- ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_));
- return *this;
-}
-
-inline SessionOptions::SessionOptions() {
- ThrowOnError(GetApi().CreateSessionOptions(&p_));
-}
-
-inline SessionOptions SessionOptions::Clone() const {
- OrtSessionOptions* out;
- ThrowOnError(GetApi().CloneSessionOptions(p_, &out));
- return SessionOptions{out};
-}
-
-inline SessionOptions& SessionOptions::SetIntraOpNumThreads(int intra_op_num_threads) {
- ThrowOnError(GetApi().SetIntraOpNumThreads(p_, intra_op_num_threads));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetInterOpNumThreads(int inter_op_num_threads) {
- ThrowOnError(GetApi().SetInterOpNumThreads(p_, inter_op_num_threads));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) {
- ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(p_, graph_optimization_level));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) {
- ThrowOnError(GetApi().SetOptimizedModelFilePath(p_, optimized_model_filepath));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::EnableProfiling(const ORTCHAR_T* profile_file_prefix) {
- ThrowOnError(GetApi().EnableProfiling(p_, profile_file_prefix));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::DisableProfiling() {
- ThrowOnError(GetApi().DisableProfiling(p_));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::EnableMemPattern() {
- ThrowOnError(GetApi().EnableMemPattern(p_));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::DisableMemPattern() {
- ThrowOnError(GetApi().DisableMemPattern(p_));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::EnableCpuMemArena() {
- ThrowOnError(GetApi().EnableCpuMemArena(p_));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::DisableCpuMemArena() {
- ThrowOnError(GetApi().DisableCpuMemArena(p_));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetExecutionMode(ExecutionMode execution_mode) {
- ThrowOnError(GetApi().SetSessionExecutionMode(p_, execution_mode));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetLogId(const char* logid) {
- ThrowOnError(GetApi().SetSessionLogId(p_, logid));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::SetLogSeverityLevel(int level) {
- ThrowOnError(GetApi().SetSessionLogSeverityLevel(p_, level));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::Add(OrtCustomOpDomain* custom_op_domain) {
- ThrowOnError(GetApi().AddCustomOpDomain(p_, custom_op_domain));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::AddConfigEntry(const char* config_key, const char* config_value) {
- ThrowOnError(GetApi().AddSessionConfigEntry(p_, config_key, config_value));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::AddInitializer(const char* name, const OrtValue* ort_val) {
- ThrowOnError(GetApi().AddInitializer(p_, name, ort_val));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) {
- ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(p_, &provider_options));
- return *this;
-}
-
-inline SessionOptions& SessionOptions::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) {
- ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(p_, &provider_options));
- return *this;
-}
-
-inline Session::Session(Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) {
- ThrowOnError(GetApi().CreateSession(env, model_path, options, &p_));
-}
-
-inline Session::Session(Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) {
- ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &p_));
-}
-
-inline std::vector<Value> Session::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
- const char* const* output_names, size_t output_names_count) {
- std::vector<Ort::Value> output_values;
- for (size_t i = 0; i < output_names_count; i++)
- output_values.emplace_back(nullptr);
- Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_names_count);
- return output_values;
-}
-
-inline void Session::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
- const char* const* output_names, Value* output_values, size_t output_count) {
- static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
- auto ort_input_values = reinterpret_cast<const OrtValue**>(const_cast<Value*>(input_values));
- auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
- ThrowOnError(GetApi().Run(p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values));
-}
-
-inline void Session::Run(const RunOptions& run_options, const IoBinding& io_binding) {
- ThrowOnError(GetApi().RunWithBinding(p_, run_options, io_binding));
-}
-
-inline size_t Session::GetInputCount() const {
- size_t out;
- ThrowOnError(GetApi().SessionGetInputCount(p_, &out));
- return out;
-}
-
-inline size_t Session::GetOutputCount() const {
- size_t out;
- ThrowOnError(GetApi().SessionGetOutputCount(p_, &out));
- return out;
-}
-
-inline size_t Session::GetOverridableInitializerCount() const {
- size_t out;
- ThrowOnError(GetApi().SessionGetOverridableInitializerCount(p_, &out));
- return out;
-}
-
-inline char* Session::GetInputName(size_t index, OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().SessionGetInputName(p_, index, allocator, &out));
- return out;
-}
-
-inline char* Session::GetOutputName(size_t index, OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().SessionGetOutputName(p_, index, allocator, &out));
- return out;
-}
-
-inline char* Session::GetOverridableInitializerName(size_t index, OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().SessionGetOverridableInitializerName(p_, index, allocator, &out));
- return out;
-}
-
-inline char* Session::EndProfiling(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().SessionEndProfiling(p_, allocator, &out));
- return out;
-}
-
-inline uint64_t Session::GetProfilingStartTimeNs() const {
- uint64_t out;
- ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(p_, &out));
- return out;
-}
-
-inline ModelMetadata Session::GetModelMetadata() const {
- OrtModelMetadata* out;
- ThrowOnError(GetApi().SessionGetModelMetadata(p_, &out));
- return ModelMetadata{out};
-}
-
-inline char* ModelMetadata::GetProducerName(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out));
- return out;
-}
-
-inline char* ModelMetadata::GetGraphName(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out));
- return out;
-}
-
-inline char* ModelMetadata::GetDomain(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out));
- return out;
-}
-
-inline char* ModelMetadata::GetDescription(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out));
- return out;
-}
-
-inline char* ModelMetadata::GetGraphDescription(OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out));
- return out;
-}
-
-inline char* ModelMetadata::LookupCustomMetadataMap(const char* key, OrtAllocator* allocator) const {
- char* out;
- ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out));
- return out;
-}
-
-inline char** ModelMetadata::GetCustomMetadataMapKeys(OrtAllocator* allocator, _Out_ int64_t& num_keys) const {
- char** out;
- ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys));
- return out;
-}
-
-inline int64_t ModelMetadata::GetVersion() const {
- int64_t out;
- ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out));
- return out;
-}
-
-inline TypeInfo Session::GetInputTypeInfo(size_t index) const {
- OrtTypeInfo* out;
- ThrowOnError(GetApi().SessionGetInputTypeInfo(p_, index, &out));
- return TypeInfo{out};
-}
-
-inline TypeInfo Session::GetOutputTypeInfo(size_t index) const {
- OrtTypeInfo* out;
- ThrowOnError(GetApi().SessionGetOutputTypeInfo(p_, index, &out));
- return TypeInfo{out};
-}
-
-inline TypeInfo Session::GetOverridableInitializerTypeInfo(size_t index) const {
- OrtTypeInfo* out;
- ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(p_, index, &out));
- return TypeInfo{out};
-}
-
-inline ONNXTensorElementDataType TensorTypeAndShapeInfo::GetElementType() const {
- ONNXTensorElementDataType out;
- ThrowOnError(GetApi().GetTensorElementType(p_, &out));
- return out;
-}
-
-inline size_t TensorTypeAndShapeInfo::GetElementCount() const {
- size_t out;
- ThrowOnError(GetApi().GetTensorShapeElementCount(p_, &out));
- return static_cast<size_t>(out);
-}
-
-inline size_t TensorTypeAndShapeInfo::GetDimensionsCount() const {
- size_t out;
- ThrowOnError(GetApi().GetDimensionsCount(p_, &out));
- return out;
-}
-
-inline void TensorTypeAndShapeInfo::GetDimensions(int64_t* values, size_t values_count) const {
- ThrowOnError(GetApi().GetDimensions(p_, values, values_count));
-}
-
-inline void TensorTypeAndShapeInfo::GetSymbolicDimensions(const char** values, size_t values_count) const {
- ThrowOnError(GetApi().GetSymbolicDimensions(p_, values, values_count));
-}
-
-inline std::vector<int64_t> TensorTypeAndShapeInfo::GetShape() const {
- std::vector<int64_t> out(GetDimensionsCount(), 0);
- GetDimensions(out.data(), out.size());
- return out;
-}
-
-inline Unowned<TensorTypeAndShapeInfo> TypeInfo::GetTensorTypeAndShapeInfo() const {
- const OrtTensorTypeAndShapeInfo* out;
- ThrowOnError(GetApi().CastTypeInfoToTensorInfo(p_, &out));
- return Unowned<TensorTypeAndShapeInfo>(const_cast<OrtTensorTypeAndShapeInfo*>(out));
-}
-
-inline Unowned<SequenceTypeInfo> TypeInfo::GetSequenceTypeInfo() const {
- const OrtSequenceTypeInfo* out;
- ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(p_, &out));
- return Unowned<SequenceTypeInfo>{const_cast<OrtSequenceTypeInfo*>(out)};
-}
-
-inline TypeInfo SequenceTypeInfo::GetSequenceElementType() const {
- OrtTypeInfo* output;
- ThrowOnError(GetApi().GetSequenceElementType(p_, &output));
- return TypeInfo{output};
-}
-
-inline Unowned<MapTypeInfo> TypeInfo::GetMapTypeInfo() const {
- const OrtMapTypeInfo* out;
- ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(p_, &out));
- return Unowned<MapTypeInfo>{const_cast<OrtMapTypeInfo*>(out)};
-}
-
-inline ONNXTensorElementDataType MapTypeInfo::GetMapKeyType() const {
- ONNXTensorElementDataType out;
- ThrowOnError(GetApi().GetMapKeyType(p_, &out));
- return out;
-}
-
-inline TypeInfo MapTypeInfo::GetMapValueType() const {
- OrtTypeInfo* output;
- ThrowOnError(GetApi().GetMapValueType(p_, &output));
- return TypeInfo{output};
-}
-
-inline ONNXType TypeInfo::GetONNXType() const {
- ONNXType out;
- ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(p_, &out));
- return out;
-}
-
-template <typename T>
-inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len) {
- return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType<T>::type);
-}
-
-inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, const int64_t* shape, size_t shape_len,
- ONNXTensorElementDataType type) {
- OrtValue* out;
- ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out));
- return Value{out};
-}
-
-template <typename T>
-inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) {
- return CreateTensor(allocator, shape, shape_len, TypeToTensorType<T>::type);
-}
-
-inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type) {
- OrtValue* out;
- ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out));
- return Value{out};
-}
-
-inline Value Value::CreateMap(Value& keys, Value& values) {
- OrtValue* out;
- OrtValue* inputs[2] = {keys, values};
- ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out));
- return Value{out};
-}
-
-inline Value Value::CreateSequence(std::vector<Value>& values) {
- OrtValue* out;
- std::vector<OrtValue*> values_ort{values.data(), values.data() + values.size()};
- ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out));
- return Value{out};
-}
-
-template <typename T>
-inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) {
- OrtValue* out;
- ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out));
- return Value{out};
-}
-
-template <typename T>
-inline void Value::GetOpaqueData(const char* domain, const char* type_name, T& out) const {
- ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, p_, &out, sizeof(T)));
-}
-
-inline bool Value::IsTensor() const {
- int out;
- ThrowOnError(GetApi().IsTensor(p_, &out));
- return out != 0;
-}
-
-inline size_t Value::GetCount() const {
- size_t out;
- ThrowOnError(GetApi().GetValueCount(p_, &out));
- return out;
-}
-
-inline Value Value::GetValue(int index, OrtAllocator* allocator) const {
- OrtValue* out;
- ThrowOnError(GetApi().GetValue(p_, index, allocator, &out));
- return Value{out};
-}
-
-inline size_t Value::GetStringTensorDataLength() const {
- size_t out;
- ThrowOnError(GetApi().GetStringTensorDataLength(p_, &out));
- return out;
-}
-
-inline size_t Value::GetStringTensorElementLength(size_t element_index) const {
- size_t out;
- ThrowOnError(GetApi().GetStringTensorElementLength(p_, element_index, &out));
- return out;
-}
-
-inline void Value::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const {
- ThrowOnError(GetApi().GetStringTensorContent(p_, buffer, buffer_length, offsets, offsets_count));
-}
-
-inline void Value::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const {
- ThrowOnError(GetApi().GetStringTensorElement(p_, buffer_length, element_index, buffer));
-}
-
-inline void Value::FillStringTensor(const char* const* s, size_t s_len) {
- ThrowOnError(GetApi().FillStringTensor(p_, s, s_len));
-}
-
-inline void Value::FillStringTensorElement(const char* s, size_t index) {
- ThrowOnError(GetApi().FillStringTensorElement(p_, s, index));
-}
-
-template <typename T>
-T* Value::GetTensorMutableData() {
- T* out;
- ThrowOnError(GetApi().GetTensorMutableData(p_, (void**)&out));
- return out;
-}
-
-template <typename T>
-const T* Value::GetTensorData() const {
- T* out;
- ThrowOnError(GetApi().GetTensorMutableData(p_, (void**)&out));
- return out;
-}
-
-template <typename T>
-inline T& Value::At(const std::vector<int64_t>& location) {
- static_assert(!std::is_same<T, std::string>::value, "this api does not support std::string");
- T* out;
- ThrowOnError(GetApi().TensorAt(p_, location.data(), location.size(), (void**)&out));
- return *out;
-}
-
-inline TypeInfo Value::GetTypeInfo() const {
- OrtTypeInfo* output;
- ThrowOnError(GetApi().GetTypeInfo(p_, &output));
- return TypeInfo{output};
-}
-
-inline TensorTypeAndShapeInfo Value::GetTensorTypeAndShapeInfo() const {
- OrtTensorTypeAndShapeInfo* output;
- ThrowOnError(GetApi().GetTensorTypeAndShape(p_, &output));
- return TensorTypeAndShapeInfo{output};
-}
-
-//
-// Custom OP API Inlines
-//
-inline void CustomOpApi::ThrowOnError(OrtStatus* status) {
- Ort::ThrowOnError(api_, status);
-}
-
-template <>
-inline float CustomOpApi::KernelInfoGetAttribute<float>(_In_ const OrtKernelInfo* info, _In_ const char* name) {
- float out;
- ThrowOnError(api_.KernelInfoGetAttribute_float(info, name, &out));
- return out;
-}
-
-template <>
-inline int64_t CustomOpApi::KernelInfoGetAttribute<int64_t>(_In_ const OrtKernelInfo* info, _In_ const char* name) {
- int64_t out;
- ThrowOnError(api_.KernelInfoGetAttribute_int64(info, name, &out));
- return out;
-}
-
-template <>
-inline std::string CustomOpApi::KernelInfoGetAttribute<std::string>(_In_ const OrtKernelInfo* info, _In_ const char* name) {
- size_t size = 0;
- std::string out;
- OrtStatus* status = api_.KernelInfoGetAttribute_string(info, name, nullptr, &size);
-
- // The status should be ORT_INVALID_ARGUMENT because the size is insufficient to hold the string
- if (api_.GetErrorCode(status) == ORT_INVALID_ARGUMENT) {
- api_.ReleaseStatus(status);
- out.resize(size);
- ThrowOnError(api_.KernelInfoGetAttribute_string(info, name, &out[0], &size));
- out.resize(size - 1); // remove the terminating character '\0'
- } else {
- ThrowOnError(status);
- }
- return out;
-}
-
-inline OrtTensorTypeAndShapeInfo* CustomOpApi::GetTensorTypeAndShape(_In_ const OrtValue* value) {
- OrtTensorTypeAndShapeInfo* out;
- ThrowOnError(api_.GetTensorTypeAndShape(value, &out));
- return out;
-}
-
-inline size_t CustomOpApi::GetTensorShapeElementCount(_In_ const OrtTensorTypeAndShapeInfo* info) {
- size_t out;
- ThrowOnError(api_.GetTensorShapeElementCount(info, &out));
- return out;
-}
-
-inline ONNXTensorElementDataType CustomOpApi::GetTensorElementType(const OrtTensorTypeAndShapeInfo* info) {
- ONNXTensorElementDataType out;
- ThrowOnError(api_.GetTensorElementType(info, &out));
- return out;
-}
-
-inline size_t CustomOpApi::GetDimensionsCount(_In_ const OrtTensorTypeAndShapeInfo* info) {
- size_t out;
- ThrowOnError(api_.GetDimensionsCount(info, &out));
- return out;
-}
-
-inline void CustomOpApi::GetDimensions(_In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, size_t dim_values_length) {
- ThrowOnError(api_.GetDimensions(info, dim_values, dim_values_length));
-}
-
-inline void CustomOpApi::SetDimensions(OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count) {
- ThrowOnError(api_.SetDimensions(info, dim_values, dim_count));
-}
-
-template <typename T>
-inline T* CustomOpApi::GetTensorMutableData(_Inout_ OrtValue* value) {
- T* data;
- ThrowOnError(api_.GetTensorMutableData(value, reinterpret_cast<void**>(&data)));
- return data;
-}
-
-template <typename T>
-inline const T* CustomOpApi::GetTensorData(_Inout_ const OrtValue* value) {
- return GetTensorMutableData<T>(const_cast<OrtValue*>(value));
-}
-
-inline std::vector<int64_t> CustomOpApi::GetTensorShape(const OrtTensorTypeAndShapeInfo* info) {
- std::vector<int64_t> output(GetDimensionsCount(info));
- GetDimensions(info, output.data(), output.size());
- return output;
-}
-
-inline void CustomOpApi::ReleaseTensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* input) {
- api_.ReleaseTensorTypeAndShapeInfo(input);
-}
-
-inline size_t CustomOpApi::KernelContext_GetInputCount(const OrtKernelContext* context) {
- size_t out;
- ThrowOnError(api_.KernelContext_GetInputCount(context, &out));
- return out;
-}
-
-inline const OrtValue* CustomOpApi::KernelContext_GetInput(const OrtKernelContext* context, _In_ size_t index) {
- const OrtValue* out;
- ThrowOnError(api_.KernelContext_GetInput(context, index, &out));
- return out;
-}
-
-inline size_t CustomOpApi::KernelContext_GetOutputCount(const OrtKernelContext* context) {
- size_t out;
- ThrowOnError(api_.KernelContext_GetOutputCount(context, &out));
- return out;
-}
-
-inline OrtValue* CustomOpApi::KernelContext_GetOutput(OrtKernelContext* context, _In_ size_t index,
- _In_ const int64_t* dim_values, size_t dim_count) {
- OrtValue* out;
- ThrowOnError(api_.KernelContext_GetOutput(context, index, dim_values, dim_count, &out));
- return out;
-}
-
-inline SessionOptions& SessionOptions::DisablePerSessionThreads() {
- ThrowOnError(GetApi().DisablePerSessionThreads(p_));
- return *this;
-}
-
-inline std::vector<std::string> GetAvailableProviders() {
- int len;
- char** providers;
- const OrtApi& api = GetApi();
- ThrowOnError(api.GetAvailableProviders(&providers, &len));
- std::vector<std::string> available_providers(providers, providers + len);
- ThrowOnError(api.ReleaseAvailableProviders(providers, len));
- return available_providers;
-}
-
-SessionOptions& AddInitializer(const char* name, const OrtValue* ort_val);
-
-} // namespace Ort
diff --git a/include/onnxruntime/core/session/onnxruntime_session_options_config_keys.h b/include/onnxruntime/core/session/onnxruntime_session_options_config_keys.h
deleted file mode 100755
index ff247f2..0000000
--- a/include/onnxruntime/core/session/onnxruntime_session_options_config_keys.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// Licensed under the MIT License.
-
-#pragma once
-
-/*
- * This file defines SessionOptions Config Keys and format of the Config Values.
- *
- * The Naming Convention for a SessionOptions Config Key,
- * "[Area][.[SubArea1].[SubArea2]...].[Keyname]"
- * Such as "ep.cuda.use_arena"
- * The Config Key cannot be empty
- * The maximum length of the Config Key is 128
- *
- * The string format of a SessionOptions Config Value is defined individually for each Config.
- * The maximum length of the Config Value is 1024
- */
-
-// Key for disable PrePacking,
-// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value)
-static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking";
-
-// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session
-// will be used. Use this to override the usage of env allocators on a per session level.
-static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators";
-
-// Set to 'ORT' (case sensitive) to load an ORT format model.
-// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT
-static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format";
-
-// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set.
-// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'.
-static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format";
-
-// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0".
-// When multiple sessions are created, a main thread doesn't override changes from succeeding session options,
-// but threads in session thread pools follow option changes.
-// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and
-// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool.
-// Note that an alternative way not using this option at runtime is to train and export a model without denormals
-// and that's recommended because turning this option on may hurt model accuracy.
-static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero";
diff --git a/include/opencv2/calib3d.hpp b/include/opencv2/calib3d.hpp
index ced32fe..b48c928 100755
--- a/include/opencv2/calib3d.hpp
+++ b/include/opencv2/calib3d.hpp
@@ -51,17 +51,141 @@
/**
@defgroup calib3d Camera Calibration and 3D Reconstruction
-The functions in this section use a so-called pinhole camera model. In this model, a scene view is
-formed by projecting 3D points into the image plane using a perspective transformation.
+The functions in this section use a so-called pinhole camera model. The view of a scene
+is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective
+transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are
+represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will
+find a brief introduction to projective geometry, homogeneous vectors and homogeneous
+transformations at the end of this section's introduction. For more succinct notation, we often drop
+the 'homogeneous' and say vector instead of homogeneous vector.
-\f[s \; m' = A [R|t] M'\f]
+The distortion-free projective transformation given by a pinhole camera model is shown below.
-or
+\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f]
-\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}
+where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system,
+\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix,
+\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from
+world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's
+arbitrary scaling and not part of the camera model.
+
+The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated
+as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e.
+
+\f[p = A P_c.\f]
+
+The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are
+expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the
+image center:
+
+\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f]
+
+and thus
+
+\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f]
+
+The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can
+be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the
+camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided,
+respectively) by the same factor.
+
+The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective
+transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points
+represented in camera coordinates to 2D points in the image plane and represented in normalized
+camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$:
+
+\f[Z_c \begin{bmatrix}
+x' \\
+y' \\
+1
+\end{bmatrix} = \begin{bmatrix}
+1 & 0 & 0 & 0 \\
+0 & 1 & 0 & 0 \\
+0 & 0 & 1 & 0
+\end{bmatrix}
\begin{bmatrix}
-r_{11} & r_{12} & r_{13} & t_x \\
-r_{21} & r_{22} & r_{23} & t_y \\
+X_c \\
+Y_c \\
+Z_c \\
+1
+\end{bmatrix}.\f]
+
+The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and
+represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem
+\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we
+obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by
+
+\f[P_c = \begin{bmatrix}
+R & t \\
+0 & 1
+\end{bmatrix} P_w,\f]
+
+This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a
+3-by-1 translation vector:
+
+\f[\begin{bmatrix}
+R & t \\
+0 & 1
+\end{bmatrix} = \begin{bmatrix}
+r_{11} & r_{12} & r_{13} & t_x \\
+r_{21} & r_{22} & r_{23} & t_y \\
+r_{31} & r_{32} & r_{33} & t_z \\
+0 & 0 & 0 & 1
+\end{bmatrix},
+\f]
+
+and therefore
+
+\f[\begin{bmatrix}
+X_c \\
+Y_c \\
+Z_c \\
+1
+\end{bmatrix} = \begin{bmatrix}
+r_{11} & r_{12} & r_{13} & t_x \\
+r_{21} & r_{22} & r_{23} & t_y \\
+r_{31} & r_{32} & r_{33} & t_z \\
+0 & 0 & 0 & 1
+\end{bmatrix}
+\begin{bmatrix}
+X_w \\
+Y_w \\
+Z_w \\
+1
+\end{bmatrix}.\f]
+
+Combining the projective transformation and the homogeneous transformation, we obtain the projective
+transformation that maps 3D points in world coordinates into 2D points in the image plane and in
+normalized camera coordinates:
+
+\f[Z_c \begin{bmatrix}
+x' \\
+y' \\
+1
+\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix}
+X_w \\
+Y_w \\
+Z_w \\
+1
+\end{bmatrix} = \begin{bmatrix}
+r_{11} & r_{12} & r_{13} & t_x \\
+r_{21} & r_{22} & r_{23} & t_y \\
+r_{31} & r_{32} & r_{33} & t_z
+\end{bmatrix}
+\begin{bmatrix}
+X_w \\
+Y_w \\
+Z_w \\
+1
+\end{bmatrix},\f]
+
+with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out
+\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as
+
+\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}
+\begin{bmatrix}
+r_{11} & r_{12} & r_{13} & t_x \\
+r_{21} & r_{22} & r_{23} & t_y \\
r_{31} & r_{32} & r_{33} & t_z
\end{bmatrix}
\begin{bmatrix}
@@ -69,76 +193,112 @@ X_w \\
Y_w \\
Z_w \\
1
+\end{bmatrix}.\f]
+
+If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following,
+
+\f[\begin{bmatrix}
+u \\
+v
+\end{bmatrix} = \begin{bmatrix}
+f_x X_c/Z_c + c_x \\
+f_y Y_c/Z_c + c_y
\end{bmatrix}\f]
-where:
-
-- \f$(X_w, Y_w, Z_w)\f$ are the coordinates of a 3D point in the world coordinate space
-- \f$(u, v)\f$ are the coordinates of the projection point in pixels
-- \f$A\f$ is a camera matrix, or a matrix of intrinsic parameters
-- \f$(c_x, c_y)\f$ is a principal point that is usually at the image center
-- \f$f_x, f_y\f$ are the focal lengths expressed in pixel units.
-
-Thus, if an image from the camera is scaled by a factor, all of these parameters should be scaled
-(multiplied/divided, respectively) by the same factor. The matrix of intrinsic parameters does not
-depend on the scene viewed. So, once estimated, it can be re-used as long as the focal length is
-fixed (in case of zoom lens). The joint rotation-translation matrix \f$[R|t]\f$ is called a matrix of
-extrinsic parameters. It is used to describe the camera motion around a static scene, or vice versa,
-rigid motion of an object in front of a still camera. That is, \f$[R|t]\f$ translates coordinates of a
-world point \f$(X_w, Y_w, Z_w)\f$ to a coordinate system, fixed with respect to the camera.
-The transformation above is equivalent to the following (when \f$z \ne 0\f$ ):
-
-\f[\begin{array}{l}
-\vecthree{X_c}{Y_c}{Z_c} = R \vecthree{X_w}{Y_w}{Z_w} + t \\
-x' = X_c/Z_c \\
-y' = Y_c/Z_c \\
-u = f_x \times x' + c_x \\
-v = f_y \times y' + c_y
-\end{array}\f]
+with
+
+\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix}
+R|t
+\end{bmatrix} \begin{bmatrix}
+X_w \\
+Y_w \\
+Z_w \\
+1
+\end{bmatrix}.\f]
The following figure illustrates the pinhole camera model.
![Pinhole camera model](pics/pinhole_camera_model.png)
-Real lenses usually have some distortion, mostly radial distortion and slight tangential distortion.
+Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion.
So, the above model is extended as:
-\f[\begin{array}{l}
-\vecthree{X_c}{Y_c}{Z_c} = R \vecthree{X_w}{Y_w}{Z_w} + t \\
-x' = X_c/Z_c \\
-y' = Y_c/Z_c \\
-x'' = x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\
-y'' = y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
-\text{where} \quad r^2 = x'^2 + y'^2 \\
-u = f_x \times x'' + c_x \\
-v = f_y \times y'' + c_y
-\end{array}\f]
+\f[\begin{bmatrix}
+u \\
+v
+\end{bmatrix} = \begin{bmatrix}
+f_x x'' + c_x \\
+f_y y'' + c_y
+\end{bmatrix}\f]
+
+where
+
+\f[\begin{bmatrix}
+x'' \\
+y''
+\end{bmatrix} = \begin{bmatrix}
+x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\
+y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
+\end{bmatrix}\f]
+
+with
-\f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ are radial distortion coefficients. \f$p_1\f$ and \f$p_2\f$ are
-tangential distortion coefficients. \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, are the thin prism distortion
-coefficients. Higher-order coefficients are not considered in OpenCV.
+\f[r^2 = x'^2 + y'^2\f]
-The next figures show two common types of radial distortion: barrel distortion (typically \f$ k_1 < 0 \f$) and pincushion distortion (typically \f$ k_1 > 0 \f$).
+and
+
+\f[\begin{bmatrix}
+x'\\
+y'
+\end{bmatrix} = \begin{bmatrix}
+X_c/Z_c \\
+Y_c/Z_c
+\end{bmatrix},\f]
+
+if \f$Z_c \ne 0\f$.
+
+The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$
+,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$,
+are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV.
+
+The next figures show two common types of radial distortion: barrel distortion
+(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing)
+and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing).
+Radial distortion is always monotonic for real lenses,
+and if the estimator produces a non-monotonic result,
+this should be considered a calibration failure.
+More generally, radial distortion must be monotonic and the distortion function must be bijective.
+A failed estimation result may look deceptively good near the image center
+but will work poorly in e.g. AR/SFM applications.
+The optimization method used in OpenCV camera calibration does not include these constraints as
+the framework does not support the required integer programming and polynomial inequalities.
+See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information.
![](pics/distortion_examples.png)
![](pics/distortion_examples2.png)
-In some cases the image sensor may be tilted in order to focus an oblique plane in front of the
+In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the
camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or
triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and
-\f$y''\f$. This distortion can be modelled in the following way, see e.g. @cite Louhichi07.
+\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07.
+
+\f[\begin{bmatrix}
+u \\
+v
+\end{bmatrix} = \begin{bmatrix}
+f_x x''' + c_x \\
+f_y y''' + c_y
+\end{bmatrix},\f]
-\f[\begin{array}{l}
-s\vecthree{x'''}{y'''}{1} =
+where
+
+\f[s\vecthree{x'''}{y'''}{1} =
\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)}
{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
-{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
-u = f_x \times x''' + c_x \\
-v = f_y \times y''' + c_y
-\end{array}\f]
+{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f]
-where the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter \f$\tau_x\f$
-and \f$\tau_y\f$, respectively,
+and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter
+\f$\tau_x\f$ and \f$\tau_y\f$, respectively,
\f[
R(\tau_x, \tau_y) =
@@ -157,8 +317,8 @@ vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$
coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera
parameters. And they remain the same regardless of the captured image resolution. If, for example, a
camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion
-coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, \f$c_x\f$, and
-\f$c_y\f$ need to be scaled appropriately.
+coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$,
+\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately.
The functions below use the above model to do the following:
@@ -170,8 +330,63 @@ pattern (every view is described by several 3D-2D point correspondences).
- Estimate the relative position and orientation of the stereo camera "heads" and compute the
*rectification* transformation that makes the camera optical axes parallel.
+<B> Homogeneous Coordinates </B><br>
+Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use
+allows to represent points at infinity by finite coordinates and simplifies formulas when compared
+to the cartesian counterparts, e.g. they have the advantage that affine transformations can be
+expressed as linear homogeneous transformation.
+
+One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian
+vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is:
+
+\f[\begin{bmatrix}
+X \\
+Y \\
+Z
+\end{bmatrix} \rightarrow \begin{bmatrix}
+X \\
+Y \\
+Z \\
+1
+\end{bmatrix}.\f]
+
+For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector
+by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by:
+
+\f[\begin{bmatrix}
+X \\
+Y \\
+W
+\end{bmatrix} \rightarrow \begin{bmatrix}
+X / W \\
+Y / W
+\end{bmatrix},\f]
+
+if \f$W \ne 0\f$.
+
+Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent
+the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective
+transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical
+observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are
+projected to the same image point, e.g. all points along the red ray in the image of the pinhole
+camera model above would be mapped to the same image coordinate. This property is also the source
+for the scale ambiguity s in the equation of the pinhole camera model.
+
+As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by
+\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system
+0 to coordinate system 1 becomes:
+
+\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix}
+R & t \\
+0 & 1
+\end{bmatrix} P_{h_0}.\f]
+
@note
- - A calibration sample for 3 cameras in horizontal position can be found at
+ - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all
+ functions assume the same structure of this parameter, they may name it differently. The
+ parameter's description, however, will be clear in that a camera intrinsic matrix with the structure
+ shown above is required.
+ - A calibration sample for 3 cameras in a horizontal position can be found at
opencv_source_code/samples/cpp/3calibration.cpp
- A calibration sample based on a sequence of images can be found at
opencv_source_code/samples/cpp/calibration.cpp
@@ -235,8 +450,10 @@ enum SolvePnPMethod {
SOLVEPNP_ITERATIVE = 0,
SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp
SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete
- SOLVEPNP_DLS = 3, //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct
- SOLVEPNP_UPNP = 4, //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive
+ SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
+ //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct
+ SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
+ //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive
SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17
SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
//!< Object points must be coplanar.
@@ -247,6 +464,7 @@ enum SolvePnPMethod {
//!< - point 1: [ squareLength / 2, squareLength / 2, 0]
//!< - point 2: [ squareLength / 2, -squareLength / 2, 0]
//!< - point 3: [-squareLength / 2, -squareLength / 2, 0]
+ SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis20
#ifndef CV_DOXYGEN
SOLVEPNP_MAX_COUNT //!< Used for count
#endif
@@ -255,9 +473,7 @@ enum SolvePnPMethod {
enum { CALIB_CB_ADAPTIVE_THRESH = 1,
CALIB_CB_NORMALIZE_IMAGE = 2,
CALIB_CB_FILTER_QUADS = 4,
- CALIB_CB_FAST_CHECK = 8,
- CALIB_CB_EXHAUSTIVE = 16,
- CALIB_CB_ACCURACY = 32
+ CALIB_CB_FAST_CHECK = 8
};
enum { CALIB_CB_SYMMETRIC_GRID = 1,
@@ -265,8 +481,7 @@ enum { CALIB_CB_SYMMETRIC_GRID = 1,
CALIB_CB_CLUSTERING = 4
};
-enum { CALIB_NINTRINSIC = 18,
- CALIB_USE_INTRINSIC_GUESS = 0x00001,
+enum { CALIB_USE_INTRINSIC_GUESS = 0x00001,
CALIB_FIX_ASPECT_RATIO = 0x00002,
CALIB_FIX_PRINCIPAL_POINT = 0x00004,
CALIB_ZERO_TANGENT_DIST = 0x00008,
@@ -338,73 +553,6 @@ can be found in:
*/
CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() );
-
-
-/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it
- optimizes the target vector criteria "err"
- (finds local minima of each target vector component absolute value).
-
- When needed, it calls user-provided callback.
-*/
-class CV_EXPORTS LMSolver : public Algorithm
-{
-public:
- class CV_EXPORTS Callback
- {
- public:
- virtual ~Callback() {}
- /**
- computes error and Jacobian for the specified vector of parameters
-
- @param param the current vector of parameters
- @param err output vector of errors: err_i = actual_f_i - ideal_f_i
- @param J output Jacobian: J_ij = d(err_i)/d(param_j)
-
- when J=noArray(), it means that it does not need to be computed.
- Dimensionality of error vector and param vector can be different.
- The callback should explicitly allocate (with "create" method) each output array
- (unless it's noArray()).
- */
- virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0;
- };
-
- /**
- Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point.
- The final vector of parameters (whether the algorithm converged or not) is stored at the same
- vector. The method returns the number of iterations used. If it's equal to the previously specified
- maxIters, there is a big chance the algorithm did not converge.
-
- @param param initial/final vector of parameters.
-
- Note that the dimensionality of parameter space is defined by the size of param vector,
- and the dimensionality of optimized criteria is defined by the size of err vector
- computed by the callback.
- */
- virtual int run(InputOutputArray param) const = 0;
-
- /**
- Sets the maximum number of iterations
- @param maxIters the number of iterations
- */
- virtual void setMaxIters(int maxIters) = 0;
- /**
- Retrieves the current maximum number of iterations
- */
- virtual int getMaxIters() const = 0;
-
- /**
- Creates Levenberg-Marquard solver
-
- @param cb callback
- @param maxIters maximum number of iterations that can be further
- modified using setMaxIters() method.
- */
- static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters);
- static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters, double eps);
-};
-
-
-
/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp
An example program about pose estimation from coplanar points
@@ -419,15 +567,15 @@ or vector\<Point2f\> .
a vector\<Point2f\> .
@param method Method used to compute a homography matrix. The following methods are possible:
- **0** - a regular method using all the points, i.e., the least squares method
-- **RANSAC** - RANSAC-based robust method
-- **LMEDS** - Least-Median robust method
-- **RHO** - PROSAC-based robust method
+- @ref RANSAC - RANSAC-based robust method
+- @ref LMEDS - Least-Median robust method
+- @ref RHO - PROSAC-based robust method
@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier
(used in the RANSAC and RHO methods only). That is, if
\f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} * \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f]
then the point \f$i\f$ is considered as 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 mask Optional output mask set by a robust method ( RANSAC or LMEDS ). Note that the input
+@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input
mask values are ignored.
@param maxIters The maximum number of RANSAC iterations.
@param confidence Confidence level, between 0 and 1.
@@ -503,10 +651,10 @@ CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mt
OutputArray Qy = noArray(),
OutputArray Qz = noArray());
-/** @brief Decomposes a projection matrix into a rotation matrix and a camera matrix.
+/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix.
@param projMatrix 3x4 input projection matrix P.
-@param cameraMatrix Output 3x3 camera matrix K.
+@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$.
@param rotMatrix Output 3x3 external rotation matrix R.
@param transVect Output 4x1 translation vector T.
@param rotMatrixX Optional 3x3 rotation matrix around x-axis.
@@ -586,14 +734,14 @@ CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1,
/** @brief Projects 3D points to an image plane.
-@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 rvec Rotation vector. See Rodrigues for details.
-@param tvec Translation vector.
-@param cameraMatrix Camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$ .
+@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3
+1-channel or 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is the number of points in the view.
+@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of
+basis from world to camera coordinate system, see @ref calibrateCamera for details.
+@param tvec The translation vector, see parameter description above.
+@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is empty, the zero distortion coefficients are assumed.
+\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed.
@param imagePoints Output array of image points, 1xN/Nx1 2-channel, or
vector\<Point2f\> .
@param jacobian Optional output 2Nx(10+\<numDistCoeffs\>) jacobian matrix of derivatives of image
@@ -601,20 +749,21 @@ points with respect to components of the rotation vector, translation vector, fo
coordinates of the principal point and the distortion coefficients. In the old interface different
components of the jacobian are returned via different output parameters.
@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the
-function assumes that the aspect ratio (*fx/fy*) is fixed and correspondingly adjusts the jacobian
-matrix.
-
-The function computes projections of 3D points to the image plane given intrinsic and extrinsic
-camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of
-image points coordinates (as functions of all the input parameters) with respect to the particular
-parameters, intrinsic and/or extrinsic. The Jacobians are used during the global optimization in
-calibrateCamera, solvePnP, and stereoCalibrate . The function itself can also be used to compute a
-re-projection error given the current intrinsic and extrinsic parameters.
-
-@note By setting rvec=tvec=(0,0,0) or by setting cameraMatrix to a 3x3 identity matrix, or by
-passing zero distortion coefficients, you can get various useful partial cases of the function. This
-means that you can compute the distorted coordinates for a sparse set of points or apply a
-perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
+function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the
+jacobian matrix.
+
+The function computes the 2D projections of 3D points to the image plane, given intrinsic and
+extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial
+derivatives of image points coordinates (as functions of all the input parameters) with respect to
+the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global
+optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself
+can also be used to compute a re-projection error, given the current intrinsic and extrinsic
+parameters.
+
+@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix,
+or by passing zero distortion coefficients, one can get various useful partial cases of the
+function. This means, one can compute the distorted coordinates for a sparse set of points or apply
+a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
*/
CV_EXPORTS_W void projectPoints( InputArray objectPoints,
InputArray rvec, InputArray tvec,
@@ -646,10 +795,9 @@ Number of input points must be 4. Object points must be defined in the following
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
where N is the number of points. vector\<Point2d\> can be also passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
the model coordinate system to the camera coordinate system.
@@ -658,37 +806,42 @@ the model coordinate system to the camera coordinate system.
the provided rvec and tvec values as initial approximations of the rotation and translation
vectors, respectively, and further optimizes them.
@param flags Method for solving a PnP problem:
-- **SOLVEPNP_ITERATIVE** Iterative method is based on a Levenberg-Marquardt optimization. In
+- @ref SOLVEPNP_ITERATIVE Iterative method is based on a Levenberg-Marquardt optimization. In
this case the function finds such a pose that minimizes reprojection error, that is the sum
of squared distances between the observed projections imagePoints and the projected (using
-projectPoints ) objectPoints .
-- **SOLVEPNP_P3P** Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
+@ref projectPoints ) objectPoints .
+- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete).
In this case the function requires exactly four object and image points.
-- **SOLVEPNP_AP3P** Method is based on the paper of T. Ke, S. Roumeliotis
+- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke, S. Roumeliotis
"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
In this case the function requires exactly four object and image points.
-- **SOLVEPNP_EPNP** Method has been introduced by F. Moreno-Noguer, V. Lepetit and P. Fua in the
+- @ref SOLVEPNP_EPNP Method has been introduced by F. Moreno-Noguer, V. Lepetit and P. Fua in the
paper "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" (@cite lepetit2009epnp).
-- **SOLVEPNP_DLS** Method is based on the paper of J. Hesch and S. Roumeliotis.
+- @ref SOLVEPNP_DLS **Broken implementation. Using this flag will fallback to EPnP.** \n
+Method is based on the paper of J. Hesch and S. Roumeliotis.
"A Direct Least-Squares (DLS) Method for PnP" (@cite hesch2011direct).
-- **SOLVEPNP_UPNP** Method is based on the paper of A. Penate-Sanchez, J. Andrade-Cetto,
+- @ref SOLVEPNP_UPNP **Broken implementation. Using this flag will fallback to EPnP.** \n
+Method is based on the paper of A. Penate-Sanchez, J. Andrade-Cetto,
F. Moreno-Noguer. "Exhaustive Linearization for Robust Camera Pose and Focal Length
Estimation" (@cite penate2013exhaustive). In this case the function also estimates the parameters \f$f_x\f$ and \f$f_y\f$
assuming that both have the same value. Then the cameraMatrix is updated with the estimated
focal length.
-- **SOLVEPNP_IPPE** Method is based on the paper of T. Collins and A. Bartoli.
+- @ref SOLVEPNP_IPPE Method is based on the paper of T. Collins and A. Bartoli.
"Infinitesimal Plane-Based Pose Estimation" (@cite Collins14). This method requires coplanar object points.
-- **SOLVEPNP_IPPE_SQUARE** Method is based on the paper of Toby Collins and Adrien Bartoli.
+- @ref SOLVEPNP_IPPE_SQUARE Method is based on the paper of Toby Collins and Adrien Bartoli.
"Infinitesimal Plane-Based Pose Estimation" (@cite Collins14). This method is suitable for marker pose estimation.
It requires 4 coplanar object points defined in the following order:
- point 0: [-squareLength / 2, squareLength / 2, 0]
- point 1: [ squareLength / 2, squareLength / 2, 0]
- point 2: [ squareLength / 2, -squareLength / 2, 0]
- point 3: [-squareLength / 2, -squareLength / 2, 0]
+- @ref SOLVEPNP_SQPNP Method is based on the paper "A Consistently Fast and Globally Optimal Solution to the
+Perspective-n-Point Problem" by G. Terzakis and M.Lourakis (@cite Terzakis20). It requires 3 or more points.
+
The function estimates the object pose given a set of object points, their corresponding image
-projections, as well as the camera matrix and the distortion coefficients, see the figure below
+projections, as well as the camera intrinsic matrix and the distortion coefficients, see the figure below
(more precisely, the X-axis of the camera frame is pointing to the right, the Y-axis downward
and the Z-axis forward).
@@ -793,22 +946,23 @@ a 3D point expressed in the world frame into the camera frame:
- Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
- - The methods **SOLVEPNP_DLS** and **SOLVEPNP_UPNP** cannot be used as the current implementations are
+ - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
unstable and sometimes give completely wrong results. If you pass one of these two
- flags, **SOLVEPNP_EPNP** method will be used instead.
- - The minimum number of points is 4 in the general case. In the case of **SOLVEPNP_P3P** and **SOLVEPNP_AP3P**
+ flags, @ref SOLVEPNP_EPNP method will be used instead.
+ - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
- - With **SOLVEPNP_ITERATIVE** method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
+ - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
global solution to converge.
- - With **SOLVEPNP_IPPE** input points must be >= 4 and object points must be coplanar.
- - With **SOLVEPNP_IPPE_SQUARE** this is a special case suitable for marker pose estimation.
+ - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
+ - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
Number of input points must be 4. Object points must be defined in the following order:
- point 0: [-squareLength / 2, squareLength / 2, 0]
- point 1: [ squareLength / 2, squareLength / 2, 0]
- point 2: [ squareLength / 2, -squareLength / 2, 0]
- point 3: [-squareLength / 2, -squareLength / 2, 0]
+ - With @ref SOLVEPNP_SQPNP input points must be >= 3
*/
CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
InputArray cameraMatrix, InputArray distCoeffs,
@@ -821,10 +975,9 @@ CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
where N is the number of points. vector\<Point2d\> can be also passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{fx}{0}{cx}{0}{fy}{cy}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
the model coordinate system to the camera coordinate system.
@@ -841,7 +994,7 @@ an inlier.
@param flags Method for solving a PnP problem (see @ref solvePnP ).
The function estimates an object pose given a set of object points, their corresponding image
-projections, as well as the camera matrix and the distortion coefficients. This function finds such
+projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such
a pose that minimizes reprojection error, that is, the sum of squared distances between the observed
projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC
makes the function resistant to outliers.
@@ -870,22 +1023,21 @@ CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoint
1x3/3x1 3-channel. vector\<Point3f\> can be also passed here.
@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel.
vector\<Point2f\> can be also passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions.
@param tvecs Output translation vectors.
@param flags Method for solving a P3P problem:
-- **SOLVEPNP_P3P** Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
+- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete).
-- **SOLVEPNP_AP3P** Method is based on the paper of T. Ke and S. Roumeliotis.
+- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis.
"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
The function estimates the object pose given 3 object points, their corresponding image
-projections, as well as the camera matrix and the distortion coefficients.
+projections, as well as the camera intrinsic matrix and the distortion coefficients.
@note
The solutions are sorted by reprojection errors (lowest to highest).
@@ -902,10 +1054,9 @@ to the camera coordinate frame) from a 3D-2D point correspondences and starting
where N is the number of points. vector\<Point3d\> can also be passed here.
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
where N is the number of points. vector\<Point2d\> can also be passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
@@ -914,7 +1065,7 @@ the model coordinate system to the camera coordinate system. Input values are us
The function refines the object pose given at least 3 object points, their corresponding image
projections, an initial solution for the rotation and translation vector,
-as well as the camera matrix and the distortion coefficients.
+as well as the camera intrinsic matrix and the distortion coefficients.
The function minimizes the projection error with respect to the rotation and the translation vectors, according
to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process.
*/
@@ -930,10 +1081,9 @@ to the camera coordinate frame) from a 3D-2D point correspondences and starting
where N is the number of points. vector\<Point3d\> can also be passed here.
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
where N is the number of points. vector\<Point2d\> can also be passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
@@ -944,7 +1094,7 @@ gain in the Damped Gauss-Newton formulation.
The function refines the object pose given at least 3 object points, their corresponding image
projections, an initial solution for the rotation and translation vector,
-as well as the camera matrix and the distortion coefficients.
+as well as the camera intrinsic matrix and the distortion coefficients.
The function minimizes the projection error with respect to the rotation and the translation vectors, using a
virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme.
*/
@@ -972,10 +1122,9 @@ Only 1 solution is returned.
1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
where N is the number of points. vector\<Point2d\> can be also passed here.
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
the model coordinate system to the camera coordinate system.
@@ -984,44 +1133,46 @@ the model coordinate system to the camera coordinate system.
the provided rvec and tvec values as initial approximations of the rotation and translation
vectors, respectively, and further optimizes them.
@param flags Method for solving a PnP problem:
-- **SOLVEPNP_ITERATIVE** Iterative method is based on a Levenberg-Marquardt optimization. In
+- @ref SOLVEPNP_ITERATIVE Iterative method is based on a Levenberg-Marquardt optimization. In
this case the function finds such a pose that minimizes reprojection error, that is the sum
of squared distances between the observed projections imagePoints and the projected (using
projectPoints ) objectPoints .
-- **SOLVEPNP_P3P** Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
+- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete).
In this case the function requires exactly four object and image points.
-- **SOLVEPNP_AP3P** Method is based on the paper of T. Ke, S. Roumeliotis
+- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke, S. Roumeliotis
"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
In this case the function requires exactly four object and image points.
-- **SOLVEPNP_EPNP** Method has been introduced by F.Moreno-Noguer, V.Lepetit and P.Fua in the
+- @ref SOLVEPNP_EPNP Method has been introduced by F.Moreno-Noguer, V.Lepetit and P.Fua in the
paper "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" (@cite lepetit2009epnp).
-- **SOLVEPNP_DLS** Method is based on the paper of Joel A. Hesch and Stergios I. Roumeliotis.
+- @ref SOLVEPNP_DLS **Broken implementation. Using this flag will fallback to EPnP.** \n
+Method is based on the paper of Joel A. Hesch and Stergios I. Roumeliotis.
"A Direct Least-Squares (DLS) Method for PnP" (@cite hesch2011direct).
-- **SOLVEPNP_UPNP** Method is based on the paper of A.Penate-Sanchez, J.Andrade-Cetto,
+- @ref SOLVEPNP_UPNP **Broken implementation. Using this flag will fallback to EPnP.** \n
+Method is based on the paper of A.Penate-Sanchez, J.Andrade-Cetto,
F.Moreno-Noguer. "Exhaustive Linearization for Robust Camera Pose and Focal Length
Estimation" (@cite penate2013exhaustive). In this case the function also estimates the parameters \f$f_x\f$ and \f$f_y\f$
assuming that both have the same value. Then the cameraMatrix is updated with the estimated
focal length.
-- **SOLVEPNP_IPPE** Method is based on the paper of T. Collins and A. Bartoli.
+- @ref SOLVEPNP_IPPE Method is based on the paper of T. Collins and A. Bartoli.
"Infinitesimal Plane-Based Pose Estimation" (@cite Collins14). This method requires coplanar object points.
-- **SOLVEPNP_IPPE_SQUARE** Method is based on the paper of Toby Collins and Adrien Bartoli.
+- @ref SOLVEPNP_IPPE_SQUARE Method is based on the paper of Toby Collins and Adrien Bartoli.
"Infinitesimal Plane-Based Pose Estimation" (@cite Collins14). This method is suitable for marker pose estimation.
It requires 4 coplanar object points defined in the following order:
- point 0: [-squareLength / 2, squareLength / 2, 0]
- point 1: [ squareLength / 2, squareLength / 2, 0]
- point 2: [ squareLength / 2, -squareLength / 2, 0]
- point 3: [-squareLength / 2, -squareLength / 2, 0]
-@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is SOLVEPNP_ITERATIVE
+@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
and useExtrinsicGuess is set to true.
-@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is SOLVEPNP_ITERATIVE
+@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
and useExtrinsicGuess is set to true.
@param reprojectionError Optional vector of reprojection error, that is the RMS error
(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points
and the 3D object points projected with the estimated pose.
The function estimates the object pose given a set of object points, their corresponding image
-projections, as well as the camera matrix and the distortion coefficients, see the figure below
+projections, as well as the camera intrinsic matrix and the distortion coefficients, see the figure below
(more precisely, the X-axis of the camera frame is pointing to the right, the Y-axis downward
and the Z-axis forward).
@@ -1126,17 +1277,17 @@ a 3D point expressed in the world frame into the camera frame:
- Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
- - The methods **SOLVEPNP_DLS** and **SOLVEPNP_UPNP** cannot be used as the current implementations are
+ - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
unstable and sometimes give completely wrong results. If you pass one of these two
- flags, **SOLVEPNP_EPNP** method will be used instead.
- - The minimum number of points is 4 in the general case. In the case of **SOLVEPNP_P3P** and **SOLVEPNP_AP3P**
+ flags, @ref SOLVEPNP_EPNP method will be used instead.
+ - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
- - With **SOLVEPNP_ITERATIVE** method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
+ - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
global solution to converge.
- - With **SOLVEPNP_IPPE** input points must be >= 4 and object points must be coplanar.
- - With **SOLVEPNP_IPPE_SQUARE** this is a special case suitable for marker pose estimation.
+ - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
+ - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
Number of input points must be 4. Object points must be defined in the following order:
- point 0: [-squareLength / 2, squareLength / 2, 0]
- point 1: [ squareLength / 2, squareLength / 2, 0]
@@ -1150,7 +1301,7 @@ CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoint
InputArray rvec = noArray(), InputArray tvec = noArray(),
OutputArray reprojectionError = noArray() );
-/** @brief Finds an initial camera matrix from 3D-2D point correspondences.
+/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences.
@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
@@ -1161,7 +1312,7 @@ old interface all the per-view vectors are concatenated.
@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently.
Otherwise, \f$f_x = f_y * \texttt{aspectRatio}\f$ .
-The function estimates and returns an initial camera matrix for the camera calibration process.
+The function estimates and returns an initial camera intrinsic matrix for the camera calibration process.
Currently, the function only supports planar calibration patterns, which are patterns where each
object point has z-coordinate =0.
*/
@@ -1173,16 +1324,16 @@ CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
@param image Source chessboard view. It must be an 8-bit grayscale or color image.
@param patternSize Number of inner corners per a chessboard row and column
-( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ).
+( patternSize = cvSize(points_per_row,points_per_colum) = cvSize(columns,rows) ).
@param corners Output array of detected corners.
@param flags Various operation flags that can be zero or a combination of the following values:
-- **CALIB_CB_ADAPTIVE_THRESH** Use adaptive thresholding to convert the image to black
+- @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black
and white, rather than a fixed threshold level (computed from the average image brightness).
-- **CALIB_CB_NORMALIZE_IMAGE** Normalize the image gamma with equalizeHist before
+- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before
applying fixed or adaptive thresholding.
-- **CALIB_CB_FILTER_QUADS** Use additional criteria (like contour area, perimeter,
+- @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter,
square-like shape) to filter out false quads extracted at the contour retrieval stage.
-- **CALIB_CB_FAST_CHECK** Run a fast check on the image that looks for chessboard corners,
+- @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners,
and shortcut the call if none is found. This can drastically speed up the call in the
degenerate condition when no chessboard is observed.
@@ -1221,44 +1372,6 @@ square grouping and ordering algorithm fails.
CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners,
int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE );
-/*
- Checks whether the image contains chessboard of the specific size or not.
- If yes, nonzero value is returned.
-*/
-CV_EXPORTS_W bool checkChessboard(InputArray img, Size size);
-
-/** @brief Finds the positions of internal corners of the chessboard using a sector based approach.
-
-@param image Source chessboard view. It must be an 8-bit grayscale or color image.
-@param patternSize Number of inner corners per a chessboard row and column
-( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ).
-@param corners Output array of detected corners.
-@param flags Various operation flags that can be zero or a combination of the following values:
-- **CALIB_CB_NORMALIZE_IMAGE** Normalize the image gamma with equalizeHist before detection.
-- **CALIB_CB_EXHAUSTIVE** Run an exhaustive search to improve detection rate.
-- **CALIB_CB_ACCURACY** Up sample input image to improve sub-pixel accuracy due to aliasing effects.
-This should be used if an accurate camera calibration is required.
-
-The function is analog to findchessboardCorners but uses a localized radon
-transformation approximated by box filters being more robust to all sort of
-noise, faster on larger images and is able to directly return the sub-pixel
-position of the internal chessboard corners. The Method is based on the paper
-@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for
-Calibration" demonstrating that the returned sub-pixel positions are more
-accurate than the one returned by cornerSubPix allowing a precise camera
-calibration for demanding applications.
-
-@note The function requires a white boarder with roughly the same width as one
-of the checkerboard fields around the whole board to improve the detection in
-various environments. In addition, because of the localized radon
-transformation it is beneficial to use round corners for the field corners
-which are located on the outside of the board. The following figure illustrates
-a sample checkerboard optimized for the detection. However, any other checkerboard
-can be used as well.
-![Checkerboard](pics/checkerboard_radon.png)
- */
-CV_EXPORTS_W bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners,int flags=0);
-
//! finds subpixel-accurate positions of the chessboard corners
CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size );
@@ -1281,10 +1394,9 @@ CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSiz
@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered.
@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters.
-\f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$
+\f$\cameramatrix{A}\f$
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is empty, the zero distortion coefficients are assumed.
+\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed.
@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
the model coordinate system to the camera coordinate system.
@param tvec Translation vector.
@@ -1319,15 +1431,16 @@ struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters
SYMMETRIC_GRID, ASYMMETRIC_GRID
};
GridType gridType;
+};
+
+struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters2 : public CirclesGridFinderParameters
+{
+ CV_WRAP CirclesGridFinderParameters2();
CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING.
- CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from predicion. Used by CALIB_CB_CLUSTERING.
+ CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING.
};
-#ifndef DISABLE_OPENCV_3_COMPATIBILITY
-typedef CirclesGridFinderParameters CirclesGridFinderParameters2;
-#endif
-
/** @brief Finds centers in the grid of circles.
@param image grid view of input circles; it must be an 8-bit grayscale or color image.
@@ -1335,11 +1448,12 @@ typedef CirclesGridFinderParameters CirclesGridFinderParameters2;
( patternSize = Size(points_per_row, points_per_colum) ).
@param centers output array of detected centers.
@param flags various operation flags that can be one of the following values:
-- **CALIB_CB_SYMMETRIC_GRID** uses symmetric pattern of circles.
-- **CALIB_CB_ASYMMETRIC_GRID** uses asymmetric pattern of circles.
-- **CALIB_CB_CLUSTERING** uses a special algorithm for grid detection. It is more robust to
+- @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles.
+- @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles.
+- @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to
perspective distortions but much more sensitive to background clutter.
@param blobDetector feature detector that finds blobs like dark circles on light background.
+ If `blobDetector` is NULL then `image` represents Point2f array of candidates.
@param parameters struct for finding circles in a grid pattern.
The function attempts to determine whether the input image contains a grid of circles. If it is, the
@@ -1350,7 +1464,7 @@ row). Otherwise, if the function fails to find all the corners or reorder them,
Sample usage of detecting and drawing the centers of circles: :
@code
Size patternsize(7,7); //number of centers
- Mat gray = ....; //source image
+ Mat gray = ...; //source image
vector<Point2f> centers; //this will be filled by the detected centers
bool patternfound = findCirclesGrid(gray, patternsize, centers);
@@ -1363,87 +1477,96 @@ the board to make the detection more robust in various environments.
CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
OutputArray centers, int flags,
const Ptr<FeatureDetector> &blobDetector,
- const CirclesGridFinderParameters& parameters);
+ CirclesGridFinderParameters parameters);
+
+/** @overload */
+CV_EXPORTS_W bool findCirclesGrid2( InputArray image, Size patternSize,
+ OutputArray centers, int flags,
+ const Ptr<FeatureDetector> &blobDetector,
+ CirclesGridFinderParameters2 parameters);
/** @overload */
CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID,
const Ptr<FeatureDetector> &blobDetector = SimpleBlobDetector::create());
-/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
+/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration
+pattern.
@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in
the calibration pattern coordinate space (e.g. std::vector<std::vector<cv::Vec3f>>). The outer
-vector contains as many elements as the number of the pattern views. If the same calibration pattern
+vector contains as many elements as the number of pattern views. If the same calibration pattern
is shown in each view and it is fully visible, all the vectors will be the same. Although, it is
-possible to use partially occluded patterns, or even different patterns in different views. Then,
-the vectors will be different. The points are 3D, but since they are in a pattern coordinate system,
-then, if the rig is planar, it may make sense to put the model to a XY coordinate plane so that
-Z-coordinate of each input object point is 0.
+possible to use partially occluded patterns or even different patterns in different views. Then,
+the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's
+XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig.
In the old interface all the vectors of object points from different views are concatenated
together.
@param imagePoints In the new interface it is a vector of vectors of the projections of calibration
pattern points (e.g. std::vector<std::vector<cv::Vec2f>>). imagePoints.size() and
-objectPoints.size() and imagePoints[i].size() must be equal to objectPoints[i].size() for each i.
-In the old interface all the vectors of object points from different views are concatenated
-together.
-@param imageSize Size of the image used only to initialize the intrinsic camera matrix.
-@param cameraMatrix Output 3x3 floating-point camera matrix
-\f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If CV\_CALIB\_USE\_INTRINSIC\_GUESS
-and/or CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be
+objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal,
+respectively. In the old interface all the vectors of object points from different views are
+concatenated together.
+@param imageSize Size of the image used only to initialize the camera intrinsic matrix.
+@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix
+\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS
+and/or @ref CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be
initialized before calling the function.
-@param distCoeffs Output vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements.
-@param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view
-(e.g. std::vector<cv::Mat>>). That is, each k-th rotation vector together with the corresponding
-k-th translation vector (see the next output parameter description) brings the calibration pattern
-from the model coordinate space (in which object points are specified) to the world coordinate
-space, that is, a real position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
-@param tvecs Output vector of translation vectors estimated for each pattern view.
-@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters.
- Order of deviations values:
+@param distCoeffs Input/output vector of distortion coefficients
+\f$\distcoeffs\f$.
+@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view
+(e.g. std::vector<cv::Mat>>). That is, each i-th rotation vector together with the corresponding
+i-th translation vector (see the next output parameter description) brings the calibration pattern
+from the object coordinate space (in which object points are specified) to the camera coordinate
+space. In more technical terms, the tuple of the i-th rotation and translation vector performs
+a change of basis from object coordinate space to camera coordinate space. Due to its duality, this
+tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate
+space.
+@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter
+describtion above.
+@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic
+parameters. Order of deviations values:
\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3,
s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero.
-@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters.
- Order of deviations values: \f$(R_1, T_1, \dotsc , R_M, T_M)\f$ where M is number of pattern views,
- \f$R_i, T_i\f$ are concatenated 1x3 vectors.
+@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic
+parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is
+the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors.
@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
@param flags Different flags that may be zero or a combination of the following values:
-- **CALIB_USE_INTRINSIC_GUESS** cameraMatrix contains valid initial values of
+- @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
center ( imageSize is used), and focal distances are computed in a least-squares fashion.
Note, that if intrinsic parameters are known, there is no need to use this function just to
estimate extrinsic parameters. Use solvePnP instead.
-- **CALIB_FIX_PRINCIPAL_POINT** The principal point is not changed during the global
+- @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
optimization. It stays at the center or at a different location specified when
-CALIB_USE_INTRINSIC_GUESS is set too.
-- **CALIB_FIX_ASPECT_RATIO** The functions considers only fy as a free parameter. The
+ @ref CALIB_USE_INTRINSIC_GUESS is set too.
+- @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The
ratio fx/fy stays the same as in the input cameraMatrix . When
-CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are
+ @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are
ignored, only their ratio is computed and used further.
-- **CALIB_ZERO_TANGENT_DIST** Tangential distortion coefficients \f$(p_1, p_2)\f$ are set
+- @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set
to zeros and stay zero.
-- **CALIB_FIX_K1,...,CALIB_FIX_K6** The corresponding radial distortion
-coefficient is not changed during the optimization. If CALIB_USE_INTRINSIC_GUESS is
+- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion
+coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is
set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
-- **CALIB_RATIONAL_MODEL** Coefficients k4, k5, and k6 are enabled. To provide the
+- @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the
backward compatibility, this extra flag should be explicitly specified to make the
calibration function use the rational model and return 8 coefficients. If the flag is not
set, the function computes and returns only 5 distortion coefficients.
-- **CALIB_THIN_PRISM_MODEL** Coefficients s1, s2, s3 and s4 are enabled. To provide the
+- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
backward compatibility, this extra flag should be explicitly specified to make the
calibration function use the thin prism model and return 12 coefficients. If the flag is not
set, the function computes and returns only 5 distortion coefficients.
-- **CALIB_FIX_S1_S2_S3_S4** The thin prism distortion coefficients are not changed during
-the optimization. If CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
+- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
+the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
-- **CALIB_TILTED_MODEL** Coefficients tauX and tauY are enabled. To provide the
+- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
backward compatibility, this extra flag should be explicitly specified to make the
calibration function use the tilted sensor model and return 14 coefficients. If the flag is not
set, the function computes and returns only 5 distortion coefficients.
-- **CALIB_FIX_TAUX_TAUY** The coefficients of the tilted sensor model are not changed during
-the optimization. If CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
+- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
+the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
@param criteria Termination criteria for the iterative optimization algorithm.
@@ -1452,10 +1575,10 @@ supplied distCoeffs matrix is used. Otherwise, it is set to 0.
The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object
points and their corresponding 2D projections in each view must be specified. That may be achieved
-by using an object with a known geometry and easily detectable feature points. Such an object is
+by using an object with known geometry and easily detectable feature points. Such an object is
called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as
-a calibration rig (see findChessboardCorners ). Currently, initialization of intrinsic parameters
-(when CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
+a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic
+parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also
be used as long as initial cameraMatrix is provided.
@@ -1474,14 +1597,14 @@ The algorithm performs the following steps:
objectPoints. See projectPoints for details.
@note
- If you use a non-square (=non-NxN) grid and findChessboardCorners for calibration, and
- calibrateCamera returns bad values (zero distortion coefficients, an image center very far from
- (w/2-0.5,h/2-0.5), and/or large differences between \f$f_x\f$ and \f$f_y\f$ (ratios of 10:1 or more)),
- then you have probably used patternSize=cvSize(rows,cols) instead of using
- patternSize=cvSize(cols,rows) in findChessboardCorners .
+ If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration,
+ and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and
+ \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and
+ \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols)
+ instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners.
@sa
- calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
+ findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
*/
CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints,
InputArrayOfArrays imagePoints, Size imageSize,
@@ -1493,95 +1616,24 @@ CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArray
int flags = 0, TermCriteria criteria = TermCriteria(
TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
-/** @overload */
-CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
+/** @overload double calibrateCamera( InputArrayOfArrays objectPoints,
InputArrayOfArrays imagePoints, Size imageSize,
InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
+ OutputArray stdDeviations, OutputArray perViewErrors,
int flags = 0, TermCriteria criteria = TermCriteria(
- TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
-
-/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
-
-This function is an extension of calibrateCamera() with the method of releasing object which was
-proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar
-targets (calibration plates), this method can dramatically improve the precision of the estimated
-camera parameters. Both the object-releasing method and standard method are supported by this
-function. Use the parameter **iFixedPoint** for method selection. In the internal implementation,
-calibrateCamera() is a wrapper for this function.
-
-@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern
-coordinate space. See calibrateCamera() for details. If the method of releasing object to be used,
-the identical calibration board must be used in each view and it must be fully visible, and all
-objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration
-target has to be rigid, or at least static if the camera (rather than the calibration target) is
-shifted for grabbing images.**
-@param imagePoints Vector of vectors of the projections of calibration pattern points. See
-calibrateCamera() for details.
-@param imageSize Size of the image used only to initialize the intrinsic camera matrix.
-@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as
-a switch for calibration method selection. If object-releasing method to be used, pass in the
-parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will
-make standard calibration method selected. Usually the top-right corner point of the calibration
-board grid is recommended to be fixed when object-releasing method being utilized. According to
-\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front
-and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and
-newObjPoints are only possible if coordinates of these three fixed points are accurate enough.
-@param cameraMatrix Output 3x3 floating-point camera matrix. See calibrateCamera() for details.
-@param distCoeffs Output vector of distortion coefficients. See calibrateCamera() for details.
-@param rvecs Output vector of rotation vectors estimated for each pattern view. See calibrateCamera()
-for details.
-@param tvecs Output vector of translation vectors estimated for each pattern view.
-@param newObjPoints The updated output vector of calibration pattern points. The coordinates might
-be scaled based on three fixed points. The returned coordinates are accurate only if the above
-mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter
-is ignored with standard calibration method.
-@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters.
-See calibrateCamera() for details.
-@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters.
-See calibrateCamera() for details.
-@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates
-of calibration pattern points. It has the same size and order as objectPoints[0] vector. This
-parameter is ignored with standard calibration method.
- @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
-@param flags Different flags that may be zero or a combination of some predefined values. See
-calibrateCamera() for details. If the method of releasing object is used, the calibration time may
-be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially
-less precise and less stable in some rare cases.
-@param criteria Termination criteria for the iterative optimization algorithm.
-
-@return the overall RMS re-projection error.
-
-The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
-views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See
-calibrateCamera() for other detailed explanations.
-@sa
- calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
+ TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) )
*/
-CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints,
- InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
- InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
- OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
- OutputArray newObjPoints,
- OutputArray stdDeviationsIntrinsics,
- OutputArray stdDeviationsExtrinsics,
- OutputArray stdDeviationsObjPoints,
- OutputArray perViewErrors,
- int flags = 0, TermCriteria criteria = TermCriteria(
- TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
-
-/** @overload */
-CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints,
- InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
+CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
+ InputArrayOfArrays imagePoints, Size imageSize,
InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
- OutputArray newObjPoints,
int flags = 0, TermCriteria criteria = TermCriteria(
TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
-/** @brief Computes useful camera characteristics from the camera matrix.
+/** @brief Computes useful camera characteristics from the camera intrinsic matrix.
-@param cameraMatrix Input camera matrix that can be estimated by calibrateCamera or
+@param cameraMatrix Input camera intrinsic matrix that can be estimated by calibrateCamera or
stereoCalibrate .
@param imageSize Input image size in pixels.
@param apertureWidth Physical width in mm of the sensor.
@@ -1605,98 +1657,125 @@ CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSi
CV_OUT double& focalLength, CV_OUT Point2d& principalPoint,
CV_OUT double& aspectRatio );
-/** @brief Calibrates the stereo camera.
+/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters
+for each of the two cameras and the extrinsic parameters between the two cameras.
-@param objectPoints Vector of vectors of the calibration pattern points.
+@param objectPoints Vector of vectors of the calibration pattern points. The same structure as
+in @ref calibrateCamera. For each pattern view, both cameras need to see the same object
+points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be
+equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to
+be equal for each i.
@param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
-observed by the first camera.
+observed by the first camera. The same structure as in @ref calibrateCamera.
@param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
-observed by the second camera.
-@param cameraMatrix1 Input/output first camera matrix:
-\f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If
-any of CALIB_USE_INTRINSIC_GUESS , CALIB_FIX_ASPECT_RATIO ,
-CALIB_FIX_INTRINSIC , or CALIB_FIX_FOCAL_LENGTH are specified, some or all of the
-matrix components must be initialized. See the flags description for details.
-@param distCoeffs1 Input/output vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. The output vector length depends on the flags.
-@param cameraMatrix2 Input/output second camera matrix. The parameter is similar to cameraMatrix1
-@param distCoeffs2 Input/output lens distortion coefficients for the second camera. The parameter
-is similar to distCoeffs1 .
-@param imageSize Size of the image used only to initialize intrinsic camera matrix.
-@param R Output rotation matrix between the 1st and the 2nd camera coordinate systems.
-@param T Output translation vector between the coordinate systems of the cameras.
+observed by the second camera. The same structure as in @ref calibrateCamera.
+@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in
+@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
+@param distCoeffs1 Input/output vector of distortion coefficients, the same as in
+@ref calibrateCamera.
+@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for
+cameraMatrix1.
+@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See
+description for distCoeffs1.
+@param imageSize Size of the image used only to initialize the camera intrinsic matrices.
+@param R Output rotation matrix. Together with the translation vector T, this matrix brings
+points given in the first camera's coordinate system to points in the second camera's
+coordinate system. In more technical terms, the tuple of R and T performs a change of basis
+from the first camera's coordinate system to the second camera's coordinate system. Due to its
+duality, this tuple is equivalent to the position of the first camera with respect to the
+second camera coordinate system.
+@param T Output translation vector, see description above.
@param E Output essential matrix.
@param F Output fundamental matrix.
@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
@param flags Different flags that may be zero or a combination of the following values:
-- **CALIB_FIX_INTRINSIC** Fix cameraMatrix? and distCoeffs? so that only R, T, E , and F
+- @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F
matrices are estimated.
-- **CALIB_USE_INTRINSIC_GUESS** Optimize some or all of the intrinsic parameters
+- @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters
according to the specified flags. Initial values are provided by the user.
-- **CALIB_USE_EXTRINSIC_GUESS** R, T contain valid initial values that are optimized further.
-Otherwise R, T are initialized to the median value of the pattern views (each dimension separately).
-- **CALIB_FIX_PRINCIPAL_POINT** Fix the principal points during the optimization.
-- **CALIB_FIX_FOCAL_LENGTH** Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ .
-- **CALIB_FIX_ASPECT_RATIO** Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$
+- @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further.
+Otherwise R and T are initialized to the median value of the pattern views (each dimension separately).
+- @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization.
+- @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ .
+- @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$
.
-- **CALIB_SAME_FOCAL_LENGTH** Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ .
-- **CALIB_ZERO_TANGENT_DIST** Set tangential distortion coefficients for each camera to
+- @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ .
+- @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to
zeros and fix there.
-- **CALIB_FIX_K1,...,CALIB_FIX_K6** Do not change the corresponding radial
-distortion coefficient during the optimization. If CALIB_USE_INTRINSIC_GUESS is set,
+- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial
+distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set,
the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
-- **CALIB_RATIONAL_MODEL** Enable coefficients k4, k5, and k6. To provide the backward
+- @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward
compatibility, this extra flag should be explicitly specified to make the calibration
function use the rational model and return 8 coefficients. If the flag is not set, the
function computes and returns only 5 distortion coefficients.
-- **CALIB_THIN_PRISM_MODEL** Coefficients s1, s2, s3 and s4 are enabled. To provide the
+- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
backward compatibility, this extra flag should be explicitly specified to make the
calibration function use the thin prism model and return 12 coefficients. If the flag is not
set, the function computes and returns only 5 distortion coefficients.
-- **CALIB_FIX_S1_S2_S3_S4** The thin prism distortion coefficients are not changed during
-the optimization. If CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
+- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
+the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
-- **CALIB_TILTED_MODEL** Coefficients tauX and tauY are enabled. To provide the
+- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
backward compatibility, this extra flag should be explicitly specified to make the
calibration function use the tilted sensor model and return 14 coefficients. If the flag is not
set, the function computes and returns only 5 distortion coefficients.
-- **CALIB_FIX_TAUX_TAUY** The coefficients of the tilted sensor model are not changed during
-the optimization. If CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
+- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
+the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
supplied distCoeffs matrix is used. Otherwise, it is set to 0.
@param criteria Termination criteria for the iterative optimization algorithm.
-The function estimates transformation between two cameras making a stereo pair. If you have a stereo
-camera where the relative position and orientation of two cameras is fixed, and if you computed
-poses of an object relative to the first camera and to the second camera, (R1, T1) and (R2, T2),
-respectively (this can be done with solvePnP ), then those poses definitely relate to each other.
-This means that, given ( \f$R_1\f$,\f$T_1\f$ ), it should be possible to compute ( \f$R_2\f$,\f$T_2\f$ ). You only
-need to know the position and orientation of the second camera relative to the first camera. This is
-what the described function does. It computes ( \f$R\f$,\f$T\f$ ) so that:
+The function estimates the transformation between two cameras making a stereo pair. If one computes
+the poses of an object relative to the first camera and to the second camera,
+( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the
+relative position and orientation between the two cameras are fixed, then those poses definitely
+relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the
+two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is
+given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that:
+
+\f[R_2=R R_1\f]
+\f[T_2=R T_1 + T.\f]
+
+Therefore, one can compute the coordinate representation of a 3D point for the second camera's
+coordinate system when given the point's coordinate representation in the first camera's coordinate
+system:
+
+\f[\begin{bmatrix}
+X_2 \\
+Y_2 \\
+Z_2 \\
+1
+\end{bmatrix} = \begin{bmatrix}
+R & T \\
+0 & 1
+\end{bmatrix} \begin{bmatrix}
+X_1 \\
+Y_1 \\
+Z_1 \\
+1
+\end{bmatrix}.\f]
-\f[R_2=R*R_1\f]
-\f[T_2=R*T_1 + T,\f]
Optionally, it computes the essential matrix E:
-\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} *R\f]
+\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f]
-where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . And the function
-can also compute the fundamental matrix F:
+where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ .
+And the function can also compute the fundamental matrix F:
-\f[F = cameraMatrix2^{-T} E cameraMatrix1^{-1}\f]
+\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f]
Besides the stereo-related information, the function can also perform a full calibration of each of
-two cameras. However, due to the high dimensionality of the parameter space and noise in the input
-data, the function can diverge from the correct solution. If the intrinsic parameters can be
+the two cameras. However, due to the high dimensionality of the parameter space and noise in the
+input data, the function can diverge from the correct solution. If the intrinsic parameters can be
estimated with high accuracy for each of the cameras individually (for example, using
-calibrateCamera ), you are recommended to do so and then pass CALIB_FIX_INTRINSIC flag to the
+calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the
function along with the computed intrinsic parameters. Otherwise, if all the parameters are
estimated at once, it makes sense to restrict some parameters, for example, pass
-CALIB_SAME_FOCAL_LENGTH and CALIB_ZERO_TANGENT_DIST flags, which is usually a
+ @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a
reasonable assumption.
-Similarly to calibrateCamera , the function minimizes the total re-projection error for all the
+Similarly to calibrateCamera, the function minimizes the total re-projection error for all the
points in all the available views from both cameras. The function returns the final value of the
re-projection error.
*/
@@ -1719,21 +1798,31 @@ CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
/** @brief Computes rectification transforms for each head of a calibrated stereo camera.
-@param cameraMatrix1 First camera matrix.
+@param cameraMatrix1 First camera intrinsic matrix.
@param distCoeffs1 First camera distortion parameters.
-@param cameraMatrix2 Second camera matrix.
+@param cameraMatrix2 Second camera intrinsic matrix.
@param distCoeffs2 Second camera distortion parameters.
@param imageSize Size of the image used for stereo calibration.
-@param R Rotation matrix from the coordinate system of the first camera to the second.
-@param T Translation vector from the coordinate system of the first camera to the second.
-@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera.
-@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera.
+@param R Rotation matrix from the coordinate system of the first camera to the second camera,
+see @ref stereoCalibrate.
+@param T Translation vector from the coordinate system of the first camera to the second camera,
+see @ref stereoCalibrate.
+@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix
+brings points given in the unrectified first camera's coordinate system to points in the rectified
+first camera's coordinate system. In more technical terms, it performs a change of basis from the
+unrectified first camera's coordinate system to the rectified first camera's coordinate system.
+@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix
+brings points given in the unrectified second camera's coordinate system to points in the rectified
+second camera's coordinate system. In more technical terms, it performs a change of basis from the
+unrectified second camera's coordinate system to the rectified second camera's coordinate system.
@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
-camera.
+camera, i.e. it projects points given in the rectified first camera coordinate system into the
+rectified first camera's image.
@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
-camera.
-@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see reprojectImageTo3D ).
-@param flags Operation flags that may be zero or CALIB_ZERO_DISPARITY . If the flag is set,
+camera, i.e. it projects points given in the rectified first camera coordinate system into the
+rectified second camera's image.
+@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D).
+@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set,
the function makes the principal points of each camera have the same pixel coordinates in the
rectified views. And if the flag is not set, the function may still shift the images in the
horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
@@ -1743,11 +1832,11 @@ scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that
images are zoomed and shifted so that only valid pixels are visible (no black areas after
rectification). alpha=1 means that the rectified image is decimated and shifted so that all the
pixels from the original images from the cameras are retained in the rectified images (no source
-image pixels are lost). Obviously, any intermediate value yields an intermediate result between
+image pixels are lost). Any intermediate value yields an intermediate result between
those two extreme cases.
@param newImageSize New image resolution after rectification. The same size should be passed to
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
+is passed (default), it is set to the original imageSize . Setting it to a larger value can help you
preserve details in the original image, especially when there is a big radial distortion.
@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
@@ -1763,27 +1852,43 @@ as input. As output, it provides two rotation matrices and also two projection m
coordinates. The function distinguishes the following two cases:
- **Horizontal stereo**: the first and the second camera views are shifted relative to each other
- mainly along the x axis (with possible small vertical shift). In the rectified images, the
+ mainly along the x-axis (with possible small vertical shift). In the rectified images, the
corresponding epipolar lines in the left and right cameras are horizontal and have the same
y-coordinate. P1 and P2 look like:
- \f[\texttt{P1} = \begin{bmatrix} f & 0 & cx_1 & 0 \\ 0 & f & cy & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix}\f]
+ \f[\texttt{P1} = \begin{bmatrix}
+ f & 0 & cx_1 & 0 \\
+ 0 & f & cy & 0 \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix}\f]
- \f[\texttt{P2} = \begin{bmatrix} f & 0 & cx_2 & T_x*f \\ 0 & f & cy & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix} ,\f]
+ \f[\texttt{P2} = \begin{bmatrix}
+ f & 0 & cx_2 & T_x*f \\
+ 0 & f & cy & 0 \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix} ,\f]
where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if
- CALIB_ZERO_DISPARITY is set.
+ @ref CALIB_ZERO_DISPARITY is set.
- **Vertical stereo**: the first and the second camera views are shifted relative to each other
- mainly in vertical direction (and probably a bit in the horizontal direction too). The epipolar
+ mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar
lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like:
- \f[\texttt{P1} = \begin{bmatrix} f & 0 & cx & 0 \\ 0 & f & cy_1 & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix}\f]
+ \f[\texttt{P1} = \begin{bmatrix}
+ f & 0 & cx & 0 \\
+ 0 & f & cy_1 & 0 \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix}\f]
- \f[\texttt{P2} = \begin{bmatrix} f & 0 & cx & 0 \\ 0 & f & cy_2 & T_y*f \\ 0 & 0 & 1 & 0 \end{bmatrix} ,\f]
+ \f[\texttt{P2} = \begin{bmatrix}
+ f & 0 & cx & 0 \\
+ 0 & f & cy_2 & T_y*f \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix},\f]
- where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if CALIB_ZERO_DISPARITY is
- set.
+ where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if
+ @ref CALIB_ZERO_DISPARITY is set.
As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera
matrices. The matrices, together with R1 and R2 , can then be passed to initUndistortRectifyMap to
@@ -1851,12 +1956,11 @@ CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distC
OutputArray Q, double alpha, Size newImgSize,
CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
-/** @brief Returns the new camera matrix based on the free scaling parameter.
+/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter.
-@param cameraMatrix Input camera matrix.
+@param cameraMatrix Input camera intrinsic matrix.
@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of
-4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are
+\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
assumed.
@param imageSize Original image size.
@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are
@@ -1865,17 +1969,17 @@ stereoRectify for details.
@param newImgSize 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 stereoRectify .
-@param centerPrincipalPoint Optional flag that indicates whether in the new camera matrix the
+@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the
principal point should be at the image center or not. By default, the principal point is chosen to
best fit a subset of the source image (determined by alpha) to the corrected image.
-@return new_camera_matrix Output new camera matrix.
+@return new_camera_matrix Output new camera intrinsic matrix.
-The function computes and returns the optimal new camera matrix based on the free scaling parameter.
+The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter.
By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original
image pixels if there is valuable information in the corners alpha=1 , or get something in between.
When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to
-"virtual" pixels outside of the captured distorted image. The original camera matrix, distortion
-coefficients, the computed new camera matrix, and newImageSize should be passed to
+"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion
+coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to
initUndistortRectifyMap to produce the maps for remap .
*/
CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs,
@@ -1887,23 +1991,23 @@ CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray
@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point
expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
-This is a vector (`vector<Mat>`) that contains the rotation matrices for all the transformations
-from gripper frame to robot base frame.
+This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
+for all the transformations from gripper frame to robot base frame.
@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point
expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
-This is a vector (`vector<Mat>`) that contains the translation vectors for all the transformations
+This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
from gripper frame to robot base frame.
@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
-This is a vector (`vector<Mat>`) that contains the rotation matrices for all the transformations
-from calibration target frame to camera frame.
+This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
+for all the transformations from calibration target frame to camera frame.
@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
-This is a vector (`vector<Mat>`) that contains the translation vectors for all the transformations
+This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
from calibration target frame to camera frame.
-@param[out] R_cam2gripper Estimated rotation part extracted from the homogeneous matrix that transforms a point
+@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
-@param[out] t_cam2gripper Estimated translation part extracted from the homogeneous matrix that transforms a point
+@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod
@@ -2055,17 +2159,18 @@ CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst );
floating-point (single or double precision).
@param points2 Array of the second image points of the same size and format as points1 .
@param method Method for computing a fundamental matrix.
-- **CV_FM_7POINT** for a 7-point algorithm. \f$N = 7\f$
-- **CV_FM_8POINT** for an 8-point algorithm. \f$N \ge 8\f$
-- **CV_FM_RANSAC** for the RANSAC algorithm. \f$N \ge 8\f$
-- **CV_FM_LMEDS** for the LMedS algorithm. \f$N \ge 8\f$
+- @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$
+- @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$
+- @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$
+- @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$
@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar
line in pixels, beyond which the point is considered an outlier and is not used for computing the
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
point localization, image resolution, and the image noise.
@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level
of confidence (probability) that the estimated matrix is correct.
-@param mask
+@param[out] mask optional output mask
+@param maxIters The maximum number of robust method iterations.
The epipolar geometry is described by the following equation:
@@ -2099,6 +2204,11 @@ stereoRectifyUncalibrated to compute the rectification transformation. :
findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
@endcode
*/
+CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
+ int method, double ransacReprojThreshold, double confidence,
+ int maxIters, OutputArray mask = noArray() );
+
+/** @overload */
CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
int method = FM_RANSAC,
double ransacReprojThreshold = 3., double confidence = 0.99,
@@ -2114,12 +2224,15 @@ CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
be floating-point (single or double precision).
@param points2 Array of the second image points of the same size and format as points1 .
-@param cameraMatrix Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
Note that this function assumes that points1 and points2 are feature points from cameras with the
-same camera matrix.
+same camera intrinsic matrix. If this assumption does not hold for your use case, use
+`undistortPoints()` with `P = cv::NoArray()` for both cameras to transform image points
+to normalized image coordinates, which are valid for the identity camera intrinsic matrix. When
+passing these coordinates, pass the identity matrix for this parameter.
@param method Method for computing an essential matrix.
-- **RANSAC** for the RANSAC algorithm.
-- **LMEDS** for the LMedS algorithm.
+- @ref RANSAC for the RANSAC algorithm.
+- @ref LMEDS for the LMedS algorithm.
@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
confidence (probability) that the estimated matrix is correct.
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
@@ -2151,8 +2264,8 @@ be floating-point (single or double precision).
are feature points from cameras with same focal length and principal point.
@param pp principal point of the camera.
@param method Method for computing a fundamental matrix.
-- **RANSAC** for the RANSAC algorithm.
-- **LMEDS** for the LMedS algorithm.
+- @ref RANSAC for the RANSAC algorithm.
+- @ref LMEDS for the LMedS algorithm.
@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
line in pixels, beyond which the point is considered an outlier and is not used for computing the
final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
@@ -2162,10 +2275,10 @@ confidence (probability) that the estimated matrix is correct.
@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
for the other points. The array is computed only in the RANSAC and LMedS methods.
-This function differs from the one above that it computes camera matrix from focal length and
+This function differs from the one above that it computes camera intrinsic matrix from focal length and
principal point:
-\f[K =
+\f[A =
\begin{bmatrix}
f & 0 & x_{pp} \\
0 & f & y_{pp} \\
@@ -2184,35 +2297,47 @@ CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
@param R2 Another possible rotation matrix.
@param t One possible translation.
-This function decompose an essential matrix E using svd decomposition @cite HartleyZ00 . Generally 4
-possible poses exists for a given E. They are \f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. By
-decomposing E, you can only get the direction of the translation, so the function returns unit t.
+This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In
+general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$,
+\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$.
+
+If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image
+points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples
+\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first
+camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one
+can only get the direction of the translation. For this reason, the translation t is returned with
+unit length.
*/
CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t );
-/** @brief Recover relative camera rotation and translation from an estimated essential matrix and the
-corresponding points in two images, using cheirality check. Returns the number of inliers which pass
-the check.
+/** @brief Recovers the relative camera rotation and the translation from an estimated essential
+matrix and the corresponding points in two images, using cheirality check. Returns the number of
+inliers that pass the check.
@param E The input essential matrix.
@param points1 Array of N 2D points from the first image. The point coordinates should be
floating-point (single or double precision).
@param points2 Array of the second image points of the same size and format as points1 .
-@param cameraMatrix Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
Note that this function assumes that points1 and points2 are feature points from cameras with the
-same camera matrix.
-@param R Recovered relative rotation.
-@param t Recovered relative translation.
-@param mask Input/output mask for inliers in points1 and points2.
-: If it is not empty, then it marks inliers in points1 and points2 for then given essential
-matrix E. Only these inliers will be used to recover pose. In the output mask only inliers
-which pass the cheirality check.
-This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible
-pose hypotheses by doing cheirality check. The cheirality check basically means that the
-triangulated 3D points should have positive depth. Some details can be found in @cite Nister03 .
-
-This function can be used to process output E and mask from findEssentialMat. In this scenario,
-points1 and points2 are the same input for findEssentialMat. :
+same camera intrinsic matrix.
+@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
+that performs a change of basis from the first camera's coordinate system to the second camera's
+coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
+described below.
+@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
+therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
+length.
+@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
+inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
+recover pose. In the output mask only inliers which pass the cheirality check.
+
+This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
+possible pose hypotheses by doing cheirality check. The cheirality check means that the
+triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
+
+This function can be used to process the output E and mask from @ref findEssentialMat. In this
+scenario, points1 and points2 are the same input for findEssentialMat.:
@code
// Example. Estimation of fundamental matrix using the RANSAC algorithm
int point_count = 100;
@@ -2244,20 +2369,24 @@ CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray point
@param points1 Array of N 2D points from the first image. The point coordinates should be
floating-point (single or double precision).
@param points2 Array of the second image points of the same size and format as points1 .
-@param R Recovered relative rotation.
-@param t Recovered relative translation.
+@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
+that performs a change of basis from the first camera's coordinate system to the second camera's
+coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
+description below.
+@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
+therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
+length.
@param focal Focal length of the camera. Note that this function assumes that points1 and points2
are feature points from cameras with same focal length and principal point.
@param pp principal point of the camera.
-@param mask Input/output mask for inliers in points1 and points2.
-: If it is not empty, then it marks inliers in points1 and points2 for then given essential
-matrix E. Only these inliers will be used to recover pose. In the output mask only inliers
-which pass the cheirality check.
+@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
+inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
+recover pose. In the output mask only inliers which pass the cheirality check.
-This function differs from the one above that it computes camera matrix from focal length and
+This function differs from the one above that it computes camera intrinsic matrix from focal length and
principal point:
-\f[K =
+\f[A =
\begin{bmatrix}
f & 0 & x_{pp} \\
0 & f & y_{pp} \\
@@ -2274,19 +2403,26 @@ CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray point
@param points1 Array of N 2D points from the first image. The point coordinates should be
floating-point (single or double precision).
@param points2 Array of the second image points of the same size and format as points1.
-@param cameraMatrix Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
Note that this function assumes that points1 and points2 are feature points from cameras with the
-same camera matrix.
-@param R Recovered relative rotation.
-@param t Recovered relative translation.
-@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite points).
-@param mask Input/output mask for inliers in points1 and points2.
-: If it is not empty, then it marks inliers in points1 and points2 for then given essential
-matrix E. Only these inliers will be used to recover pose. In the output mask only inliers
-which pass the cheirality check.
-@param triangulatedPoints 3d points which were reconstructed by triangulation.
+same camera intrinsic matrix.
+@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
+that performs a change of basis from the first camera's coordinate system to the second camera's
+coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
+description below.
+@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
+therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
+length.
+@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite
+points).
+@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
+inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
+recover pose. In the output mask only inliers which pass the cheirality check.
+@param triangulatedPoints 3D points which were reconstructed by triangulation.
+
+This function differs from the one above that it outputs the triangulated 3D point that are used for
+the cheirality check.
*/
-
CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(),
OutputArray triangulatedPoints = noArray());
@@ -2317,22 +2453,27 @@ Line coefficients are defined up to a scale. They are normalized so that \f$a_i^
CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage,
InputArray F, OutputArray lines );
-/** @brief Reconstructs points by triangulation.
+/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using
+their observations with a stereo camera.
-@param projMatr1 3x4 projection matrix of the first camera.
-@param projMatr2 3x4 projection matrix of the second camera.
-@param projPoints1 2xN array of feature points in the first image. In case of c++ version it can
-be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
-@param projPoints2 2xN array of corresponding points in the second image. In case of c++ version
+@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points
+given in the world's coordinate system into the first image.
+@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points
+given in the world's coordinate system into the second image.
+@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version,
it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
-@param points4D 4xN array of reconstructed points in homogeneous coordinates.
-
-The function reconstructs 3-dimensional points (in homogeneous coordinates) by using their
-observations with a stereo camera. Projections matrices can be obtained from stereoRectify.
+@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++
+version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
+@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are
+returned in the world's coordinate system.
@note
Keep in mind that all input data should be of float type in order for this function to work.
+@note
+ If the projection matrices from @ref stereoRectify are used, then the returned points are
+ represented in the first camera's rectified coordinate system.
+
@sa
reprojectImageTo3D
*/
@@ -2377,7 +2518,7 @@ CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal,
//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify())
CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
int minDisparity, int numberOfDisparities,
- int SADWindowSize );
+ int blockSize );
//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost,
@@ -2387,15 +2528,16 @@ CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost
/** @brief Reprojects a disparity image to 3D space.
@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
-floating-point disparity image.
-The values of 8-bit / 16-bit signed formats are assumed to have no fractional bits.
-If the disparity is 16-bit signed format as computed by
-StereoBM/StereoSGBM/StereoBinaryBM/StereoBinarySGBM and may be other algorithms,
-it should be divided by 16 (and scaled to float) before being used here.
-@param _3dImage Output 3-channel floating-point image of the same size as disparity . Each
-element of _3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity
-map.
-@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with stereoRectify.
+floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no
+fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or
+@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before
+being used here.
+@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of
+_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one
+uses Q obtained by @ref stereoRectify, then the returned points are represented in the first
+camera's rectified coordinate system.
+@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with
+@ref stereoRectify.
@param handleMissingValues Indicates, whether the function should handle missing values (i.e.
points where the disparity was not computed). If handleMissingValues=true, then pixels with the
minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed
@@ -2407,11 +2549,20 @@ The function transforms a single-channel disparity map to a 3-channel image repr
surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it
computes:
-\f[\begin{array}{l} [X \; Y \; Z \; W]^T = \texttt{Q} *[x \; y \; \texttt{disparity} (x,y) \; 1]^T \\ \texttt{\_3dImage} (x,y) = (X/W, \; Y/W, \; Z/W) \end{array}\f]
+\f[\begin{bmatrix}
+X \\
+Y \\
+Z \\
+W
+\end{bmatrix} = Q \begin{bmatrix}
+x \\
+y \\
+\texttt{disparity} (x,y) \\
+z
+\end{bmatrix}.\f]
-The matrix Q can be an arbitrary \f$4 \times 4\f$ matrix (for example, the one computed by
-stereoRectify). To reproject a sparse set of points {(x,y,d),...} to 3D space, use
-perspectiveTransform .
+@sa
+ To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform.
*/
CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
OutputArray _3dImage, InputArray Q,
@@ -2517,8 +2668,8 @@ b_2\\
@param to Second input 2D point set containing \f$(x,y)\f$.
@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
@param method Robust method used to compute transformation. The following methods are possible:
-- cv::RANSAC - RANSAC-based robust method
-- cv::LMEDS - Least-Median robust method
+- @ref RANSAC - RANSAC-based robust method
+- @ref LMEDS - Least-Median robust method
RANSAC is the default method.
@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
a point as an inlier. Applies only to RANSAC.
@@ -2563,8 +2714,8 @@ two 2D point sets.
@param to Second input 2D point set.
@param inliers Output vector indicating which points are inliers.
@param method Robust method used to compute transformation. The following methods are possible:
-- cv::RANSAC - RANSAC-based robust method
-- cv::LMEDS - Least-Median robust method
+- @ref RANSAC - RANSAC-based robust method
+- @ref LMEDS - Least-Median robust method
RANSAC is the default method.
@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
a point as an inlier. Applies only to RANSAC.
@@ -2613,16 +2764,24 @@ Check @ref tutorial_homography "the corresponding tutorial" for more details.
/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s).
@param H The input homography matrix between two images.
-@param K The input intrinsic camera calibration matrix.
+@param K The input camera intrinsic matrix.
@param rotations Array of rotation matrices.
@param translations Array of translation matrices.
@param normals Array of plane normal matrices.
-This function extracts relative camera motion between two views observing a planar object from the
-homography H induced by the plane. The intrinsic camera matrix K must also be provided. The function
-may return up to four mathematical solution sets. At least two of the solutions may further be
-invalidated if point correspondences are available by applying positive depth constraint (all points
-must be in front of the camera). The decomposition method is described in detail in @cite Malis .
+This function extracts relative camera motion between two views of a planar object and returns up to
+four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of
+the homography matrix H is described in detail in @cite Malis.
+
+If the homography H, induced by the plane, gives the constraint
+\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points
+\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and
+translations[k] is a change of basis from the source camera's coordinate system to the destination
+camera's coordinate system. However, by decomposing H, one can only get the translation normalized
+by the (typically unknown) depth of the scene, i.e. its direction but with normalized length.
+
+If point correspondences are available, at least two solutions may further be invalidated, by
+applying positive depth constraint, i.e. all points must be in front of the camera.
*/
CV_EXPORTS_W int decomposeHomographyMat(InputArray H,
InputArray K,
@@ -2802,8 +2961,8 @@ public:
the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
- P1 and P2 values are shown (like 8\*number_of_image_channels\*SADWindowSize\*SADWindowSize and
- 32\*number_of_image_channels\*SADWindowSize\*SADWindowSize , respectively).
+ P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and
+ 32\*number_of_image_channels\*blockSize\*blockSize , respectively).
@param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
disparity check. Set it to a non-positive value to disable the check.
@param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
@@ -2833,209 +2992,6 @@ public:
int mode = StereoSGBM::MODE_SGBM);
};
-
-//! cv::undistort mode
-enum UndistortTypes
-{
- PROJ_SPHERICAL_ORTHO = 0,
- PROJ_SPHERICAL_EQRECT = 1
-};
-
-/** @brief Transforms an image to compensate for lens distortion.
-
-The function transforms an image to compensate radial and tangential lens distortion.
-
-The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap
-(with bilinear interpolation). See the former function for details of the transformation being
-performed.
-
-Those pixels in the destination image, for which there is no correspondent pixels in the source
-image, are filled with zeros (black color).
-
-A particular subset of the source image that will be visible in the corrected image can be regulated
-by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate
-newCameraMatrix depending on your requirements.
-
-The camera matrix and the distortion parameters can be determined using #calibrateCamera. If
-the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
-f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
-the same.
-
-@param src Input (distorted) image.
-@param dst Output (corrected) image that has the same size and type as src .
-@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
-@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
-of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
-@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
-cameraMatrix but you may additionally scale and shift the result by using a different matrix.
- */
-CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
- InputArray cameraMatrix,
- InputArray distCoeffs,
- InputArray newCameraMatrix = noArray() );
-
-/** @brief Computes the undistortion and rectification transformation map.
-
-The function computes the joint undistortion and rectification transformation and represents the
-result in the form of maps for remap. The undistorted image looks like original, as if it is
-captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
-monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
-#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
-newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
-
-Also, this new camera is oriented differently in the coordinate space, according to R. That, for
-example, helps to align two heads of a stereo camera so that the epipolar lines on both images
-become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
-
-The function actually builds the maps for the inverse mapping algorithm that is used by remap. That
-is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
-computes the corresponding coordinates in the source image (that is, in the original image from
-camera). The following process is applied:
-\f[
-\begin{array}{l}
-x \leftarrow (u - {c'}_x)/{f'}_x \\
-y \leftarrow (v - {c'}_y)/{f'}_y \\
-{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\
-x' \leftarrow X/W \\
-y' \leftarrow Y/W \\
-r^2 \leftarrow x'^2 + y'^2 \\
-x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
-+ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\
-y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
-+ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
-s\vecthree{x'''}{y'''}{1} =
-\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
-{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
-{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
-map_x(u,v) \leftarrow x''' f_x + c_x \\
-map_y(u,v) \leftarrow y''' f_y + c_y
-\end{array}
-\f]
-where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
-are the distortion coefficients.
-
-In case of a stereo camera, this function is called twice: once for each camera head, after
-stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera
-was not calibrated, it is still possible to compute the rectification transformations directly from
-the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes
-homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
-space. R can be computed from H as
-\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
-where cameraMatrix can be chosen arbitrarily.
-
-@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
-@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
-of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
-@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
-computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
-is assumed. In cvInitUndistortMap R assumed to be an identity matrix.
-@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
-@param size Undistorted image size.
-@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
-@param map1 The first output map.
-@param map2 The second output map.
- */
-CV_EXPORTS_W
-void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs,
- InputArray R, InputArray newCameraMatrix,
- Size size, int m1type, OutputArray map1, OutputArray map2);
-
-//! initializes maps for #remap for wide-angle
-CV_EXPORTS
-float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
- Size imageSize, int destImageWidth,
- int m1type, OutputArray map1, OutputArray map2,
- enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
-static inline
-float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
- Size imageSize, int destImageWidth,
- int m1type, OutputArray map1, OutputArray map2,
- int projType, double alpha = 0)
-{
- return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth,
- m1type, map1, map2, (UndistortTypes)projType, alpha);
-}
-
-/** @brief Returns the default new camera matrix.
-
-The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
-centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
-
-In the latter case, the new camera matrix will be:
-
-\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f]
-
-where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
-
-By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not
-move the principal point. However, when you work with stereo, it is important to move the principal
-points in both views to the same y-coordinate (which is required by most of stereo correspondence
-algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
-each view where the principal points are located at the center.
-
-@param cameraMatrix Input camera matrix.
-@param imgsize Camera view image size in pixels.
-@param centerPrincipalPoint Location of the principal point in the new camera matrix. The
-parameter indicates whether this location should be at the image center or not.
- */
-CV_EXPORTS_W
-Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(),
- bool centerPrincipalPoint = false);
-
-/** @brief Computes the ideal point coordinates from the observed point coordinates.
-
-The function is similar to #undistort and #initUndistortRectifyMap but it operates on a
-sparse set of points instead of a raster image. Also the function performs a reverse transformation
-to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
-planar object, it does, up to a translation vector, if the proper R is specified.
-
-For each observed point coordinate \f$(u, v)\f$ the function computes:
-\f[
-\begin{array}{l}
-x^{"} \leftarrow (u - c_x)/f_x \\
-y^{"} \leftarrow (v - c_y)/f_y \\
-(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
-{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
-x \leftarrow X/W \\
-y \leftarrow Y/W \\
-\text{only performed if P is specified:} \\
-u' \leftarrow x {f'}_x + {c'}_x \\
-v' \leftarrow y {f'}_y + {c'}_y
-\end{array}
-\f]
-
-where *undistort* is an approximate iterative algorithm that estimates the normalized original
-point coordinates out of the normalized distorted point coordinates ("normalized" means that the
-coordinates do not depend on the camera matrix).
-
-The function can be used for both a stereo camera head or a monocular camera (when R is empty).
-@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or
-vector\<Point2f\> ).
-@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\<Point2f\> ) after undistortion and reverse perspective
-transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.
-@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
-@param distCoeffs Input vector of distortion coefficients
-\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
-of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
-@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
-#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
-@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by
-#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used.
- */
-CV_EXPORTS_W
-void undistortPoints(InputArray src, OutputArray dst,
- InputArray cameraMatrix, InputArray distCoeffs,
- InputArray R = noArray(), InputArray P = noArray());
-/** @overload
- @note Default version of #undistortPoints does 5 iterations to compute undistorted points.
- */
-CV_EXPORTS_AS(undistortPointsIter)
-void undistortPoints(InputArray src, OutputArray dst,
- InputArray cameraMatrix, InputArray distCoeffs,
- InputArray R, InputArray P, TermCriteria criteria);
-
//! @} calib3d
/** @brief The methods in this namespace use a so-called fisheye camera model.
@@ -3056,7 +3012,8 @@ namespace fisheye
CALIB_FIX_K3 = 1 << 6,
CALIB_FIX_K4 = 1 << 7,
CALIB_FIX_INTRINSIC = 1 << 8,
- CALIB_FIX_PRINCIPAL_POINT = 1 << 9
+ CALIB_FIX_PRINCIPAL_POINT = 1 << 9,
+ CALIB_ZERO_DISPARITY = 1 << 10
};
/** @brief Projects points using fisheye model
@@ -3066,8 +3023,8 @@ namespace fisheye
@param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or
vector\<Point2f\>.
@param affine
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param alpha The skew coefficient.
@param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect
to components of the focal lengths, coordinates of the principal point, distortion coefficients,
@@ -3090,12 +3047,12 @@ namespace fisheye
@param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is
the number of points in the view.
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param alpha The skew coefficient.
@param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
- Note that the function assumes the camera matrix of the undistorted points to be identity.
+ Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity.
This means if you want to transform back points undistorted with undistortPoints() you have to
multiply them with \f$P^{-1}\f$.
*/
@@ -3105,11 +3062,11 @@ namespace fisheye
@param distorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is the
number of points in the view.
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
1-channel or 1x1 3-channel
- @param P New camera matrix (3x3) or new projection matrix (3x4)
+ @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
@param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
*/
CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted,
@@ -3118,11 +3075,11 @@ namespace fisheye
/** @brief Computes undistortion and rectification maps for image transform by cv::remap(). If D is empty zero
distortion is used, if R or P is empty identity matrixes are used.
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
1-channel or 1x1 3-channel
- @param P New camera matrix (3x3) or new projection matrix (3x4)
+ @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
@param size Undistorted image size.
@param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See convertMaps()
for details.
@@ -3136,9 +3093,9 @@ namespace fisheye
@param distorted image with fisheye lens distortion.
@param undistorted Output image with compensated fisheye lens distortion.
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
- @param Knew Camera matrix of the distorted image. By default, it is the identity matrix but you
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
+ @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you
may additionally scale and shift the result by using a different matrix.
@param new_size the new size
@@ -3163,14 +3120,14 @@ namespace fisheye
CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted,
InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size());
- /** @brief Estimates new camera matrix for undistortion or rectification.
+ /** @brief Estimates new camera intrinsic matrix for undistortion or rectification.
- @param K Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{_1}\f$.
+ @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
@param image_size Size of the image
- @param D Input vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
1-channel or 1x1 3-channel
- @param P New camera matrix (3x3) or new projection matrix (3x4)
+ @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
@param balance Sets the new focal length in range between the min focal length and the max focal
length. Balance is in range of [0, 1].
@param new_size the new size
@@ -3186,12 +3143,12 @@ namespace fisheye
@param imagePoints vector of vectors of the projections of calibration pattern points.
imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to
objectPoints[i].size() for each i.
- @param image_size Size of the image used only to initialize the intrinsic camera matrix.
- @param K Output 3x3 floating-point camera matrix
- \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . If
- fisheye::CALIB_USE_INTRINSIC_GUESS/ is specified, some or all of fx, fy, cx, cy must be
+ @param image_size Size of the image used only to initialize the camera intrinsic matrix.
+ @param K Output 3x3 floating-point camera intrinsic matrix
+ \f$\cameramatrix{A}\f$ . If
+ @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be
initialized before calling the function.
- @param D Output vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$.
+ @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$.
@param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view.
That is, each k-th rotation vector together with the corresponding k-th translation vector (see
the next output parameter description) brings the calibration pattern from the model coordinate
@@ -3199,17 +3156,17 @@ namespace fisheye
position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
@param tvecs Output vector of translation vectors estimated for each pattern view.
@param flags Different flags that may be zero or a combination of the following values:
- - **fisheye::CALIB_USE_INTRINSIC_GUESS** cameraMatrix contains valid initial values of
+ - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
center ( imageSize is used), and focal distances are computed in a least-squares fashion.
- - **fisheye::CALIB_RECOMPUTE_EXTRINSIC** Extrinsic will be recomputed after each iteration
+ - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
of intrinsic optimization.
- - **fisheye::CALIB_CHECK_COND** The functions will check validity of condition number.
- - **fisheye::CALIB_FIX_SKEW** Skew coefficient (alpha) is set to zero and stay zero.
- - **fisheye::CALIB_FIX_K1..fisheye::CALIB_FIX_K4** Selected distortion coefficients
+ - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
+ - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
+ - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients
are set to zeros and stay zero.
- - **fisheye::CALIB_FIX_PRINCIPAL_POINT** The principal point is not changed during the global
-optimization. It stays at the center or at a different location specified when CALIB_USE_INTRINSIC_GUESS is set too.
+ - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
+optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
@param criteria Termination criteria for the iterative optimization algorithm.
*/
CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size,
@@ -3218,9 +3175,9 @@ optimization. It stays at the center or at a different location specified when C
/** @brief Stereo rectification for fisheye camera model
- @param K1 First camera matrix.
+ @param K1 First camera intrinsic matrix.
@param D1 First camera distortion parameters.
- @param K2 Second camera matrix.
+ @param K2 Second camera intrinsic matrix.
@param D2 Second camera distortion parameters.
@param imageSize Size of the image used for stereo calibration.
@param R Rotation matrix between the coordinate systems of the first and the second
@@ -3233,7 +3190,7 @@ optimization. It stays at the center or at a different location specified when C
@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
camera.
@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see reprojectImageTo3D ).
- @param flags Operation flags that may be zero or CALIB_ZERO_DISPARITY . If the flag is set,
+ @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set,
the function makes the principal points of each camera have the same pixel coordinates in the
rectified views. And if the flag is not set, the function may still shift the images in the
horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
@@ -3257,28 +3214,28 @@ optimization. It stays at the center or at a different location specified when C
observed by the first camera.
@param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
observed by the second camera.
- @param K1 Input/output first camera matrix:
+ @param K1 Input/output first camera intrinsic matrix:
\f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If
- any of fisheye::CALIB_USE_INTRINSIC_GUESS , fisheye::CALIB_FIX_INTRINSIC are specified,
+ any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified,
some or all of the matrix components must be initialized.
- @param D1 Input/output vector of distortion coefficients \f$(k_1, k_2, k_3, k_4)\f$ of 4 elements.
- @param K2 Input/output second camera matrix. The parameter is similar to K1 .
+ @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements.
+ @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 .
@param D2 Input/output lens distortion coefficients for the second camera. The parameter is
similar to D1 .
- @param imageSize Size of the image used only to initialize intrinsic camera matrix.
+ @param imageSize Size of the image used only to initialize camera intrinsic matrix.
@param R Output rotation matrix between the 1st and the 2nd camera coordinate systems.
@param T Output translation vector between the coordinate systems of the cameras.
@param flags Different flags that may be zero or a combination of the following values:
- - **fisheye::CALIB_FIX_INTRINSIC** Fix K1, K2? and D1, D2? so that only R, T matrices
+ - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices
are estimated.
- - **fisheye::CALIB_USE_INTRINSIC_GUESS** K1, K2 contains valid initial values of
+ - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of
fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
center (imageSize is used), and focal distances are computed in a least-squares fashion.
- - **fisheye::CALIB_RECOMPUTE_EXTRINSIC** Extrinsic will be recomputed after each iteration
+ - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
of intrinsic optimization.
- - **fisheye::CALIB_CHECK_COND** The functions will check validity of condition number.
- - **fisheye::CALIB_FIX_SKEW** Skew coefficient (alpha) is set to zero and stay zero.
- - **fisheye::CALIB_FIX_K1..4** Selected distortion coefficients are set to zeros and stay
+ - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
+ - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
+ - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay
zero.
@param criteria Termination criteria for the iterative optimization algorithm.
*/
@@ -3292,44 +3249,8 @@ optimization. It stays at the center or at a different location specified when C
} //end namespace cv
-#if 0 //def __cplusplus
-//////////////////////////////////////////////////////////////////////////////////////////
-class CV_EXPORTS CvLevMarq
-{
-public:
- CvLevMarq();
- CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria=
- cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
- bool completeSymmFlag=false );
- ~CvLevMarq();
- void init( int nparams, int nerrs, CvTermCriteria criteria=
- cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
- bool completeSymmFlag=false );
- bool update( const CvMat*& param, CvMat*& J, CvMat*& err );
- bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm );
-
- void clear();
- void step();
- enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 };
-
- cv::Ptr<CvMat> mask;
- cv::Ptr<CvMat> prevParam;
- cv::Ptr<CvMat> param;
- cv::Ptr<CvMat> J;
- cv::Ptr<CvMat> err;
- cv::Ptr<CvMat> JtJ;
- cv::Ptr<CvMat> JtJN;
- cv::Ptr<CvMat> JtErr;
- cv::Ptr<CvMat> JtJV;
- cv::Ptr<CvMat> JtJW;
- double prevErrNorm, errNorm;
- int lambdaLg10;
- CvTermCriteria criteria;
- int state;
- int iters;
- bool completeSymmFlag;
- int solveMethod;
-};
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/calib3d/calib3d_c.h"
#endif
#endif
diff --git a/include/opencv2/calib3d/calib3d_c.h b/include/opencv2/calib3d/calib3d_c.h
index e2af07b..8ec6390 100755
--- a/include/opencv2/calib3d/calib3d_c.h
+++ b/include/opencv2/calib3d/calib3d_c.h
@@ -44,12 +44,41 @@
#ifndef OPENCV_CALIB3D_C_H
#define OPENCV_CALIB3D_C_H
-#include "opencv2/core/types_c.h"
+#include "opencv2/core/core_c.h"
#ifdef __cplusplus
extern "C" {
#endif
+/** @addtogroup calib3d_c
+ @{
+ */
+
+/****************************************************************************************\
+* Camera Calibration, Pose Estimation and Stereo *
+\****************************************************************************************/
+
+typedef struct CvPOSITObject CvPOSITObject;
+
+/* Allocates and initializes CvPOSITObject structure before doing cvPOSIT */
+CVAPI(CvPOSITObject*) cvCreatePOSITObject( CvPoint3D32f* points, int point_count );
+
+
+/* Runs POSIT (POSe from ITeration) algorithm for determining 3d position of
+ an object given its model and projection in a weak-perspective case */
+CVAPI(void) cvPOSIT( CvPOSITObject* posit_object, CvPoint2D32f* image_points,
+ double focal_length, CvTermCriteria criteria,
+ float* rotation_matrix, float* translation_vector);
+
+/* Releases CvPOSITObject structure */
+CVAPI(void) cvReleasePOSITObject( CvPOSITObject** posit_object );
+
+/* updates the number of RANSAC iterations */
+CVAPI(int) cvRANSACUpdateNumIters( double p, double err_prob,
+ int model_points, int max_iters );
+
+CVAPI(void) cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst );
+
/* Calculates fundamental matrix given a set of corresponding points */
#define CV_FM_7POINT 1
#define CV_FM_8POINT 2
@@ -70,11 +99,136 @@ enum
CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP"
};
+CVAPI(int) cvFindFundamentalMat( const CvMat* points1, const CvMat* points2,
+ CvMat* fundamental_matrix,
+ int method CV_DEFAULT(CV_FM_RANSAC),
+ double param1 CV_DEFAULT(3.), double param2 CV_DEFAULT(0.99),
+ CvMat* status CV_DEFAULT(NULL) );
+
+/* For each input point on one of images
+ computes parameters of the corresponding
+ epipolar line on the other image */
+CVAPI(void) cvComputeCorrespondEpilines( const CvMat* points,
+ int which_image,
+ const CvMat* fundamental_matrix,
+ CvMat* correspondent_lines );
+
+/* Triangulation functions */
+
+CVAPI(void) cvTriangulatePoints(CvMat* projMatr1, CvMat* projMatr2,
+ CvMat* projPoints1, CvMat* projPoints2,
+ CvMat* points4D);
+
+CVAPI(void) cvCorrectMatches(CvMat* F, CvMat* points1, CvMat* points2,
+ CvMat* new_points1, CvMat* new_points2);
+
+
+/* Computes the optimal new camera matrix according to the free scaling parameter alpha:
+ alpha=0 - only valid pixels will be retained in the undistorted image
+ alpha=1 - all the source image pixels will be retained in the undistorted image
+*/
+CVAPI(void) cvGetOptimalNewCameraMatrix( const CvMat* camera_matrix,
+ const CvMat* dist_coeffs,
+ CvSize image_size, double alpha,
+ CvMat* new_camera_matrix,
+ CvSize new_imag_size CV_DEFAULT(cvSize(0,0)),
+ CvRect* valid_pixel_ROI CV_DEFAULT(0),
+ int center_principal_point CV_DEFAULT(0));
+
+/* Converts rotation vector to rotation matrix or vice versa */
+CVAPI(int) cvRodrigues2( const CvMat* src, CvMat* dst,
+ CvMat* jacobian CV_DEFAULT(0) );
+
+/* Finds perspective transformation between the object plane and image (view) plane */
+CVAPI(int) cvFindHomography( const CvMat* src_points,
+ const CvMat* dst_points,
+ CvMat* homography,
+ int method CV_DEFAULT(0),
+ double ransacReprojThreshold CV_DEFAULT(3),
+ CvMat* mask CV_DEFAULT(0),
+ int maxIters CV_DEFAULT(2000),
+ double confidence CV_DEFAULT(0.995));
+
+/* Computes RQ decomposition for 3x3 matrices */
+CVAPI(void) cvRQDecomp3x3( const CvMat *matrixM, CvMat *matrixR, CvMat *matrixQ,
+ CvMat *matrixQx CV_DEFAULT(NULL),
+ CvMat *matrixQy CV_DEFAULT(NULL),
+ CvMat *matrixQz CV_DEFAULT(NULL),
+ CvPoint3D64f *eulerAngles CV_DEFAULT(NULL));
+
+/* Computes projection matrix decomposition */
+CVAPI(void) cvDecomposeProjectionMatrix( const CvMat *projMatr, CvMat *calibMatr,
+ CvMat *rotMatr, CvMat *posVect,
+ CvMat *rotMatrX CV_DEFAULT(NULL),
+ CvMat *rotMatrY CV_DEFAULT(NULL),
+ CvMat *rotMatrZ CV_DEFAULT(NULL),
+ CvPoint3D64f *eulerAngles CV_DEFAULT(NULL));
+
+/* Computes d(AB)/dA and d(AB)/dB */
+CVAPI(void) cvCalcMatMulDeriv( const CvMat* A, const CvMat* B, CvMat* dABdA, CvMat* dABdB );
+
+/* Computes r3 = rodrigues(rodrigues(r2)*rodrigues(r1)),
+ t3 = rodrigues(r2)*t1 + t2 and the respective derivatives */
+CVAPI(void) cvComposeRT( const CvMat* _rvec1, const CvMat* _tvec1,
+ const CvMat* _rvec2, const CvMat* _tvec2,
+ CvMat* _rvec3, CvMat* _tvec3,
+ CvMat* dr3dr1 CV_DEFAULT(0), CvMat* dr3dt1 CV_DEFAULT(0),
+ CvMat* dr3dr2 CV_DEFAULT(0), CvMat* dr3dt2 CV_DEFAULT(0),
+ CvMat* dt3dr1 CV_DEFAULT(0), CvMat* dt3dt1 CV_DEFAULT(0),
+ CvMat* dt3dr2 CV_DEFAULT(0), CvMat* dt3dt2 CV_DEFAULT(0) );
+
+/* Projects object points to the view plane using
+ the specified extrinsic and intrinsic camera parameters */
+CVAPI(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 CV_DEFAULT(NULL), CvMat* dpdt CV_DEFAULT(NULL),
+ CvMat* dpdf CV_DEFAULT(NULL), CvMat* dpdc CV_DEFAULT(NULL),
+ CvMat* dpddist CV_DEFAULT(NULL),
+ double aspect_ratio CV_DEFAULT(0));
+
+/* Finds extrinsic camera parameters from
+ a few known corresponding point pairs and intrinsic parameters */
+CVAPI(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 CV_DEFAULT(0) );
+
+/* Computes initial estimate of the intrinsic camera parameters
+ in case of planar calibration target (e.g. chessboard) */
+CVAPI(void) cvInitIntrinsicParams2D( const CvMat* object_points,
+ const CvMat* image_points,
+ const CvMat* npoints, CvSize image_size,
+ CvMat* camera_matrix,
+ double aspect_ratio CV_DEFAULT(1.) );
+
#define CV_CALIB_CB_ADAPTIVE_THRESH 1
#define CV_CALIB_CB_NORMALIZE_IMAGE 2
#define CV_CALIB_CB_FILTER_QUADS 4
#define CV_CALIB_CB_FAST_CHECK 8
+// Performs a fast check if a chessboard is in the input image. This is a workaround to
+// a problem of cvFindChessboardCorners being slow on images with no chessboard
+// - src: input image
+// - size: chessboard size
+// Returns 1 if a chessboard can be in this image and findChessboardCorners should be called,
+// 0 if there is no chessboard, -1 in case of error
+CVAPI(int) cvCheckChessboard(IplImage* src, CvSize size);
+
+ /* Detects corners on a chessboard calibration pattern */
+CVAPI(int) cvFindChessboardCorners( const void* image, CvSize pattern_size,
+ CvPoint2D32f* corners,
+ int* corner_count CV_DEFAULT(NULL),
+ int flags CV_DEFAULT(CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE) );
+
+/* Draws individual chessboard corners or the whole chessboard detected */
+CVAPI(void) cvDrawChessboardCorners( CvArr* image, CvSize pattern_size,
+ CvPoint2D32f* corners,
+ int count, int pattern_was_found );
+
#define CV_CALIB_USE_INTRINSIC_GUESS 1
#define CV_CALIB_FIX_ASPECT_RATIO 2
#define CV_CALIB_FIX_PRINCIPAL_POINT 4
@@ -95,15 +249,138 @@ enum
#define CV_CALIB_NINTRINSIC 18
+/* Finds intrinsic and extrinsic camera parameters
+ from a few views of known calibration pattern */
+CVAPI(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 CV_DEFAULT(NULL),
+ CvMat* translation_vectors CV_DEFAULT(NULL),
+ int flags CV_DEFAULT(0),
+ CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria(
+ CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,DBL_EPSILON)) );
+
+/* Computes various useful characteristics of the camera from the data computed by
+ cvCalibrateCamera2 */
+CVAPI(void) cvCalibrationMatrixValues( const CvMat *camera_matrix,
+ CvSize image_size,
+ double aperture_width CV_DEFAULT(0),
+ double aperture_height CV_DEFAULT(0),
+ double *fovx CV_DEFAULT(NULL),
+ double *fovy CV_DEFAULT(NULL),
+ double *focal_length CV_DEFAULT(NULL),
+ CvPoint2D64f *principal_point CV_DEFAULT(NULL),
+ double *pixel_aspect_ratio CV_DEFAULT(NULL));
+
#define CV_CALIB_FIX_INTRINSIC 256
#define CV_CALIB_SAME_FOCAL_LENGTH 512
+/* Computes the transformation from one camera coordinate system to another one
+ from a few correspondent views of the same calibration target. Optionally, calibrates
+ both cameras */
+CVAPI(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 CV_DEFAULT(0), CvMat* F CV_DEFAULT(0),
+ int flags CV_DEFAULT(CV_CALIB_FIX_INTRINSIC),
+ CvTermCriteria term_crit CV_DEFAULT(cvTermCriteria(
+ CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,30,1e-6)) );
+
#define CV_CALIB_ZERO_DISPARITY 1024
+/* Computes 3D rotations (+ optional shift) for each camera coordinate system to make both
+ views parallel (=> to make all the epipolar lines horizontal or vertical) */
+CVAPI(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 CV_DEFAULT(0),
+ int flags CV_DEFAULT(CV_CALIB_ZERO_DISPARITY),
+ double alpha CV_DEFAULT(-1),
+ CvSize new_image_size CV_DEFAULT(cvSize(0,0)),
+ CvRect* valid_pix_ROI1 CV_DEFAULT(0),
+ CvRect* valid_pix_ROI2 CV_DEFAULT(0));
+
+/* Computes rectification transformations for uncalibrated pair of images using a set
+ of point correspondences */
+CVAPI(int) cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2,
+ const CvMat* F, CvSize img_size,
+ CvMat* H1, CvMat* H2,
+ double threshold CV_DEFAULT(5));
+
+
+
/* stereo correspondence parameters and functions */
+
#define CV_STEREO_BM_NORMALIZED_RESPONSE 0
#define CV_STEREO_BM_XSOBEL 1
+/* Block matching algorithm structure */
+typedef struct CvStereoBMState
+{
+ // pre-filtering (normalization of input images)
+ int preFilterType; // =CV_STEREO_BM_NORMALIZED_RESPONSE now
+ int preFilterSize; // averaging window size: ~5x5..21x21
+ int preFilterCap; // the output of pre-filtering is clipped by [-preFilterCap,preFilterCap]
+
+ // correspondence using Sum of Absolute Difference (SAD)
+ int SADWindowSize; // ~5x5..21x21
+ int minDisparity; // minimum disparity (can be negative)
+ int numberOfDisparities; // maximum disparity - minimum disparity (> 0)
+
+ // post-filtering
+ int textureThreshold; // the disparity is only computed for pixels
+ // with textured enough neighborhood
+ int uniquenessRatio; // accept the computed disparity d* only if
+ // SAD(d) >= SAD(d*)*(1 + uniquenessRatio/100.)
+ // for any d != d*+/-1 within the search range.
+ int speckleWindowSize; // disparity variation window
+ int speckleRange; // acceptable range of variation in window
+
+ int trySmallerWindows; // if 1, the results may be more accurate,
+ // at the expense of slower processing
+ CvRect roi1, roi2;
+ int disp12MaxDiff;
+
+ // temporary buffers
+ CvMat* preFilteredImg0;
+ CvMat* preFilteredImg1;
+ CvMat* slidingSumBuf;
+ CvMat* cost;
+ CvMat* disp;
+} CvStereoBMState;
+
+#define CV_STEREO_BM_BASIC 0
+#define CV_STEREO_BM_FISH_EYE 1
+#define CV_STEREO_BM_NARROW 2
+
+CVAPI(CvStereoBMState*) cvCreateStereoBMState(int preset CV_DEFAULT(CV_STEREO_BM_BASIC),
+ int numberOfDisparities CV_DEFAULT(0));
+
+CVAPI(void) cvReleaseStereoBMState( CvStereoBMState** state );
+
+CVAPI(void) cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right,
+ CvArr* disparity, CvStereoBMState* state );
+
+CVAPI(CvRect) cvGetValidDisparityROI( CvRect roi1, CvRect roi2, int minDisparity,
+ int numberOfDisparities, int SADWindowSize );
+
+CVAPI(void) cvValidateDisparity( CvArr* disparity, const CvArr* cost,
+ int minDisparity, int numberOfDisparities,
+ int disp12MaxDiff CV_DEFAULT(1) );
+
+/* Reprojects the computed disparity image to the 3D space using the specified 4x4 matrix */
+CVAPI(void) cvReprojectImageTo3D( const CvArr* disparityImage,
+ CvArr* _3dImage, const CvMat* Q,
+ int handleMissingValues CV_DEFAULT(0) );
+
+/** @} calib3d_c */
+
#ifdef __cplusplus
} // extern "C"
diff --git a/include/opencv2/core.hpp b/include/opencv2/core.hpp
index ff9fa36..fc2432d 100755
--- a/include/opencv2/core.hpp
+++ b/include/opencv2/core.hpp
@@ -95,7 +95,6 @@
@{
@defgroup core_hal_intrin_impl Private implementation helpers
@}
- @defgroup core_lowlevel_api Low-level API for external libraries / plugins
@}
@}
*/
@@ -149,7 +148,7 @@ It is possible to alternate error processing by using #redirectError().
@param exc the exception raisen.
@deprecated drop this version
*/
-CV_EXPORTS CV_NORETURN void error(const Exception& exc);
+CV_EXPORTS void error( const Exception& exc );
enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently
SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted
@@ -203,6 +202,9 @@ enum CovarFlags {
COVAR_COLS = 16
};
+//! @addtogroup core_cluster
+//! @{
+
//! k-Means flags
enum KmeansFlags {
/** Select random initial centers in each attempt.*/
@@ -216,12 +218,39 @@ enum KmeansFlags {
KMEANS_USE_INITIAL_LABELS = 1
};
+//! @} core_cluster
+
+//! type of line
+enum LineTypes {
+ FILLED = -1,
+ LINE_4 = 4, //!< 4-connected line
+ LINE_8 = 8, //!< 8-connected line
+ LINE_AA = 16 //!< antialiased line
+};
+
+//! Only a subset of Hershey fonts <https://en.wikipedia.org/wiki/Hershey_fonts> are supported
+enum HersheyFonts {
+ FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font
+ FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font
+ FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
+ FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font
+ FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
+ FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
+ FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
+ FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
+ FONT_ITALIC = 16 //!< flag for italic font
+};
+
+//! @addtogroup core_array
+//! @{
+
enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.
REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.
REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.
REDUCE_MIN = 3 //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix.
};
+//! @} core_array
/** @brief Swaps two matrices
*/
@@ -420,13 +449,8 @@ The function cv::divide divides one array by another:
or a scalar by an array when there is no src1 :
\f[\texttt{dst(I) = saturate(scale/src2(I))}\f]
-Different channels of multi-channel arrays are processed independently.
-
-For integer types when src2(I) is zero, dst(I) will also be zero.
-
-@note In case of floating point data there is no special defined behavior for zero src2(I) values.
-Regular floating-point division is used.
-Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values).
+When src2(I) is zero, dst(I) will also be zero. Different channels of
+multi-channel arrays are processed independently.
@note Saturation is not applied when the output array has the depth CV_32S. You may even get
result of an incorrect sign in the case of overflow.
@@ -591,7 +615,7 @@ or
// access pixel coordinates
Point pnt = locations[i];
@endcode
-@param src single-channel array
+@param src single-channel array (type CV_8UC1)
@param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input
*/
CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
@@ -691,8 +715,7 @@ CV_EXPORTS double norm( const SparseMat& src, int normType );
/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric.
-This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB),
-between two input arrays src1 and src2. The arrays must have the same type.
+This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), between two input arrays src1 and src2. Arrays must have depth CV_8U.
The PSNR is calculated as follows:
@@ -700,15 +723,13 @@ The PSNR is calculated as follows:
\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) }
\f]
-where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data)
-and MSE is the mean squared error between the two arrays.
+where R is the maximum integer value of depth CV_8U (255) and MSE is the mean squared error between the two arrays.
@param src1 first input array.
@param src2 second input array of the same size as src1.
-@param R the maximum pixel value (255 by default)
*/
-CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.);
+CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
/** @brief naive nearest neighbor finder
@@ -1351,17 +1372,6 @@ You may even get a negative value in the case of overflow.
*/
CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
-/** @brief This is an overloaded member function, provided for convenience (python)
-Copies the matrix to another one.
-When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.
-@param src source matrix.
-@param dst Destination matrix. If it does not have a proper size or type before the operation, it is
-reallocated.
-@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
-elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
-*/
-
-void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask);
/** @brief Checks if array elements lie between the elements of two other arrays.
The function checks the range as follows:
@@ -1614,7 +1624,9 @@ elements.
CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,
double minVal = -DBL_MAX, double maxVal = DBL_MAX);
-/** @brief converts NaN's to the given number
+/** @brief converts NaNs to the given number
+@param a input/output matrix (CV_32F type).
+@param val value to convert the NaNs
*/
CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
@@ -2606,6 +2618,7 @@ public:
static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
protected:
+ bool _dataAsRow; // unused, but needed for 3.0 ABI compatibility.
int _num_components;
Mat _eigenvectors;
Mat _eigenvalues;
@@ -3018,8 +3031,7 @@ public:
class CV_EXPORTS Formatter
{
public:
- enum FormatType {
- FMT_DEFAULT = 0,
+ enum { FMT_DEFAULT = 0,
FMT_MATLAB = 1,
FMT_CSV = 2,
FMT_PYTHON = 3,
@@ -3031,12 +3043,11 @@ public:
virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
- virtual void set16fPrecision(int p = 4) = 0;
virtual void set32fPrecision(int p = 8) = 0;
virtual void set64fPrecision(int p = 16) = 0;
virtual void setMultiline(bool ml = true) = 0;
- static Ptr<Formatter> get(Formatter::FormatType fmt = FMT_DEFAULT);
+ static Ptr<Formatter> get(int fmt = FMT_DEFAULT);
};
@@ -3059,7 +3070,7 @@ String& operator << (String& out, const Mat& mtx)
class CV_EXPORTS Algorithm;
-template<typename _Tp, typename _EnumTp = void> struct ParamType {};
+template<typename _Tp> struct ParamType {};
/** @brief This is a base class for all more or less complex algorithms in OpenCV
@@ -3172,9 +3183,9 @@ protected:
void writeFormat(FileStorage& fs) const;
};
-enum struct Param {
- INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,
- UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12
+struct Param {
+ enum { INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,
+ UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 };
};
@@ -3184,7 +3195,7 @@ template<> struct ParamType<bool>
typedef bool const_param_type;
typedef bool member_type;
- static const Param type = Param::BOOLEAN;
+ enum { type = Param::BOOLEAN };
};
template<> struct ParamType<int>
@@ -3192,7 +3203,7 @@ template<> struct ParamType<int>
typedef int const_param_type;
typedef int member_type;
- static const Param type = Param::INT;
+ enum { type = Param::INT };
};
template<> struct ParamType<double>
@@ -3200,7 +3211,7 @@ template<> struct ParamType<double>
typedef double const_param_type;
typedef double member_type;
- static const Param type = Param::REAL;
+ enum { type = Param::REAL };
};
template<> struct ParamType<String>
@@ -3208,7 +3219,7 @@ template<> struct ParamType<String>
typedef const String& const_param_type;
typedef String member_type;
- static const Param type = Param::STRING;
+ enum { type = Param::STRING };
};
template<> struct ParamType<Mat>
@@ -3216,7 +3227,7 @@ template<> struct ParamType<Mat>
typedef const Mat& const_param_type;
typedef Mat member_type;
- static const Param type = Param::MAT;
+ enum { type = Param::MAT };
};
template<> struct ParamType<std::vector<Mat> >
@@ -3224,7 +3235,7 @@ template<> struct ParamType<std::vector<Mat> >
typedef const std::vector<Mat>& const_param_type;
typedef std::vector<Mat> member_type;
- static const Param type = Param::MAT_VECTOR;
+ enum { type = Param::MAT_VECTOR };
};
template<> struct ParamType<Algorithm>
@@ -3232,7 +3243,7 @@ template<> struct ParamType<Algorithm>
typedef const Ptr<Algorithm>& const_param_type;
typedef Ptr<Algorithm> member_type;
- static const Param type = Param::ALGORITHM;
+ enum { type = Param::ALGORITHM };
};
template<> struct ParamType<float>
@@ -3240,7 +3251,7 @@ template<> struct ParamType<float>
typedef float const_param_type;
typedef float member_type;
- static const Param type = Param::FLOAT;
+ enum { type = Param::FLOAT };
};
template<> struct ParamType<unsigned>
@@ -3248,7 +3259,7 @@ template<> struct ParamType<unsigned>
typedef unsigned const_param_type;
typedef unsigned member_type;
- static const Param type = Param::UNSIGNED_INT;
+ enum { type = Param::UNSIGNED_INT };
};
template<> struct ParamType<uint64>
@@ -3256,7 +3267,7 @@ template<> struct ParamType<uint64>
typedef uint64 const_param_type;
typedef uint64 member_type;
- static const Param type = Param::UINT64;
+ enum { type = Param::UINT64 };
};
template<> struct ParamType<uchar>
@@ -3264,7 +3275,7 @@ template<> struct ParamType<uchar>
typedef uchar const_param_type;
typedef uchar member_type;
- static const Param type = Param::UCHAR;
+ enum { type = Param::UCHAR };
};
template<> struct ParamType<Scalar>
@@ -3272,16 +3283,7 @@ template<> struct ParamType<Scalar>
typedef const Scalar& const_param_type;
typedef Scalar member_type;
- static const Param type = Param::SCALAR;
-};
-
-template<typename _Tp>
-struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type>
-{
- typedef typename std::underlying_type<_Tp>::type const_param_type;
- typedef typename std::underlying_type<_Tp>::type member_type;
-
- static const Param type = Param::INT;
+ enum { type = Param::SCALAR };
};
//! @} core_basic
diff --git a/include/opencv2/core/base.hpp b/include/opencv2/core/base.hpp
index a3a3e51..546140e 100755
--- a/include/opencv2/core/base.hpp
+++ b/include/opencv2/core/base.hpp
@@ -295,7 +295,32 @@ It is possible to alternate error processing by using redirectError().
@param _line - line number in the source file where the error has occurred
@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert
*/
-CV_EXPORTS CV_NORETURN void error(int _code, const String& _err, const char* _func, const char* _file, int _line);
+CV_EXPORTS void error(int _code, const String& _err, const char* _func, const char* _file, int _line);
+
+#ifdef __GNUC__
+# if defined __clang__ || defined __APPLE__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Winvalid-noreturn"
+# endif
+#endif
+
+/** same as cv::error, but does not return */
+CV_INLINE CV_NORETURN void errorNoReturn(int _code, const String& _err, const char* _func, const char* _file, int _line)
+{
+ error(_code, _err, _func, _file, _line);
+#ifdef __GNUC__
+# if !defined __clang__ && !defined __APPLE__
+ // this suppresses this warning: "noreturn" function does return [enabled by default]
+ __builtin_trap();
+ // or use infinite loop: for (;;) {}
+# endif
+#endif
+}
+#ifdef __GNUC__
+# if defined __clang__ || defined __APPLE__
+# pragma GCC diagnostic pop
+# endif
+#endif
#ifdef CV_STATIC_ANALYSIS
@@ -304,6 +329,8 @@ CV_EXPORTS CV_NORETURN void error(int _code, const String& _err, const char* _fu
#define CV_Error(code, msg) do { (void)(code); (void)(msg); abort(); } while (0)
#define CV_Error_(code, args) do { (void)(code); (void)(cv::format args); abort(); } while (0)
#define CV_Assert( expr ) do { if (!(expr)) abort(); } while (0)
+#define CV_ErrorNoReturn CV_Error
+#define CV_ErrorNoReturn_ CV_Error_
#else // CV_STATIC_ANALYSIS
@@ -341,31 +368,53 @@ configurations while CV_DbgAssert is only retained in the Debug configuration.
*/
#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0)
+//! @cond IGNORED
+#define CV__ErrorNoReturn( code, msg ) cv::errorNoReturn( code, msg, CV_Func, __FILE__, __LINE__ )
+#define CV__ErrorNoReturn_( code, args ) cv::errorNoReturn( code, cv::format args, CV_Func, __FILE__, __LINE__ )
+#ifdef __OPENCV_BUILD
+#undef CV_Error
+#define CV_Error CV__ErrorNoReturn
+#undef CV_Error_
+#define CV_Error_ CV__ErrorNoReturn_
+#undef CV_Assert
+#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::errorNoReturn( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0)
+#else
+// backward compatibility
+#define CV_ErrorNoReturn CV__ErrorNoReturn
+#define CV_ErrorNoReturn_ CV__ErrorNoReturn_
+#endif
+//! @endcond
+
#endif // CV_STATIC_ANALYSIS
//! @cond IGNORED
-#if !defined(__OPENCV_BUILD) // TODO: backward compatibility only
-#ifndef CV_ErrorNoReturn
-#define CV_ErrorNoReturn CV_Error
-#endif
-#ifndef CV_ErrorNoReturn_
-#define CV_ErrorNoReturn_ CV_Error_
-#endif
+
+#if defined OPENCV_FORCE_MULTIARG_ASSERT_CHECK && defined CV_STATIC_ANALYSIS
+#warning "OPENCV_FORCE_MULTIARG_ASSERT_CHECK can't be used with CV_STATIC_ANALYSIS"
+#undef OPENCV_FORCE_MULTIARG_ASSERT_CHECK
#endif
+#ifdef OPENCV_FORCE_MULTIARG_ASSERT_CHECK
+#define CV_Assert_1( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0)
+#else
#define CV_Assert_1 CV_Assert
-#define CV_Assert_2( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_1( __VA_ARGS__ ))
-#define CV_Assert_3( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_2( __VA_ARGS__ ))
-#define CV_Assert_4( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_3( __VA_ARGS__ ))
-#define CV_Assert_5( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_4( __VA_ARGS__ ))
-#define CV_Assert_6( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_5( __VA_ARGS__ ))
-#define CV_Assert_7( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_6( __VA_ARGS__ ))
-#define CV_Assert_8( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_7( __VA_ARGS__ ))
-#define CV_Assert_9( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_8( __VA_ARGS__ ))
-#define CV_Assert_10( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_9( __VA_ARGS__ ))
-
-#define CV_Assert_N(...) do { __CV_EXPAND(__CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__)); } while(0)
-
+#endif
+#define CV_Assert_2( expr1, expr2 ) CV_Assert_1(expr1); CV_Assert_1(expr2)
+#define CV_Assert_3( expr1, expr2, expr3 ) CV_Assert_2(expr1, expr2); CV_Assert_1(expr3)
+#define CV_Assert_4( expr1, expr2, expr3, expr4 ) CV_Assert_3(expr1, expr2, expr3); CV_Assert_1(expr4)
+#define CV_Assert_5( expr1, expr2, expr3, expr4, expr5 ) CV_Assert_4(expr1, expr2, expr3, expr4); CV_Assert_1(expr5)
+#define CV_Assert_6( expr1, expr2, expr3, expr4, expr5, expr6 ) CV_Assert_5(expr1, expr2, expr3, expr4, expr5); CV_Assert_1(expr6)
+#define CV_Assert_7( expr1, expr2, expr3, expr4, expr5, expr6, expr7 ) CV_Assert_6(expr1, expr2, expr3, expr4, expr5, expr6 ); CV_Assert_1(expr7)
+#define CV_Assert_8( expr1, expr2, expr3, expr4, expr5, expr6, expr7, expr8 ) CV_Assert_7(expr1, expr2, expr3, expr4, expr5, expr6, expr7 ); CV_Assert_1(expr8)
+#define CV_Assert_9( expr1, expr2, expr3, expr4, expr5, expr6, expr7, expr8, expr9 ) CV_Assert_8(expr1, expr2, expr3, expr4, expr5, expr6, expr7, expr8 ); CV_Assert_1(expr9)
+#define CV_Assert_10( expr1, expr2, expr3, expr4, expr5, expr6, expr7, expr8, expr9, expr10 ) CV_Assert_9(expr1, expr2, expr3, expr4, expr5, expr6, expr7, expr8, expr9 ); CV_Assert_1(expr10)
+
+#define CV_Assert_N(...) do { __CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__); } while(0)
+
+#ifdef OPENCV_FORCE_MULTIARG_ASSERT_CHECK
+#undef CV_Assert
+#define CV_Assert CV_Assert_N
+#endif
//! @endcond
#if defined _DEBUG || defined CV_STATIC_ANALYSIS
@@ -381,7 +430,7 @@ configurations while CV_DbgAssert is only retained in the Debug configuration.
*/
struct CV_EXPORTS Hamming
{
- static const NormTypes normType = NORM_HAMMING;
+ enum { normType = NORM_HAMMING };
typedef unsigned char ValueType;
typedef int ResultType;
@@ -618,7 +667,11 @@ namespace cudev
namespace ipp
{
+#if OPENCV_ABI_COMPATIBILITY > 300
CV_EXPORTS unsigned long long getIppFeatures();
+#else
+CV_EXPORTS int getIppFeatures();
+#endif
CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL,
int line = 0);
CV_EXPORTS int getIppStatus();
@@ -631,9 +684,9 @@ CV_EXPORTS_W String getIppVersion();
// but have internal accuracy differences which have too much direct or indirect impact on accuracy tests.
CV_EXPORTS_W bool useIPP_NotExact();
CV_EXPORTS_W void setUseIPP_NotExact(bool flag);
-#ifndef DISABLE_OPENCV_3_COMPATIBILITY
-static inline bool useIPP_NE() { return useIPP_NotExact(); }
-static inline void setUseIPP_NE(bool flag) { setUseIPP_NotExact(flag); }
+#if OPENCV_ABI_COMPATIBILITY < 400
+CV_EXPORTS_W bool useIPP_NE();
+CV_EXPORTS_W void setUseIPP_NE(bool flag);
#endif
} // ipp
diff --git a/include/opencv2/core/bindings_utils.hpp b/include/opencv2/core/bindings_utils.hpp
index f693dc8..92f27f0 100755
--- a/include/opencv2/core/bindings_utils.hpp
+++ b/include/opencv2/core/bindings_utils.hpp
@@ -58,6 +58,12 @@ String dumpCString(const char* argument)
return cv::format("String: %s", argument);
}
+CV_WRAP static inline
+String dumpString(const String& argument)
+{
+ return cv::format("String: %s", argument.c_str());
+}
+
CV_WRAP static inline
AsyncArray testAsyncArray(InputArray argument)
{
diff --git a/include/opencv2/core/check.hpp b/include/opencv2/core/check.hpp
index 604447e..d975223 100755
--- a/include/opencv2/core/check.hpp
+++ b/include/opencv2/core/check.hpp
@@ -63,7 +63,7 @@ struct CheckContext {
#define CV__CHECK_LOCATION_VARNAME(id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_check_, id), __LINE__)
#define CV__DEFINE_CHECK_CONTEXT(id, message, testOp, p1_str, p2_str) \
static const cv::detail::CheckContext CV__CHECK_LOCATION_VARNAME(id) = \
- { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, message, p1_str, p2_str }
+ { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, "" message, "" p1_str, "" p2_str }
CV_EXPORTS void CV_NORETURN check_failed_auto(const int v1, const int v2, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v1, const size_t v2, const CheckContext& ctx);
@@ -79,6 +79,7 @@ CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v, const CheckContext
CV_EXPORTS void CV_NORETURN check_failed_auto(const float v, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_auto(const double v, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_<int> v, const CheckContext& ctx);
+CV_EXPORTS void CV_NORETURN check_failed_auto(const std::string& v1, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v, const CheckContext& ctx);
CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v, const CheckContext& ctx);
diff --git a/include/opencv2/core/core_c.h b/include/opencv2/core/core_c.h
index 2684151..95a98cf 100755
--- a/include/opencv2/core/core_c.h
+++ b/include/opencv2/core/core_c.h
@@ -1309,7 +1309,7 @@ CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order,
const CvArr* delta CV_DEFAULT(NULL),
double scale CV_DEFAULT(1.) );
-/** Tranposes matrix. Square matrices can be transposed in-place */
+/** Transposes matrix. Square matrices can be transposed in-place */
CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst );
#define cvT cvTranspose
@@ -1576,8 +1576,8 @@ CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos
CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size );
/** Allocates string in memory storage */
-//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr,
-// int len CV_DEFAULT(-1) );
+CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr,
+ int len CV_DEFAULT(-1) );
/** Creates new empty sequence that will reside in the specified storage */
CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size,
@@ -1970,7 +1970,6 @@ CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header,
* Data Persistence *
\****************************************************************************************/
-#if 0
/********************************** High-level functions ********************************/
/** @brief Opens file storage for reading or writing data.
@@ -2557,12 +2556,10 @@ returns NULL.
*/
CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr );
-#endif
-
/** @brief Releases an object.
- The function finds the type of a given object and calls release with the double pointer.
- @param struct_ptr Double pointer to the object
+The function finds the type of a given object and calls release with the double pointer.
+@param struct_ptr Double pointer to the object
*/
CVAPI(void) cvRelease( void** struct_ptr );
@@ -2575,6 +2572,41 @@ function, like cvCloneMat.
*/
CVAPI(void*) cvClone( const void* struct_ptr );
+/** @brief Saves an object to a file.
+
+The function saves an object to a file. It provides a simple interface to cvWrite .
+@param filename File name
+@param struct_ptr Object to save
+@param name Optional object name. If it is NULL, the name will be formed from filename .
+@param comment Optional comment to put in the beginning of the file
+@param attributes Optional attributes passed to cvWrite
+ */
+CVAPI(void) cvSave( const char* filename, const void* struct_ptr,
+ const char* name CV_DEFAULT(NULL),
+ const char* comment CV_DEFAULT(NULL),
+ CvAttrList attributes CV_DEFAULT(cvAttrList()));
+
+/** @brief Loads an object from a file.
+
+The function loads an object from a file. It basically reads the specified file, find the first
+top-level node and calls cvRead 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.
+@param filename File name
+@param memstorage Memory storage for dynamic structures, such as CvSeq or 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 real_name Optional output parameter that will contain the name of the loaded object
+(useful if name=NULL )
+ */
+CVAPI(void*) cvLoad( const char* filename,
+ CvMemStorage* memstorage CV_DEFAULT(NULL),
+ const char* name CV_DEFAULT(NULL),
+ const char** real_name CV_DEFAULT(NULL) );
+
/*********************************** Measuring Execution Time ***************************/
/** helper functions for RNG initialization and accurate time measurement:
@@ -2725,6 +2757,24 @@ static char cvFuncName[] = Name
#ifdef __cplusplus
+//! @addtogroup core_c_glue
+//! @{
+
+//! class for automatic module/RTTI data registration/unregistration
+struct CV_EXPORTS CvType
+{
+ CvType( const char* type_name,
+ CvIsInstanceFunc is_instance, CvReleaseFunc release=0,
+ CvReadFunc read=0, CvWriteFunc write=0, CvCloneFunc clone=0 );
+ ~CvType();
+ CvTypeInfo* info;
+
+ static CvTypeInfo* first;
+ static CvTypeInfo* last;
+};
+
+//! @}
+
#include "opencv2/core/utility.hpp"
namespace cv
@@ -2755,11 +2805,11 @@ CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types //////
-template<> struct DefaultDeleter<CvMat>{ CV_EXPORTS void operator ()(CvMat* obj) const; };
-template<> struct DefaultDeleter<IplImage>{ CV_EXPORTS void operator ()(IplImage* obj) const; };
-template<> struct DefaultDeleter<CvMatND>{ CV_EXPORTS void operator ()(CvMatND* obj) const; };
-template<> struct DefaultDeleter<CvSparseMat>{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; };
-template<> struct DefaultDeleter<CvMemStorage>{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; };
+template<> CV_EXPORTS void DefaultDeleter<CvMat>::operator ()(CvMat* obj) const;
+template<> CV_EXPORTS void DefaultDeleter<IplImage>::operator ()(IplImage* obj) const;
+template<> CV_EXPORTS void DefaultDeleter<CvMatND>::operator ()(CvMatND* obj) const;
+template<> CV_EXPORTS void DefaultDeleter<CvSparseMat>::operator ()(CvSparseMat* obj) const;
+template<> CV_EXPORTS void DefaultDeleter<CvMemStorage>::operator ()(CvMemStorage* obj) const;
////////////// convenient wrappers for operating old-style dynamic structures //////////////
diff --git a/include/opencv2/core/cuda.hpp b/include/opencv2/core/cuda.hpp
index 99819d7..7d7bb62 100755
--- a/include/opencv2/core/cuda.hpp
+++ b/include/opencv2/core/cuda.hpp
@@ -102,10 +102,10 @@ streams.
@sa Mat
*/
-class CV_EXPORTS_W GpuMat
+class CV_EXPORTS GpuMat
{
public:
- class CV_EXPORTS_W Allocator
+ class CV_EXPORTS Allocator
{
public:
virtual ~Allocator() {}
@@ -116,33 +116,33 @@ public:
};
//! default allocator
- CV_WRAP static GpuMat::Allocator* defaultAllocator();
- CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator);
+ static Allocator* defaultAllocator();
+ static void setDefaultAllocator(Allocator* allocator);
//! default constructor
- CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
+ explicit GpuMat(Allocator* allocator = defaultAllocator());
//! constructs GpuMat of the specified size and type
- CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
- CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
+ GpuMat(int rows, int cols, int type, Allocator* allocator = defaultAllocator());
+ GpuMat(Size size, int type, Allocator* allocator = defaultAllocator());
//! constructs GpuMat and fills it with the specified value _s
- CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
- CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
+ GpuMat(int rows, int cols, int type, Scalar s, Allocator* allocator = defaultAllocator());
+ GpuMat(Size size, int type, Scalar s, Allocator* allocator = defaultAllocator());
//! copy constructor
- CV_WRAP GpuMat(const GpuMat& m);
+ GpuMat(const GpuMat& m);
//! constructor for GpuMat headers pointing to user-allocated data
GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP);
GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP);
//! creates a GpuMat header for a part of the bigger matrix
- CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange);
- CV_WRAP GpuMat(const GpuMat& m, Rect roi);
+ GpuMat(const GpuMat& m, Range rowRange, Range colRange);
+ GpuMat(const GpuMat& m, Rect roi);
//! builds GpuMat from host memory (Blocking call)
- CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
+ explicit GpuMat(InputArray arr, Allocator* allocator = defaultAllocator());
//! destructor - calls release()
~GpuMat();
@@ -151,21 +151,21 @@ public:
GpuMat& operator =(const GpuMat& m);
//! allocates new GpuMat data unless the GpuMat already has specified size and type
- CV_WRAP void create(int rows, int cols, int type);
- CV_WRAP void create(Size size, int type);
+ void create(int rows, int cols, int type);
+ void create(Size size, int type);
//! decreases reference counter, deallocate the data when reference counter reaches 0
void release();
//! swaps with other smart pointer
- CV_WRAP void swap(GpuMat& mat);
+ void swap(GpuMat& mat);
/** @brief Performs data upload to GpuMat (Blocking call)
This function copies data from host memory to device memory. As being a blocking call, it is
guaranteed that the copy operation is finished when this function returns.
*/
- CV_WRAP void upload(InputArray arr);
+ void upload(InputArray arr);
/** @brief Performs data upload to GpuMat (Non-Blocking call)
@@ -175,14 +175,14 @@ public:
The copy operation may be overlapped with operations in other non-default streams if \p stream is
not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option.
*/
- CV_WRAP void upload(InputArray arr, Stream& stream);
+ void upload(InputArray arr, Stream& stream);
/** @brief Performs data download from GpuMat (Blocking call)
This function copies data from device memory to host memory. As being a blocking call, it is
guaranteed that the copy operation is finished when this function returns.
*/
- CV_WRAP void download(OutputArray dst) const;
+ void download(OutputArray dst) const;
/** @brief Performs data download from GpuMat (Non-Blocking call)
@@ -192,51 +192,51 @@ public:
The copy operation may be overlapped with operations in other non-default streams if \p stream is
not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option.
*/
- CV_WRAP void download(OutputArray dst, Stream& stream) const;
+ void download(OutputArray dst, Stream& stream) const;
//! returns deep copy of the GpuMat, i.e. the data is copied
- CV_WRAP GpuMat clone() const;
+ GpuMat clone() const;
//! copies the GpuMat content to device memory (Blocking call)
- CV_WRAP void copyTo(OutputArray dst) const;
+ void copyTo(OutputArray dst) const;
//! copies the GpuMat content to device memory (Non-Blocking call)
- CV_WRAP void copyTo(OutputArray dst, Stream& stream) const;
+ void copyTo(OutputArray dst, Stream& stream) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call)
- CV_WRAP void copyTo(OutputArray dst, InputArray mask) const;
+ void copyTo(OutputArray dst, InputArray mask) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call)
- CV_WRAP void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
+ void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
//! sets some of the GpuMat elements to s (Blocking call)
- CV_WRAP GpuMat& setTo(Scalar s);
+ GpuMat& setTo(Scalar s);
//! sets some of the GpuMat elements to s (Non-Blocking call)
- CV_WRAP GpuMat& setTo(Scalar s, Stream& stream);
+ GpuMat& setTo(Scalar s, Stream& stream);
//! sets some of the GpuMat elements to s, according to the mask (Blocking call)
- CV_WRAP GpuMat& setTo(Scalar s, InputArray mask);
+ GpuMat& setTo(Scalar s, InputArray mask);
//! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call)
- CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream);
+ GpuMat& setTo(Scalar s, InputArray mask, Stream& stream);
//! converts GpuMat to another datatype (Blocking call)
- CV_WRAP void convertTo(OutputArray dst, int rtype) const;
+ void convertTo(OutputArray dst, int rtype) const;
//! converts GpuMat to another datatype (Non-Blocking call)
- CV_WRAP void convertTo(OutputArray dst, int rtype, Stream& stream) const;
+ void convertTo(OutputArray dst, int rtype, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Blocking call)
- CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const;
+ void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
- CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const;
+ void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
- CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const;
+ void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const;
- CV_WRAP void assignTo(GpuMat& m, int type = -1) const;
+ void assignTo(GpuMat& m, int type=-1) const;
//! returns pointer to y-th row
uchar* ptr(int y = 0);
@@ -250,18 +250,18 @@ public:
template <typename _Tp> operator PtrStep<_Tp>() const;
//! returns a new GpuMat header for the specified row
- CV_WRAP GpuMat row(int y) const;
+ GpuMat row(int y) const;
//! returns a new GpuMat header for the specified column
- CV_WRAP GpuMat col(int x) const;
+ GpuMat col(int x) const;
//! ... for the specified row span
- CV_WRAP GpuMat rowRange(int startrow, int endrow) const;
- CV_WRAP GpuMat rowRange(Range r) const;
+ GpuMat rowRange(int startrow, int endrow) const;
+ GpuMat rowRange(Range r) const;
//! ... for the specified column span
- CV_WRAP GpuMat colRange(int startcol, int endcol) const;
- CV_WRAP GpuMat colRange(Range r) const;
+ GpuMat colRange(int startcol, int endcol) const;
+ GpuMat colRange(Range r) const;
//! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.)
GpuMat operator ()(Range rowRange, Range colRange) const;
@@ -269,44 +269,44 @@ public:
//! creates alternative GpuMat header for the same data, with different
//! number of channels and/or different number of rows
- CV_WRAP GpuMat reshape(int cn, int rows = 0) const;
+ GpuMat reshape(int cn, int rows = 0) const;
//! locates GpuMat header within a parent GpuMat
- CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const;
+ void locateROI(Size& wholeSize, Point& ofs) const;
//! moves/resizes the current GpuMat ROI inside the parent GpuMat
- CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright);
+ GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright);
//! returns true iff the GpuMat data is continuous
//! (i.e. when there are no gaps between successive rows)
- CV_WRAP bool isContinuous() const;
+ bool isContinuous() const;
//! returns element size in bytes
- CV_WRAP size_t elemSize() const;
+ size_t elemSize() const;
//! returns the size of element channel in bytes
- CV_WRAP size_t elemSize1() const;
+ size_t elemSize1() const;
//! returns element type
- CV_WRAP int type() const;
+ int type() const;
//! returns element type
- CV_WRAP int depth() const;
+ int depth() const;
//! returns number of channels
- CV_WRAP int channels() const;
+ int channels() const;
//! returns step/elemSize1()
- CV_WRAP size_t step1() const;
+ size_t step1() const;
//! returns GpuMat size : width == number of columns, height == number of rows
- CV_WRAP Size size() const;
+ Size size() const;
//! returns true if GpuMat data is NULL
- CV_WRAP bool empty() const;
+ bool empty() const;
//! internal use method: updates the continuity flag
- CV_WRAP void updateContinuityFlag();
+ void updateContinuityFlag();
/*! includes several bit-fields:
- the magic signature
@@ -320,7 +320,7 @@ public:
int rows, cols;
//! a distance between successive rows in bytes; includes the gap if any
- CV_PROP size_t step;
+ size_t step;
//! pointer to the data
uchar* data;
@@ -348,7 +348,7 @@ public:
Matrix is called continuous if its elements are stored continuously, that is, without gaps at the
end of each row.
*/
-CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr);
+CV_EXPORTS void createContinuous(int rows, int cols, int type, OutputArray arr);
/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type.
@@ -359,7 +359,7 @@ CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr
The function does not reallocate memory if the matrix has proper attributes already.
*/
-CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
+CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
/** @brief BufferPool for use with CUDA streams
@@ -478,7 +478,7 @@ and the corresponding memory is automatically returned to the pool for later usa
}
@endcode
*/
-class CV_EXPORTS_W BufferPool
+class CV_EXPORTS BufferPool
{
public:
@@ -486,21 +486,21 @@ public:
explicit BufferPool(Stream& stream);
//! Allocates a new GpuMat of given size and type.
- CV_WRAP GpuMat getBuffer(int rows, int cols, int type);
+ GpuMat getBuffer(int rows, int cols, int type);
//! Allocates a new GpuMat of given size and type.
- CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); }
+ GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); }
//! Returns the allocator associated with the stream.
- CV_WRAP Ptr<GpuMat::Allocator> getAllocator() const { return allocator_; }
+ Ptr<GpuMat::Allocator> getAllocator() const { return allocator_; }
private:
Ptr<GpuMat::Allocator> allocator_;
};
//! BufferPool management (must be called before Stream creation)
-CV_EXPORTS_W void setBufferPoolUsage(bool on);
-CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
+CV_EXPORTS void setBufferPoolUsage(bool on);
+CV_EXPORTS void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
//===================================================================================
// HostMem
@@ -521,46 +521,46 @@ Its interface is also Mat-like but with additional memory type parameters.
@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2
Pinned Memory APIs* document or *CUDA C Programming Guide*.
*/
-class CV_EXPORTS_W HostMem
+class CV_EXPORTS HostMem
{
public:
enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 };
- static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
+ static MatAllocator* getAllocator(AllocType alloc_type = PAGE_LOCKED);
- CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
+ explicit HostMem(AllocType alloc_type = PAGE_LOCKED);
HostMem(const HostMem& m);
- CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
- CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
+ HostMem(int rows, int cols, int type, AllocType alloc_type = PAGE_LOCKED);
+ HostMem(Size size, int type, AllocType alloc_type = PAGE_LOCKED);
//! creates from host memory with coping data
- CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
+ explicit HostMem(InputArray arr, AllocType alloc_type = PAGE_LOCKED);
~HostMem();
HostMem& operator =(const HostMem& m);
//! swaps with other smart pointer
- CV_WRAP void swap(HostMem& b);
+ void swap(HostMem& b);
//! returns deep copy of the matrix, i.e. the data is copied
- CV_WRAP HostMem clone() const;
+ HostMem clone() const;
//! allocates new matrix data unless the matrix already has specified size and type.
- CV_WRAP void create(int rows, int cols, int type);
+ void create(int rows, int cols, int type);
void create(Size size, int type);
//! creates alternative HostMem header for the same data, with different
//! number of channels and/or different number of rows
- CV_WRAP HostMem reshape(int cn, int rows = 0) const;
+ HostMem reshape(int cn, int rows = 0) const;
//! decrements reference counter and released memory if needed.
void release();
//! returns matrix header with disabled reference counting for HostMem data.
- CV_WRAP Mat createMatHeader() const;
+ Mat createMatHeader() const;
/** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting
for it.
@@ -572,20 +572,20 @@ public:
GpuMat createGpuMatHeader() const;
// Please see cv::Mat for descriptions
- CV_WRAP bool isContinuous() const;
- CV_WRAP size_t elemSize() const;
- CV_WRAP size_t elemSize1() const;
- CV_WRAP int type() const;
- CV_WRAP int depth() const;
- CV_WRAP int channels() const;
- CV_WRAP size_t step1() const;
- CV_WRAP Size size() const;
- CV_WRAP bool empty() const;
+ bool isContinuous() const;
+ size_t elemSize() const;
+ size_t elemSize1() const;
+ int type() const;
+ int depth() const;
+ int channels() const;
+ size_t step1() const;
+ Size size() const;
+ bool empty() const;
// Please see cv::Mat for descriptions
int flags;
int rows, cols;
- CV_PROP size_t step;
+ size_t step;
uchar* data;
int* refcount;
@@ -600,13 +600,13 @@ public:
@param m Input matrix.
*/
-CV_EXPORTS_W void registerPageLocked(Mat& m);
+CV_EXPORTS void registerPageLocked(Mat& m);
/** @brief Unmaps the memory of matrix and makes it pageable again.
@param m Input matrix.
*/
-CV_EXPORTS_W void unregisterPageLocked(Mat& m);
+CV_EXPORTS void unregisterPageLocked(Mat& m);
//===================================================================================
// Stream
@@ -639,7 +639,7 @@ void thread2()
@note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user.
In multi-threading environment the stream objects must be passed explicitly (see previous note).
*/
-class CV_EXPORTS_W Stream
+class CV_EXPORTS Stream
{
typedef void (Stream::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
@@ -648,22 +648,22 @@ public:
typedef void (*StreamCallback)(int status, void* userData);
//! creates a new asynchronous stream
- CV_WRAP Stream();
+ Stream();
//! creates a new asynchronous stream with custom allocator
- CV_WRAP Stream(const Ptr<GpuMat::Allocator>& allocator);
+ Stream(const Ptr<GpuMat::Allocator>& allocator);
/** @brief Returns true if the current stream queue is finished. Otherwise, it returns false.
*/
- CV_WRAP bool queryIfComplete() const;
+ bool queryIfComplete() const;
/** @brief Blocks the current CPU thread until all operations in the stream are complete.
*/
- CV_WRAP void waitForCompletion();
+ void waitForCompletion();
/** @brief Makes a compute stream wait on an event.
*/
- CV_WRAP void waitEvent(const Event& event);
+ void waitEvent(const Event& event);
/** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have
completed.
@@ -676,7 +676,7 @@ public:
void enqueueHostCallback(StreamCallback callback, void* userData);
//! return Stream object for default CUDA stream
- CV_WRAP static Stream& Null();
+ static Stream& Null();
//! returns true if stream object is not default (!= 0)
operator bool_type() const;
@@ -692,7 +692,7 @@ private:
friend class DefaultDeviceInitializer;
};
-class CV_EXPORTS_W Event
+class CV_EXPORTS Event
{
public:
enum CreateFlags
@@ -703,19 +703,19 @@ public:
INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */
};
- CV_WRAP explicit Event(Event::CreateFlags flags = Event::CreateFlags::DEFAULT);
+ explicit Event(CreateFlags flags = DEFAULT);
//! records an event
- CV_WRAP void record(Stream& stream = Stream::Null());
+ void record(Stream& stream = Stream::Null());
//! queries an event's status
- CV_WRAP bool queryIfComplete() const;
+ bool queryIfComplete() const;
//! waits for an event to complete
- CV_WRAP void waitForCompletion();
+ void waitForCompletion();
//! computes the elapsed time between events
- CV_WRAP static float elapsedTime(const Event& start, const Event& end);
+ static float elapsedTime(const Event& start, const Event& end);
class Impl;
@@ -741,7 +741,7 @@ Use this function before any other CUDA functions calls. If OpenCV is compiled w
this function returns 0. If the CUDA driver is not installed, or is incompatible, this function
returns -1.
*/
-CV_EXPORTS_W int getCudaEnabledDeviceCount();
+CV_EXPORTS int getCudaEnabledDeviceCount();
/** @brief Sets a device and initializes it for the current thread.
@@ -749,18 +749,18 @@ CV_EXPORTS_W int getCudaEnabledDeviceCount();
If the call of this function is omitted, a default device is initialized at the fist CUDA usage.
*/
-CV_EXPORTS_W void setDevice(int device);
+CV_EXPORTS void setDevice(int device);
/** @brief Returns the current device index set by cuda::setDevice or initialized by default.
*/
-CV_EXPORTS_W int getDevice();
+CV_EXPORTS int getDevice();
/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current
process.
Any subsequent API call to this device will reinitialize the device.
*/
-CV_EXPORTS_W void resetDevice();
+CV_EXPORTS void resetDevice();
/** @brief Enumeration providing CUDA computing features.
*/
@@ -793,7 +793,7 @@ built for.
According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute
capability can always be compiled to binary code of greater or equal compute capability".
*/
-class CV_EXPORTS_W TargetArchs
+class CV_EXPORTS TargetArchs
{
public:
/** @brief The following method checks whether the module was built with the support of the given feature:
@@ -808,23 +808,23 @@ public:
@param major Major compute capability version.
@param minor Minor compute capability version.
*/
- CV_WRAP static bool has(int major, int minor);
- CV_WRAP static bool hasPtx(int major, int minor);
- CV_WRAP static bool hasBin(int major, int minor);
-
- CV_WRAP static bool hasEqualOrLessPtx(int major, int minor);
- CV_WRAP static bool hasEqualOrGreater(int major, int minor);
- CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor);
- CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor);
+ static bool has(int major, int minor);
+ static bool hasPtx(int major, int minor);
+ static bool hasBin(int major, int minor);
+
+ static bool hasEqualOrLessPtx(int major, int minor);
+ static bool hasEqualOrGreater(int major, int minor);
+ static bool hasEqualOrGreaterPtx(int major, int minor);
+ static bool hasEqualOrGreaterBin(int major, int minor);
};
/** @brief Class providing functionality for querying the specified GPU properties.
*/
-class CV_EXPORTS_W DeviceInfo
+class CV_EXPORTS DeviceInfo
{
public:
//! creates DeviceInfo object for the current GPU
- CV_WRAP DeviceInfo();
+ DeviceInfo();
/** @brief The constructors.
@@ -833,68 +833,68 @@ public:
Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it
constructs an object for the current device.
*/
- CV_WRAP DeviceInfo(int device_id);
+ DeviceInfo(int device_id);
/** @brief Returns system index of the CUDA device starting with 0.
*/
- CV_WRAP int deviceID() const;
+ int deviceID() const;
//! ASCII string identifying device
const char* name() const;
//! global memory available on device in bytes
- CV_WRAP size_t totalGlobalMem() const;
+ size_t totalGlobalMem() const;
//! shared memory available per block in bytes
- CV_WRAP size_t sharedMemPerBlock() const;
+ size_t sharedMemPerBlock() const;
//! 32-bit registers available per block
- CV_WRAP int regsPerBlock() const;
+ int regsPerBlock() const;
//! warp size in threads
- CV_WRAP int warpSize() const;
+ int warpSize() const;
//! maximum pitch in bytes allowed by memory copies
- CV_WRAP size_t memPitch() const;
+ size_t memPitch() const;
//! maximum number of threads per block
- CV_WRAP int maxThreadsPerBlock() const;
+ int maxThreadsPerBlock() const;
//! maximum size of each dimension of a block
- CV_WRAP Vec3i maxThreadsDim() const;
+ Vec3i maxThreadsDim() const;
//! maximum size of each dimension of a grid
- CV_WRAP Vec3i maxGridSize() const;
+ Vec3i maxGridSize() const;
//! clock frequency in kilohertz
- CV_WRAP int clockRate() const;
+ int clockRate() const;
//! constant memory available on device in bytes
- CV_WRAP size_t totalConstMem() const;
+ size_t totalConstMem() const;
//! major compute capability
- CV_WRAP int majorVersion() const;
+ int majorVersion() const;
//! minor compute capability
- CV_WRAP int minorVersion() const;
+ int minorVersion() const;
//! alignment requirement for textures
- CV_WRAP size_t textureAlignment() const;
+ size_t textureAlignment() const;
//! pitch alignment requirement for texture references bound to pitched memory
- CV_WRAP size_t texturePitchAlignment() const;
+ size_t texturePitchAlignment() const;
//! number of multiprocessors on device
- CV_WRAP int multiProcessorCount() const;
+ int multiProcessorCount() const;
//! specified whether there is a run time limit on kernels
- CV_WRAP bool kernelExecTimeoutEnabled() const;
+ bool kernelExecTimeoutEnabled() const;
//! device is integrated as opposed to discrete
- CV_WRAP bool integrated() const;
+ bool integrated() const;
//! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer
- CV_WRAP bool canMapHostMemory() const;
+ bool canMapHostMemory() const;
enum ComputeMode
{
@@ -905,108 +905,108 @@ public:
};
//! compute mode
- CV_WRAP DeviceInfo::ComputeMode computeMode() const;
+ ComputeMode computeMode() const;
//! maximum 1D texture size
- CV_WRAP int maxTexture1D() const;
+ int maxTexture1D() const;
//! maximum 1D mipmapped texture size
- CV_WRAP int maxTexture1DMipmap() const;
+ int maxTexture1DMipmap() const;
//! maximum size for 1D textures bound to linear memory
- CV_WRAP int maxTexture1DLinear() const;
+ int maxTexture1DLinear() const;
//! maximum 2D texture dimensions
- CV_WRAP Vec2i maxTexture2D() const;
+ Vec2i maxTexture2D() const;
//! maximum 2D mipmapped texture dimensions
- CV_WRAP Vec2i maxTexture2DMipmap() const;
+ Vec2i maxTexture2DMipmap() const;
//! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory
- CV_WRAP Vec3i maxTexture2DLinear() const;
+ Vec3i maxTexture2DLinear() const;
//! maximum 2D texture dimensions if texture gather operations have to be performed
- CV_WRAP Vec2i maxTexture2DGather() const;
+ Vec2i maxTexture2DGather() const;
//! maximum 3D texture dimensions
- CV_WRAP Vec3i maxTexture3D() const;
+ Vec3i maxTexture3D() const;
//! maximum Cubemap texture dimensions
- CV_WRAP int maxTextureCubemap() const;
+ int maxTextureCubemap() const;
//! maximum 1D layered texture dimensions
- CV_WRAP Vec2i maxTexture1DLayered() const;
+ Vec2i maxTexture1DLayered() const;
//! maximum 2D layered texture dimensions
- CV_WRAP Vec3i maxTexture2DLayered() const;
+ Vec3i maxTexture2DLayered() const;
//! maximum Cubemap layered texture dimensions
- CV_WRAP Vec2i maxTextureCubemapLayered() const;
+ Vec2i maxTextureCubemapLayered() const;
//! maximum 1D surface size
- CV_WRAP int maxSurface1D() const;
+ int maxSurface1D() const;
//! maximum 2D surface dimensions
- CV_WRAP Vec2i maxSurface2D() const;
+ Vec2i maxSurface2D() const;
//! maximum 3D surface dimensions
- CV_WRAP Vec3i maxSurface3D() const;
+ Vec3i maxSurface3D() const;
//! maximum 1D layered surface dimensions
- CV_WRAP Vec2i maxSurface1DLayered() const;
+ Vec2i maxSurface1DLayered() const;
//! maximum 2D layered surface dimensions
- CV_WRAP Vec3i maxSurface2DLayered() const;
+ Vec3i maxSurface2DLayered() const;
//! maximum Cubemap surface dimensions
- CV_WRAP int maxSurfaceCubemap() const;
+ int maxSurfaceCubemap() const;
//! maximum Cubemap layered surface dimensions
- CV_WRAP Vec2i maxSurfaceCubemapLayered() const;
+ Vec2i maxSurfaceCubemapLayered() const;
//! alignment requirements for surfaces
- CV_WRAP size_t surfaceAlignment() const;
+ size_t surfaceAlignment() const;
//! device can possibly execute multiple kernels concurrently
- CV_WRAP bool concurrentKernels() const;
+ bool concurrentKernels() const;
//! device has ECC support enabled
- CV_WRAP bool ECCEnabled() const;
+ bool ECCEnabled() const;
//! PCI bus ID of the device
- CV_WRAP int pciBusID() const;
+ int pciBusID() const;
//! PCI device ID of the device
- CV_WRAP int pciDeviceID() const;
+ int pciDeviceID() const;
//! PCI domain ID of the device
- CV_WRAP int pciDomainID() const;
+ int pciDomainID() const;
//! true if device is a Tesla device using TCC driver, false otherwise
- CV_WRAP bool tccDriver() const;
+ bool tccDriver() const;
//! number of asynchronous engines
- CV_WRAP int asyncEngineCount() const;
+ int asyncEngineCount() const;
//! device shares a unified address space with the host
- CV_WRAP bool unifiedAddressing() const;
+ bool unifiedAddressing() const;
//! peak memory clock frequency in kilohertz
- CV_WRAP int memoryClockRate() const;
+ int memoryClockRate() const;
//! global memory bus width in bits
- CV_WRAP int memoryBusWidth() const;
+ int memoryBusWidth() const;
//! size of L2 cache in bytes
- CV_WRAP int l2CacheSize() const;
+ int l2CacheSize() const;
//! maximum resident threads per multiprocessor
- CV_WRAP int maxThreadsPerMultiProcessor() const;
+ int maxThreadsPerMultiProcessor() const;
//! gets free and total device memory
- CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
- CV_WRAP size_t freeMemory() const;
- CV_WRAP size_t totalMemory() const;
+ void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
+ size_t freeMemory() const;
+ size_t totalMemory() const;
/** @brief Provides information on CUDA feature support.
@@ -1021,14 +1021,14 @@ public:
This function returns true if the CUDA module can be run on the specified device. Otherwise, it
returns false .
*/
- CV_WRAP bool isCompatible() const;
+ bool isCompatible() const;
private:
int device_id_;
};
-CV_EXPORTS_W void printCudaDeviceInfo(int device);
-CV_EXPORTS_W void printShortCudaDeviceInfo(int device);
+CV_EXPORTS void printCudaDeviceInfo(int device);
+CV_EXPORTS void printShortCudaDeviceInfo(int device);
/** @brief Converts an array to half precision floating number.
diff --git a/include/opencv2/core/cuda/common.hpp b/include/opencv2/core/cuda/common.hpp
index 14b1f3f..80b2ff0 100755
--- a/include/opencv2/core/cuda/common.hpp
+++ b/include/opencv2/core/cuda/common.hpp
@@ -101,6 +101,20 @@ namespace cv { namespace cuda
cudaChannelFormatDesc desc = cudaCreateChannelDesc<T>();
cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) );
}
+
+ template<class T> inline void createTextureObjectPitch2D(cudaTextureObject_t* tex, PtrStepSz<T>& img, const cudaTextureDesc& texDesc)
+ {
+ cudaResourceDesc resDesc;
+ memset(&resDesc, 0, sizeof(resDesc));
+ resDesc.resType = cudaResourceTypePitch2D;
+ resDesc.res.pitch2D.devPtr = static_cast<void*>(img.ptr());
+ resDesc.res.pitch2D.height = img.rows;
+ resDesc.res.pitch2D.width = img.cols;
+ resDesc.res.pitch2D.pitchInBytes = img.step;
+ resDesc.res.pitch2D.desc = cudaCreateChannelDesc<T>();
+
+ cudaSafeCall( cudaCreateTextureObject(tex, &resDesc, &texDesc, NULL) );
+ }
}
}}
diff --git a/include/opencv2/core/cuda/detail/color_detail.hpp b/include/opencv2/core/cuda/detail/color_detail.hpp
index f4b4796..bfb4055 100755
--- a/include/opencv2/core/cuda/detail/color_detail.hpp
+++ b/include/opencv2/core/cuda/detail/color_detail.hpp
@@ -92,51 +92,13 @@ namespace cv { namespace cuda { namespace device
return vec.w;
}
- //constants for conversion from/to RGB and Gray, YUV, YCrCb according to BT.601
- constexpr float B2YF = 0.114f;
- constexpr float G2YF = 0.587f;
- constexpr float R2YF = 0.299f;
-
- //to YCbCr
- constexpr float YCBF = 0.564f; // == 1/2/(1-B2YF)
- constexpr float YCRF = 0.713f; // == 1/2/(1-R2YF)
- const int YCBI = 9241; // == YCBF*16384
- const int YCRI = 11682; // == YCRF*16384
- //to YUV
- constexpr float B2UF = 0.492f;
- constexpr float R2VF = 0.877f;
- const int B2UI = 8061; // == B2UF*16384
- const int R2VI = 14369; // == R2VF*16384
- //from YUV
- constexpr float U2BF = 2.032f;
- constexpr float U2GF = -0.395f;
- constexpr float V2GF = -0.581f;
- constexpr float V2RF = 1.140f;
- const int U2BI = 33292;
- const int U2GI = -6472;
- const int V2GI = -9519;
- const int V2RI = 18678;
- //from YCrCb
- constexpr float CB2BF = 1.773f;
- constexpr float CB2GF = -0.344f;
- constexpr float CR2GF = -0.714f;
- constexpr float CR2RF = 1.403f;
- const int CB2BI = 29049;
- const int CB2GI = -5636;
- const int CR2GI = -11698;
- const int CR2RI = 22987;
-
enum
{
yuv_shift = 14,
xyz_shift = 12,
- gray_shift = 15,
R2Y = 4899,
G2Y = 9617,
B2Y = 1868,
- RY15 = 9798, // == R2YF*32768 + 0.5
- GY15 = 19235, // == G2YF*32768 + 0.5
- BY15 = 3735, // == B2YF*32768 + 0.5
BLOCK_SIZE = 256
};
}
@@ -444,7 +406,7 @@ namespace cv { namespace cuda { namespace device
{
static __device__ __forceinline__ uchar cvt(uint t)
{
- return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 3) & 0xfc) * GY15 + ((t >> 8) & 0xf8) * RY15, gray_shift);
+ return (uchar)CV_DESCALE(((t << 3) & 0xf8) * B2Y + ((t >> 3) & 0xfc) * G2Y + ((t >> 8) & 0xf8) * R2Y, yuv_shift);
}
};
@@ -452,7 +414,7 @@ namespace cv { namespace cuda { namespace device
{
static __device__ __forceinline__ uchar cvt(uint t)
{
- return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 2) & 0xf8) * GY15 + ((t >> 7) & 0xf8) * RY15, gray_shift);
+ return (uchar)CV_DESCALE(((t << 3) & 0xf8) * B2Y + ((t >> 2) & 0xf8) * G2Y + ((t >> 7) & 0xf8) * R2Y, yuv_shift);
}
};
@@ -481,7 +443,7 @@ namespace cv { namespace cuda { namespace device
{
template <int bidx, typename T> static __device__ __forceinline__ T RGB2GrayConvert(const T* src)
{
- return (T)CV_DESCALE((unsigned)(src[bidx] * BY15 + src[1] * GY15 + src[bidx^2] * RY15), gray_shift);
+ return (T)CV_DESCALE((unsigned)(src[bidx] * B2Y + src[1] * G2Y + src[bidx^2] * R2Y), yuv_shift);
}
template <int bidx> static __device__ __forceinline__ uchar RGB2GrayConvert(uint src)
@@ -489,12 +451,12 @@ namespace cv { namespace cuda { namespace device
uint b = 0xffu & (src >> (bidx * 8));
uint g = 0xffu & (src >> 8);
uint r = 0xffu & (src >> ((bidx ^ 2) * 8));
- return CV_DESCALE((uint)(b * BY15 + g * GY15 + r * RY15), gray_shift);
+ return CV_DESCALE((uint)(b * B2Y + g * G2Y + r * R2Y), yuv_shift);
}
template <int bidx> static __device__ __forceinline__ float RGB2GrayConvert(const float* src)
{
- return src[bidx] * B2YF + src[1] * G2YF + src[bidx^2] * R2YF;
+ return src[bidx] * 0.114f + src[1] * 0.587f + src[bidx^2] * 0.299f;
}
template <typename T, int scn, int bidx> struct RGB2Gray : unary_function<typename TypeVec<T, scn>::vec_type, T>
@@ -532,8 +494,8 @@ namespace cv { namespace cuda { namespace device
namespace color_detail
{
- __constant__ float c_RGB2YUVCoeffs_f[5] = { B2YF, G2YF, R2YF, B2UF, R2VF };
- __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, B2UI, R2VI };
+ __constant__ float c_RGB2YUVCoeffs_f[5] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f };
+ __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, 8061, 14369 };
template <int bidx, typename T, typename D> static __device__ void RGB2YUVConvert(const T* src, D& dst)
{
@@ -581,8 +543,8 @@ namespace cv { namespace cuda { namespace device
namespace color_detail
{
- __constant__ float c_YUV2RGBCoeffs_f[5] = { U2BF, U2GF, V2GF, V2RF };
- __constant__ int c_YUV2RGBCoeffs_i[5] = { U2BI, U2GI, V2GI, V2RI };
+ __constant__ float c_YUV2RGBCoeffs_f[5] = { 2.032f, -0.395f, -0.581f, 1.140f };
+ __constant__ int c_YUV2RGBCoeffs_i[5] = { 33292, -6472, -9519, 18678 };
template <int bidx, typename T, typename D> static __device__ void YUV2RGBConvert(const T& src, D* dst)
{
@@ -671,8 +633,8 @@ namespace cv { namespace cuda { namespace device
namespace color_detail
{
- __constant__ float c_RGB2YCrCbCoeffs_f[5] = {R2YF, G2YF, B2YF, YCRF, YCBF};
- __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, YCRI, YCBI};
+ __constant__ float c_RGB2YCrCbCoeffs_f[5] = {0.299f, 0.587f, 0.114f, 0.713f, 0.564f};
+ __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, 11682, 9241};
template <int bidx, typename T, typename D> static __device__ void RGB2YCrCbConvert(const T* src, D& dst)
{
@@ -748,8 +710,8 @@ namespace cv { namespace cuda { namespace device
namespace color_detail
{
- __constant__ float c_YCrCb2RGBCoeffs_f[5] = {CR2RF, CR2GF, CB2GF, CB2BF};
- __constant__ int c_YCrCb2RGBCoeffs_i[5] = {CR2RI, CR2GI, CB2GI, CB2BI};
+ __constant__ float c_YCrCb2RGBCoeffs_f[5] = {1.403f, -0.714f, -0.344f, 1.773f};
+ __constant__ int c_YCrCb2RGBCoeffs_i[5] = {22987, -11698, -5636, 29049};
template <int bidx, typename T, typename D> static __device__ void YCrCb2RGBConvert(const T& src, D* dst)
{
diff --git a/include/opencv2/core/cuda/functional.hpp b/include/opencv2/core/cuda/functional.hpp
index 9f53d87..3b531a1 100755
--- a/include/opencv2/core/cuda/functional.hpp
+++ b/include/opencv2/core/cuda/functional.hpp
@@ -57,6 +57,7 @@
namespace cv { namespace cuda { namespace device
{
// Function Objects
+#ifdef CV_CXX11
template<typename Argument, typename Result> struct unary_function
{
typedef Argument argument_type;
@@ -68,6 +69,10 @@ namespace cv { namespace cuda { namespace device
typedef Argument2 second_argument_type;
typedef Result result_type;
};
+#else
+ template<typename Argument, typename Result> struct unary_function : public std::unary_function<Argument, Result> {};
+ template<typename Argument1, typename Argument2, typename Result> struct binary_function : public std::binary_function<Argument1, Argument2, Result> {};
+#endif
// Arithmetic Operations
template <typename T> struct plus : binary_function<T, T, T>
diff --git a/include/opencv2/core/cuda/vec_math.hpp b/include/opencv2/core/cuda/vec_math.hpp
index 80b1303..9085b92 100755
--- a/include/opencv2/core/cuda/vec_math.hpp
+++ b/include/opencv2/core/cuda/vec_math.hpp
@@ -199,7 +199,14 @@ CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint)
return VecTraits<output_type ## 4>::make(func (a.x), func (a.y), func (a.z), func (a.w)); \
}
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, uchar, uchar)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, char, char)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, ushort, ushort)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, short, short)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::abs, int, int)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, /*::abs*/, uint, uint)
CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float)
+CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabs, double, double)
CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float)
CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float)
diff --git a/include/opencv2/core/cuda_types.hpp b/include/opencv2/core/cuda_types.hpp
index 45dc2ca..b33f061 100755
--- a/include/opencv2/core/cuda_types.hpp
+++ b/include/opencv2/core/cuda_types.hpp
@@ -106,8 +106,8 @@ namespace cv
size_t step;
- __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)DevPtr<T>::data + y * step); }
- __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)DevPtr<T>::data + y * step); }
+ __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)(((DevPtr<T>*)this)->data) + y * step); }
+ __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)(((DevPtr<T>*)this)->data) + y * step); }
__CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; }
__CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; }
diff --git a/include/opencv2/core/cv_cpu_dispatch.h b/include/opencv2/core/cv_cpu_dispatch.h
index 42651ae..540fbb6 100755
--- a/include/opencv2/core/cv_cpu_dispatch.h
+++ b/include/opencv2/core/cv_cpu_dispatch.h
@@ -216,6 +216,11 @@ struct VZeroUpperGuard {
# define CV_VSX 1
#endif
+#ifdef __F16C__
+# include <immintrin.h>
+# define CV_FP16 1
+#endif
+
#endif // !__OPENCV_BUILD && !__CUDACC (Compatibility code)
diff --git a/include/opencv2/core/cvdef.h b/include/opencv2/core/cvdef.h
index 792f59e..6488b8b 100755
--- a/include/opencv2/core/cvdef.h
+++ b/include/opencv2/core/cvdef.h
@@ -84,14 +84,26 @@ namespace cv { namespace debug_build_guard { } using namespace debug_build_guard
#endif
#define __CV_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
-#define __CV_VA_NUM_ARGS(...) __CV_EXPAND(__CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
+#define __CV_VA_NUM_ARGS(...) __CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
-#if defined __GNUC__
+#ifdef CV_Func
+// keep current value (through OpenCV port file)
+#elif defined __GNUC__ || (defined (__cpluscplus) && (__cpluscplus >= 201103))
+#define CV_Func __func__
+#elif defined __clang__ && (__clang_minor__ * 100 + __clang_major__ >= 305)
+#define CV_Func __func__
+#elif defined(__STDC_VERSION__) && (__STDC_VERSION >= 199901)
#define CV_Func __func__
#elif defined _MSC_VER
#define CV_Func __FUNCTION__
+#elif defined(__INTEL_COMPILER) && (_INTEL_COMPILER >= 600)
+#define CV_Func __FUNCTION__
+#elif defined __IBMCPP__ && __IBMCPP__ >=500
+#define CV_Func __FUNCTION__
+#elif defined __BORLAND__ && (__BORLANDC__ >= 0x550)
+#define CV_Func __FUNC__
#else
-#define CV_Func ""
+#define CV_Func "<unknown>"
#endif
//! @cond IGNORED
@@ -158,6 +170,20 @@ namespace cv {
#define CV_UNUSED(name) (void)name
+#if defined __GNUC__ && !defined __EXCEPTIONS
+#define CV_TRY
+#define CV_CATCH(A, B) for (A B; false; )
+#define CV_CATCH_ALL if (false)
+#define CV_THROW(A) abort()
+#define CV_RETHROW() abort()
+#else
+#define CV_TRY try
+#define CV_CATCH(A, B) catch(const A & B)
+#define CV_CATCH_ALL catch(...)
+#define CV_THROW(A) throw A
+#define CV_RETHROW() throw
+#endif
+
//! @endcond
// undef problematic defines sometimes defined by system headers (windows.h in particular)
@@ -167,7 +193,12 @@ namespace cv {
#undef abs
#undef Complex
+#if defined __cplusplus
+#include <limits>
+#else
#include <limits.h>
+#endif
+
#include "opencv2/core/hal/interface.h"
#if defined __ICL
@@ -321,6 +352,13 @@ enum CpuFeatures {
#include "cv_cpu_dispatch.h"
+#if !defined(CV_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64))
+// int*, int64* should be propertly aligned pointers on ARMv7
+#define CV_STRONG_ALIGNMENT 1
+#endif
+#if !defined(CV_STRONG_ALIGNMENT)
+#define CV_STRONG_ALIGNMENT 0
+#endif
/* fundamental constants */
#define CV_PI 3.1415926535897932384626433832795
@@ -360,10 +398,10 @@ typedef union Cv64suf
}
Cv64suf;
-#define OPENCV_ABI_COMPATIBILITY 400
+#define OPENCV_ABI_COMPATIBILITY 300
#ifdef __OPENCV_BUILD
-# define DISABLE_OPENCV_3_COMPATIBILITY
+# define DISABLE_OPENCV_24_COMPATIBILITY
# define OPENCV_DISABLE_DEPRECATED_COMPATIBILITY
#endif
@@ -423,9 +461,6 @@ Cv64suf;
#define CV_PROP_RW
#define CV_WRAP
#define CV_WRAP_AS(synonym)
-#define CV_WRAP_MAPPABLE(mappable)
-#define CV_WRAP_PHANTOM(phantom_header)
-#define CV_WRAP_DEFAULT(val)
/****************************************************************************************\
* Matrix type (Mat) *
@@ -444,10 +479,13 @@ Cv64suf;
#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG)
/** Size of each channel item,
- 0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
-#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15)
+ 0x8442211 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
+#define CV_ELEM_SIZE1(type) \
+ ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15)
-#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type))
+/** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */
+#define CV_ELEM_SIZE(type) \
+ (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3))
#ifndef MIN
# define MIN(a,b) ((a) > (b) ? (b) : (a))
@@ -457,142 +495,6 @@ Cv64suf;
# define MAX(a,b) ((a) < (b) ? (b) : (a))
#endif
-///////////////////////////////////////// Enum operators ///////////////////////////////////////
-
-/**
-
-Provides compatibility operators for both classical and C++11 enum classes,
-as well as exposing the C++11 enum class members for backwards compatibility
-
-@code
- // Provides operators required for flag enums
- CV_ENUM_FLAGS(AccessFlag)
-
- // Exposes the listed members of the enum class AccessFlag to the current namespace
- CV_ENUM_CLASS_EXPOSE(AccessFlag, ACCESS_READ [, ACCESS_WRITE [, ...] ]);
-@endcode
-*/
-
-#define __CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST) \
-static const EnumType MEMBER_CONST = EnumType::MEMBER_CONST; \
-
-#define __CV_ENUM_CLASS_EXPOSE_2(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_1(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_3(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_2(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_4(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_3(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_5(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_4(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_6(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_5(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_7(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_6(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_8(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_7(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_CLASS_EXPOSE_9(EnumType, MEMBER_CONST, ...) \
-__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \
-__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_8(EnumType, __VA_ARGS__)); \
-
-#define __CV_ENUM_FLAGS_LOGICAL_NOT(EnumType) \
-static inline bool operator!(const EnumType& val) \
-{ \
- typedef std::underlying_type<EnumType>::type UnderlyingType; \
- return !static_cast<UnderlyingType>(val); \
-} \
-
-#define __CV_ENUM_FLAGS_LOGICAL_NOT_EQ(Arg1Type, Arg2Type) \
-static inline bool operator!=(const Arg1Type& a, const Arg2Type& b) \
-{ \
- return static_cast<int>(a) != static_cast<int>(b); \
-} \
-
-#define __CV_ENUM_FLAGS_LOGICAL_EQ(Arg1Type, Arg2Type) \
-static inline bool operator==(const Arg1Type& a, const Arg2Type& b) \
-{ \
- return static_cast<int>(a) == static_cast<int>(b); \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_NOT(EnumType) \
-static inline EnumType operator~(const EnumType& val) \
-{ \
- typedef std::underlying_type<EnumType>::type UnderlyingType; \
- return static_cast<EnumType>(~static_cast<UnderlyingType>(val)); \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_OR(EnumType, Arg1Type, Arg2Type) \
-static inline EnumType operator|(const Arg1Type& a, const Arg2Type& b) \
-{ \
- typedef std::underlying_type<EnumType>::type UnderlyingType; \
- return static_cast<EnumType>(static_cast<UnderlyingType>(a) | static_cast<UnderlyingType>(b)); \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \
-static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \
-{ \
- typedef std::underlying_type<EnumType>::type UnderlyingType; \
- return static_cast<EnumType>(static_cast<UnderlyingType>(a) & static_cast<UnderlyingType>(b)); \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_XOR(EnumType, Arg1Type, Arg2Type) \
-static inline EnumType operator^(const Arg1Type& a, const Arg2Type& b) \
-{ \
- typedef std::underlying_type<EnumType>::type UnderlyingType; \
- return static_cast<EnumType>(static_cast<UnderlyingType>(a) ^ static_cast<UnderlyingType>(b)); \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_OR_EQ(EnumType, Arg1Type) \
-static inline EnumType& operator|=(EnumType& _this, const Arg1Type& val) \
-{ \
- _this = static_cast<EnumType>(static_cast<int>(_this) | static_cast<int>(val)); \
- return _this; \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_AND_EQ(EnumType, Arg1Type) \
-static inline EnumType& operator&=(EnumType& _this, const Arg1Type& val) \
-{ \
- _this = static_cast<EnumType>(static_cast<int>(_this) & static_cast<int>(val)); \
- return _this; \
-} \
-
-#define __CV_ENUM_FLAGS_BITWISE_XOR_EQ(EnumType, Arg1Type) \
-static inline EnumType& operator^=(EnumType& _this, const Arg1Type& val) \
-{ \
- _this = static_cast<EnumType>(static_cast<int>(_this) ^ static_cast<int>(val)); \
- return _this; \
-} \
-
-#define CV_ENUM_CLASS_EXPOSE(EnumType, ...) \
-__CV_EXPAND(__CV_CAT(__CV_ENUM_CLASS_EXPOSE_, __CV_VA_NUM_ARGS(__VA_ARGS__))(EnumType, __VA_ARGS__)); \
-
-#define CV_ENUM_FLAGS(EnumType) \
-__CV_ENUM_FLAGS_LOGICAL_NOT (EnumType) \
-__CV_ENUM_FLAGS_LOGICAL_EQ (EnumType, int) \
-__CV_ENUM_FLAGS_LOGICAL_NOT_EQ (EnumType, int) \
- \
-__CV_ENUM_FLAGS_BITWISE_NOT (EnumType) \
-__CV_ENUM_FLAGS_BITWISE_OR (EnumType, EnumType, EnumType) \
-__CV_ENUM_FLAGS_BITWISE_AND (EnumType, EnumType, EnumType) \
-__CV_ENUM_FLAGS_BITWISE_XOR (EnumType, EnumType, EnumType) \
- \
-__CV_ENUM_FLAGS_BITWISE_OR_EQ (EnumType, EnumType) \
-__CV_ENUM_FLAGS_BITWISE_AND_EQ (EnumType, EnumType) \
-__CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType) \
-
/****************************************************************************************\
* static analysys *
\****************************************************************************************/
@@ -700,21 +602,75 @@ __CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType)
# undef CV_CXX11
# endif
#endif
-#ifndef CV_CXX11
-# error "OpenCV 4.x+ requires enabled C++11 support"
+
+
+/****************************************************************************************\
+* C++ Move semantics *
+\****************************************************************************************/
+
+#ifndef CV_CXX_MOVE_SEMANTICS
+# if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || (defined(_MSC_VER) && _MSC_VER >= 1600)
+# define CV_CXX_MOVE_SEMANTICS 1
+# elif defined(__clang)
+# if __has_feature(cxx_rvalue_references)
+# define CV_CXX_MOVE_SEMANTICS 1
+# endif
+# endif
+#else
+# if CV_CXX_MOVE_SEMANTICS == 0
+# undef CV_CXX_MOVE_SEMANTICS
+# endif
#endif
-#define CV_CXX_MOVE_SEMANTICS 1
+#ifdef CV_CXX_MOVE_SEMANTICS
#define CV_CXX_MOVE(x) std::move(x)
-#define CV_CXX_STD_ARRAY 1
-#include <array>
+#else
+#define CV_CXX_MOVE(x) (x)
+#endif
+
+
+/****************************************************************************************\
+* C++11 std::array *
+\****************************************************************************************/
+
+#ifndef CV_CXX_STD_ARRAY
+# if __cplusplus >= 201103L || (defined(__cplusplus) && defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/)
+# define CV_CXX_STD_ARRAY 1
+# include <array>
+# endif
+#else
+# if CV_CXX_STD_ARRAY == 0
+# undef CV_CXX_STD_ARRAY
+# endif
+#endif
+
+
+/****************************************************************************************\
+* C++11 override / final *
+\****************************************************************************************/
+
#ifndef CV_OVERRIDE
-# define CV_OVERRIDE override
+# ifdef CV_CXX11
+# define CV_OVERRIDE override
+# endif
+#endif
+#ifndef CV_OVERRIDE
+# define CV_OVERRIDE
+#endif
+
+#ifndef CV_FINAL
+# ifdef CV_CXX11
+# define CV_FINAL final
+# endif
#endif
#ifndef CV_FINAL
-# define CV_FINAL final
+# define CV_FINAL
#endif
+/****************************************************************************************\
+* C++11 noexcept *
+\****************************************************************************************/
+
#ifndef CV_NOEXCEPT
# if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/)
# define CV_NOEXCEPT noexcept
@@ -724,14 +680,7 @@ __CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType)
# define CV_NOEXCEPT
#endif
-#ifndef CV_CONSTEXPR
-# if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/)
-# define CV_CONSTEXPR constexpr
-# endif
-#endif
-#ifndef CV_CONSTEXPR
-# define CV_CONSTEXPR
-#endif
+
// Integer types portatibility
#ifdef OPENCV_STDINT_HEADER
@@ -786,7 +735,7 @@ class float16_t
public:
#if CV_FP16_TYPE
- float16_t() : h(0) {}
+ float16_t() {}
explicit float16_t(float x) { h = (__fp16)x; }
operator float() const { return (float)h; }
static float16_t fromBits(ushort w)
@@ -813,10 +762,10 @@ protected:
__fp16 h;
#else
- float16_t() : w(0) {}
+ float16_t() {}
explicit float16_t(float x)
{
- #if CV_AVX2
+ #if CV_FP16
__m128 v = _mm_load_ss(&x);
w = (ushort)_mm_cvtsi128_si32(_mm_cvtps_ph(v, 0));
#else
@@ -847,7 +796,7 @@ protected:
operator float() const
{
- #if CV_AVX2
+ #if CV_FP16
float f;
_mm_store_ss(&f, _mm_cvtph_ps(_mm_cvtsi32_si128(w)));
return f;
@@ -860,7 +809,7 @@ protected:
out.u = t + (1 << 23);
out.u = (e >= 0x7c00 ? t + 0x38000000 :
- e == 0 ? (static_cast<void>(out.f -= 6.103515625e-05f), out.u) : t) | sign;
+ e == 0 ? (out.f -= 6.103515625e-05f, out.u) : t) | sign;
return out.f;
#endif
}
diff --git a/include/opencv2/core/cvstd.hpp b/include/opencv2/core/cvstd.hpp
index 6ce9e4b..fbf6d31 100755
--- a/include/opencv2/core/cvstd.hpp
+++ b/include/opencv2/core/cvstd.hpp
@@ -78,8 +78,6 @@ namespace cv
using std::log;
}
-#include "cvstd_wrapper.hpp"
-
namespace cv {
//! @addtogroup core_utils
@@ -140,16 +138,894 @@ public:
//! @} core_utils
+//! @cond IGNORED
+
+namespace detail
+{
+
+// Metafunction to avoid taking a reference to void.
+template<typename T>
+struct RefOrVoid { typedef T& type; };
+
+template<>
+struct RefOrVoid<void>{ typedef void type; };
+
+template<>
+struct RefOrVoid<const void>{ typedef const void type; };
+
+template<>
+struct RefOrVoid<volatile void>{ typedef volatile void type; };
+
+template<>
+struct RefOrVoid<const volatile void>{ typedef const volatile void type; };
+
+// This class would be private to Ptr, if it didn't have to be a non-template.
+struct PtrOwner;
+
+}
+
+template<typename Y>
+struct DefaultDeleter
+{
+ void operator () (Y* p) const;
+};
+
//! @endcond
//! @addtogroup core_basic
//! @{
+/** @brief Template class for smart pointers with shared ownership
+
+A Ptr\<T\> pretends to be a pointer to an object of type T. Unlike an ordinary pointer, however, the
+object will be automatically cleaned up once all Ptr instances pointing to it are destroyed.
+
+Ptr is similar to boost::shared_ptr that is part of the Boost library
+(<http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm>) and std::shared_ptr from
+the [C++11](http://en.wikipedia.org/wiki/C++11) standard.
+
+This class provides the following advantages:
+- Default constructor, copy constructor, and assignment operator for an arbitrary C++ class or C
+ structure. For some objects, like files, windows, mutexes, sockets, and others, a copy
+ constructor or an assignment operator are difficult to define. For some other objects, like
+ complex classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally,
+ some of complex OpenCV and your own data structures may be written in C. However, copy
+ constructors and default constructors can simplify programming a lot. Besides, they are often
+ required (for example, by STL containers). By using a Ptr to such an object instead of the
+ object itself, you automatically get all of the necessary constructors and the assignment
+ operator.
+- *O(1)* complexity of the above-mentioned operations. While some structures, like std::vector,
+ provide a copy constructor and an assignment operator, the operations may take a considerable
+ amount of time if the data structures are large. But if the structures are put into a Ptr, the
+ overhead is small and independent of the data size.
+- Automatic and customizable cleanup, even for C structures. See the example below with FILE\*.
+- Heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers
+ can store only objects of the same type and the same size. The classical solution to store
+ objects of different types in the same container is to store pointers to the base class (Base\*)
+ instead but then you lose the automatic memory management. Again, by using Ptr\<Base\> instead
+ of raw pointers, you can solve the problem.
+
+A Ptr is said to *own* a pointer - that is, for each Ptr there is a pointer that will be deleted
+once all Ptr instances that own it are destroyed. The owned pointer may be null, in which case
+nothing is deleted. Each Ptr also *stores* a pointer. The stored pointer is the pointer the Ptr
+pretends to be; that is, the one you get when you use Ptr::get or the conversion to T\*. It's
+usually the same as the owned pointer, but if you use casts or the general shared-ownership
+constructor, the two may diverge: the Ptr will still own the original pointer, but will itself point
+to something else.
+
+The owned pointer is treated as a black box. The only thing Ptr needs to know about it is how to
+delete it. This knowledge is encapsulated in the *deleter* - an auxiliary object that is associated
+with the owned pointer and shared between all Ptr instances that own it. The default deleter is an
+instance of DefaultDeleter, which uses the standard C++ delete operator; as such it will work with
+any pointer allocated with the standard new operator.
+
+However, if the pointer must be deleted in a different way, you must specify a custom deleter upon
+Ptr construction. A deleter is simply a callable object that accepts the pointer as its sole
+argument. For example, if you want to wrap FILE, you may do so as follows:
+@code
+ Ptr<FILE> f(fopen("myfile.txt", "w"), fclose);
+ if(!f) throw ...;
+ fprintf(f, ....);
+ ...
+ // the file will be closed automatically by f's destructor.
+@endcode
+Alternatively, if you want all pointers of a particular type to be deleted the same way, you can
+specialize DefaultDeleter<T>::operator() for that type, like this:
+@code
+ namespace cv {
+ template<> void DefaultDeleter<FILE>::operator ()(FILE * obj) const
+ {
+ fclose(obj);
+ }
+ }
+@endcode
+For convenience, the following types from the OpenCV C API already have such a specialization that
+calls the appropriate release function:
+- CvCapture
+- CvFileStorage
+- CvHaarClassifierCascade
+- CvMat
+- CvMatND
+- CvMemStorage
+- CvSparseMat
+- CvVideoWriter
+- IplImage
+@note The shared ownership mechanism is implemented with reference counting. As such, cyclic
+ownership (e.g. when object a contains a Ptr to object b, which contains a Ptr to object a) will
+lead to all involved objects never being cleaned up. Avoid such situations.
+@note It is safe to concurrently read (but not write) a Ptr instance from multiple threads and
+therefore it is normally safe to use it in multi-threaded applications. The same is true for Mat and
+other C++ OpenCV classes that use internal reference counts.
+*/
+template<typename T>
+struct Ptr
+{
+ /** Generic programming support. */
+ typedef T element_type;
+
+ /** The default constructor creates a null Ptr - one that owns and stores a null pointer.
+ */
+ Ptr();
+
+ /**
+ If p is null, these are equivalent to the default constructor.
+ Otherwise, these constructors assume ownership of p - that is, the created Ptr owns and stores p
+ and assumes it is the sole owner of it. Don't use them if p is already owned by another Ptr, or
+ else p will get deleted twice.
+ With the first constructor, DefaultDeleter\<Y\>() becomes the associated deleter (so p will
+ eventually be deleted with the standard delete operator). Y must be a complete type at the point
+ of invocation.
+ With the second constructor, d becomes the associated deleter.
+ Y\* must be convertible to T\*.
+ @param p Pointer to own.
+ @note It is often easier to use makePtr instead.
+ */
+ template<typename Y>
+#ifdef DISABLE_OPENCV_24_COMPATIBILITY
+ explicit
+#endif
+ Ptr(Y* p);
+
+ /** @overload
+ @param d Deleter to use for the owned pointer.
+ @param p Pointer to own.
+ */
+ template<typename Y, typename D>
+ Ptr(Y* p, D d);
+
+ /**
+ These constructors create a Ptr that shares ownership with another Ptr - that is, own the same
+ pointer as o.
+ With the first two, the same pointer is stored, as well; for the second, Y\* must be convertible
+ to T\*.
+ With the third, p is stored, and Y may be any type. This constructor allows to have completely
+ unrelated owned and stored pointers, and should be used with care to avoid confusion. A relatively
+ benign use is to create a non-owning Ptr, like this:
+ @code
+ ptr = Ptr<T>(Ptr<T>(), dont_delete_me); // owns nothing; will not delete the pointer.
+ @endcode
+ @param o Ptr to share ownership with.
+ */
+ Ptr(const Ptr& o);
+
+ /** @overload
+ @param o Ptr to share ownership with.
+ */
+ template<typename Y>
+ Ptr(const Ptr<Y>& o);
+
+ /** @overload
+ @param o Ptr to share ownership with.
+ @param p Pointer to store.
+ */
+ template<typename Y>
+ Ptr(const Ptr<Y>& o, T* p);
+
+ /** The destructor is equivalent to calling Ptr::release. */
+ ~Ptr();
+
+ /**
+ Assignment replaces the current Ptr instance with one that owns and stores same pointers as o and
+ then destroys the old instance.
+ @param o Ptr to share ownership with.
+ */
+ Ptr& operator = (const Ptr& o);
+
+ /** @overload */
+ template<typename Y>
+ Ptr& operator = (const Ptr<Y>& o);
+
+ /** If no other Ptr instance owns the owned pointer, deletes it with the associated deleter. Then sets
+ both the owned and the stored pointers to NULL.
+ */
+ void release();
+
+ /**
+ `ptr.reset(...)` is equivalent to `ptr = Ptr<T>(...)`.
+ @param p Pointer to own.
+ */
+ template<typename Y>
+ void reset(Y* p);
+
+ /** @overload
+ @param d Deleter to use for the owned pointer.
+ @param p Pointer to own.
+ */
+ template<typename Y, typename D>
+ void reset(Y* p, D d);
+
+ /**
+ Swaps the owned and stored pointers (and deleters, if any) of this and o.
+ @param o Ptr to swap with.
+ */
+ void swap(Ptr& o);
+
+ /** Returns the stored pointer. */
+ T* get() const;
+
+ /** Ordinary pointer emulation. */
+ typename detail::RefOrVoid<T>::type operator * () const;
+
+ /** Ordinary pointer emulation. */
+ T* operator -> () const;
+
+ /** Equivalent to get(). */
+ operator T* () const;
+
+ /** ptr.empty() is equivalent to `!ptr.get()`. */
+ bool empty() const;
+
+ /** Returns a Ptr that owns the same pointer as this, and stores the same
+ pointer as this, except converted via static_cast to Y*.
+ */
+ template<typename Y>
+ Ptr<Y> staticCast() const;
+
+ /** Ditto for const_cast. */
+ template<typename Y>
+ Ptr<Y> constCast() const;
+
+ /** Ditto for dynamic_cast. */
+ template<typename Y>
+ Ptr<Y> dynamicCast() const;
+
+#ifdef CV_CXX_MOVE_SEMANTICS
+ Ptr(Ptr&& o);
+ Ptr& operator = (Ptr&& o);
+#endif
+
+private:
+ detail::PtrOwner* owner;
+ T* stored;
+
+ template<typename Y>
+ friend struct Ptr; // have to do this for the cross-type copy constructor
+};
+
+/** Equivalent to ptr1.swap(ptr2). Provided to help write generic algorithms. */
+template<typename T>
+void swap(Ptr<T>& ptr1, Ptr<T>& ptr2);
+
+/** Return whether ptr1.get() and ptr2.get() are equal and not equal, respectively. */
+template<typename T>
+bool operator == (const Ptr<T>& ptr1, const Ptr<T>& ptr2);
+template<typename T>
+bool operator != (const Ptr<T>& ptr1, const Ptr<T>& ptr2);
+
+/** `makePtr<T>(...)` is equivalent to `Ptr<T>(new T(...))`. It is shorter than the latter, and it's
+marginally safer than using a constructor or Ptr::reset, since it ensures that the owned pointer
+is new and thus not owned by any other Ptr instance.
+Unfortunately, perfect forwarding is impossible to implement in C++03, and so makePtr is limited
+to constructors of T that have up to 10 arguments, none of which are non-const references.
+ */
+template<typename T>
+Ptr<T> makePtr();
+/** @overload */
+template<typename T, typename A1>
+Ptr<T> makePtr(const A1& a1);
+/** @overload */
+template<typename T, typename A1, typename A2>
+Ptr<T> makePtr(const A1& a1, const A2& a2);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9);
+/** @overload */
+template<typename T, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10>
+Ptr<T> makePtr(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10);
+
//////////////////////////////// string class ////////////////////////////////
class CV_EXPORTS FileNode; //for string constructor from FileNode
-typedef std::string String;
+class CV_EXPORTS String
+{
+public:
+ typedef char value_type;
+ typedef char& reference;
+ typedef const char& const_reference;
+ typedef char* pointer;
+ typedef const char* const_pointer;
+ typedef ptrdiff_t difference_type;
+ typedef size_t size_type;
+ typedef char* iterator;
+ typedef const char* const_iterator;
+
+ static const size_t npos = size_t(-1);
+
+ String();
+ String(const String& str);
+ String(const String& str, size_t pos, size_t len = npos);
+ String(const char* s);
+ String(const char* s, size_t n);
+ String(size_t n, char c);
+ String(const char* first, const char* last);
+ template<typename Iterator> String(Iterator first, Iterator last);
+ explicit String(const FileNode& fn);
+ ~String();
+
+ String& operator=(const String& str);
+ String& operator=(const char* s);
+ String& operator=(char c);
+
+ String& operator+=(const String& str);
+ String& operator+=(const char* s);
+ String& operator+=(char c);
+
+ size_t size() const;
+ size_t length() const;
+
+ char operator[](size_t idx) const;
+ char operator[](int idx) const;
+
+ const char* begin() const;
+ const char* end() const;
+
+ const char* c_str() const;
+
+ bool empty() const;
+ void clear();
+
+ int compare(const char* s) const;
+ int compare(const String& str) const;
+
+ void swap(String& str);
+ String substr(size_t pos = 0, size_t len = npos) const;
+
+ size_t find(const char* s, size_t pos, size_t n) const;
+ size_t find(char c, size_t pos = 0) const;
+ size_t find(const String& str, size_t pos = 0) const;
+ size_t find(const char* s, size_t pos = 0) const;
+
+ size_t rfind(const char* s, size_t pos, size_t n) const;
+ size_t rfind(char c, size_t pos = npos) const;
+ size_t rfind(const String& str, size_t pos = npos) const;
+ size_t rfind(const char* s, size_t pos = npos) const;
+
+ size_t find_first_of(const char* s, size_t pos, size_t n) const;
+ size_t find_first_of(char c, size_t pos = 0) const;
+ size_t find_first_of(const String& str, size_t pos = 0) const;
+ size_t find_first_of(const char* s, size_t pos = 0) const;
+
+ size_t find_last_of(const char* s, size_t pos, size_t n) const;
+ size_t find_last_of(char c, size_t pos = npos) const;
+ size_t find_last_of(const String& str, size_t pos = npos) const;
+ size_t find_last_of(const char* s, size_t pos = npos) const;
+
+ friend String operator+ (const String& lhs, const String& rhs);
+ friend String operator+ (const String& lhs, const char* rhs);
+ friend String operator+ (const char* lhs, const String& rhs);
+ friend String operator+ (const String& lhs, char rhs);
+ friend String operator+ (char lhs, const String& rhs);
+
+ String toLowerCase() const;
+
+ String(const std::string& str);
+ String(const std::string& str, size_t pos, size_t len = npos);
+ String& operator=(const std::string& str);
+ String& operator+=(const std::string& str);
+ operator std::string() const;
+
+ friend String operator+ (const String& lhs, const std::string& rhs);
+ friend String operator+ (const std::string& lhs, const String& rhs);
+
+private:
+ char* cstr_;
+ size_t len_;
+
+ char* allocate(size_t len); // len without trailing 0
+ void deallocate();
+
+ String(int); // disabled and invalid. Catch invalid usages like, commandLineParser.has(0) problem
+};
+
+//! @} core_basic
+
+////////////////////////// cv::String implementation /////////////////////////
+
+//! @cond IGNORED
+
+inline
+String::String()
+ : cstr_(0), len_(0)
+{}
+
+inline
+String::String(const String& str)
+ : cstr_(str.cstr_), len_(str.len_)
+{
+ if (cstr_)
+ CV_XADD(((int*)cstr_)-1, 1);
+}
+
+inline
+String::String(const String& str, size_t pos, size_t len)
+ : cstr_(0), len_(0)
+{
+ pos = min(pos, str.len_);
+ len = min(str.len_ - pos, len);
+ if (!len) return;
+ if (len == str.len_)
+ {
+ CV_XADD(((int*)str.cstr_)-1, 1);
+ cstr_ = str.cstr_;
+ len_ = str.len_;
+ return;
+ }
+ memcpy(allocate(len), str.cstr_ + pos, len);
+}
+
+inline
+String::String(const char* s)
+ : cstr_(0), len_(0)
+{
+ if (!s) return;
+ size_t len = strlen(s);
+ if (!len) return;
+ memcpy(allocate(len), s, len);
+}
+
+inline
+String::String(const char* s, size_t n)
+ : cstr_(0), len_(0)
+{
+ if (!n) return;
+ if (!s) return;
+ memcpy(allocate(n), s, n);
+}
+
+inline
+String::String(size_t n, char c)
+ : cstr_(0), len_(0)
+{
+ if (!n) return;
+ memset(allocate(n), c, n);
+}
+
+inline
+String::String(const char* first, const char* last)
+ : cstr_(0), len_(0)
+{
+ size_t len = (size_t)(last - first);
+ if (!len) return;
+ memcpy(allocate(len), first, len);
+}
+
+template<typename Iterator> inline
+String::String(Iterator first, Iterator last)
+ : cstr_(0), len_(0)
+{
+ size_t len = (size_t)(last - first);
+ if (!len) return;
+ char* str = allocate(len);
+ while (first != last)
+ {
+ *str++ = *first;
+ ++first;
+ }
+}
+
+inline
+String::~String()
+{
+ deallocate();
+}
+
+inline
+String& String::operator=(const String& str)
+{
+ if (&str == this) return *this;
+
+ deallocate();
+ if (str.cstr_) CV_XADD(((int*)str.cstr_)-1, 1);
+ cstr_ = str.cstr_;
+ len_ = str.len_;
+ return *this;
+}
+
+inline
+String& String::operator=(const char* s)
+{
+ deallocate();
+ if (!s) return *this;
+ size_t len = strlen(s);
+ if (len) memcpy(allocate(len), s, len);
+ return *this;
+}
+
+inline
+String& String::operator=(char c)
+{
+ deallocate();
+ allocate(1)[0] = c;
+ return *this;
+}
+
+inline
+String& String::operator+=(const String& str)
+{
+ *this = *this + str;
+ return *this;
+}
+
+inline
+String& String::operator+=(const char* s)
+{
+ *this = *this + s;
+ return *this;
+}
+
+inline
+String& String::operator+=(char c)
+{
+ *this = *this + c;
+ return *this;
+}
+
+inline
+size_t String::size() const
+{
+ return len_;
+}
+
+inline
+size_t String::length() const
+{
+ return len_;
+}
+
+inline
+char String::operator[](size_t idx) const
+{
+ return cstr_[idx];
+}
+
+inline
+char String::operator[](int idx) const
+{
+ return cstr_[idx];
+}
+
+inline
+const char* String::begin() const
+{
+ return cstr_;
+}
+
+inline
+const char* String::end() const
+{
+ return len_ ? cstr_ + len_ : NULL;
+}
+
+inline
+bool String::empty() const
+{
+ return len_ == 0;
+}
+
+inline
+const char* String::c_str() const
+{
+ return cstr_ ? cstr_ : "";
+}
+
+inline
+void String::swap(String& str)
+{
+ cv::swap(cstr_, str.cstr_);
+ cv::swap(len_, str.len_);
+}
+
+inline
+void String::clear()
+{
+ deallocate();
+}
+
+inline
+int String::compare(const char* s) const
+{
+ if (cstr_ == s) return 0;
+ return strcmp(c_str(), s);
+}
+
+inline
+int String::compare(const String& str) const
+{
+ if (cstr_ == str.cstr_) return 0;
+ return strcmp(c_str(), str.c_str());
+}
+
+inline
+String String::substr(size_t pos, size_t len) const
+{
+ return String(*this, pos, len);
+}
+
+inline
+size_t String::find(const char* s, size_t pos, size_t n) const
+{
+ if (n == 0 || pos + n > len_) return npos;
+ const char* lmax = cstr_ + len_ - n;
+ for (const char* i = cstr_ + pos; i <= lmax; ++i)
+ {
+ size_t j = 0;
+ while (j < n && s[j] == i[j]) ++j;
+ if (j == n) return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::find(char c, size_t pos) const
+{
+ return find(&c, pos, 1);
+}
+
+inline
+size_t String::find(const String& str, size_t pos) const
+{
+ return find(str.c_str(), pos, str.len_);
+}
+
+inline
+size_t String::find(const char* s, size_t pos) const
+{
+ if (pos >= len_ || !s[0]) return npos;
+ const char* lmax = cstr_ + len_;
+ for (const char* i = cstr_ + pos; i < lmax; ++i)
+ {
+ size_t j = 0;
+ while (s[j] && s[j] == i[j])
+ { if(i + j >= lmax) return npos;
+ ++j;
+ }
+ if (!s[j]) return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::rfind(const char* s, size_t pos, size_t n) const
+{
+ if (n > len_) return npos;
+ if (pos > len_ - n) pos = len_ - n;
+ for (const char* i = cstr_ + pos; i >= cstr_; --i)
+ {
+ size_t j = 0;
+ while (j < n && s[j] == i[j]) ++j;
+ if (j == n) return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::rfind(char c, size_t pos) const
+{
+ return rfind(&c, pos, 1);
+}
+
+inline
+size_t String::rfind(const String& str, size_t pos) const
+{
+ return rfind(str.c_str(), pos, str.len_);
+}
+
+inline
+size_t String::rfind(const char* s, size_t pos) const
+{
+ return rfind(s, pos, strlen(s));
+}
+
+inline
+size_t String::find_first_of(const char* s, size_t pos, size_t n) const
+{
+ if (n == 0 || pos + n > len_) return npos;
+ const char* lmax = cstr_ + len_;
+ for (const char* i = cstr_ + pos; i < lmax; ++i)
+ {
+ for (size_t j = 0; j < n; ++j)
+ if (s[j] == *i)
+ return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::find_first_of(char c, size_t pos) const
+{
+ return find_first_of(&c, pos, 1);
+}
+
+inline
+size_t String::find_first_of(const String& str, size_t pos) const
+{
+ return find_first_of(str.c_str(), pos, str.len_);
+}
+
+inline
+size_t String::find_first_of(const char* s, size_t pos) const
+{
+ if (len_ == 0) return npos;
+ if (pos >= len_ || !s[0]) return npos;
+ const char* lmax = cstr_ + len_;
+ for (const char* i = cstr_ + pos; i < lmax; ++i)
+ {
+ for (size_t j = 0; s[j]; ++j)
+ if (s[j] == *i)
+ return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::find_last_of(const char* s, size_t pos, size_t n) const
+{
+ if (len_ == 0) return npos;
+ if (pos >= len_) pos = len_ - 1;
+ for (const char* i = cstr_ + pos; i >= cstr_; --i)
+ {
+ for (size_t j = 0; j < n; ++j)
+ if (s[j] == *i)
+ return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+size_t String::find_last_of(char c, size_t pos) const
+{
+ return find_last_of(&c, pos, 1);
+}
+
+inline
+size_t String::find_last_of(const String& str, size_t pos) const
+{
+ return find_last_of(str.c_str(), pos, str.len_);
+}
+
+inline
+size_t String::find_last_of(const char* s, size_t pos) const
+{
+ if (len_ == 0) return npos;
+ if (pos >= len_) pos = len_ - 1;
+ for (const char* i = cstr_ + pos; i >= cstr_; --i)
+ {
+ for (size_t j = 0; s[j]; ++j)
+ if (s[j] == *i)
+ return (size_t)(i - cstr_);
+ }
+ return npos;
+}
+
+inline
+String String::toLowerCase() const
+{
+ if (!cstr_)
+ return String();
+ String res(cstr_, len_);
+ for (size_t i = 0; i < len_; ++i)
+ res.cstr_[i] = (char) ::tolower(cstr_[i]);
+
+ return res;
+}
+
+//! @endcond
+
+// ************************* cv::String non-member functions *************************
+
+//! @relates cv::String
+//! @{
+
+inline
+String operator + (const String& lhs, const String& rhs)
+{
+ String s;
+ s.allocate(lhs.len_ + rhs.len_);
+ if (lhs.len_) memcpy(s.cstr_, lhs.cstr_, lhs.len_);
+ if (rhs.len_) memcpy(s.cstr_ + lhs.len_, rhs.cstr_, rhs.len_);
+ return s;
+}
+
+inline
+String operator + (const String& lhs, const char* rhs)
+{
+ String s;
+ size_t rhslen = strlen(rhs);
+ s.allocate(lhs.len_ + rhslen);
+ if (lhs.len_) memcpy(s.cstr_, lhs.cstr_, lhs.len_);
+ if (rhslen) memcpy(s.cstr_ + lhs.len_, rhs, rhslen);
+ return s;
+}
+
+inline
+String operator + (const char* lhs, const String& rhs)
+{
+ String s;
+ size_t lhslen = strlen(lhs);
+ s.allocate(lhslen + rhs.len_);
+ if (lhslen) memcpy(s.cstr_, lhs, lhslen);
+ if (rhs.len_) memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_);
+ return s;
+}
+
+inline
+String operator + (const String& lhs, char rhs)
+{
+ String s;
+ s.allocate(lhs.len_ + 1);
+ if (lhs.len_) memcpy(s.cstr_, lhs.cstr_, lhs.len_);
+ s.cstr_[lhs.len_] = rhs;
+ return s;
+}
+
+inline
+String operator + (char lhs, const String& rhs)
+{
+ String s;
+ s.allocate(rhs.len_ + 1);
+ s.cstr_[0] = lhs;
+ if (rhs.len_) memcpy(s.cstr_ + 1, rhs.cstr_, rhs.len_);
+ return s;
+}
+
+static inline bool operator== (const String& lhs, const String& rhs) { return 0 == lhs.compare(rhs); }
+static inline bool operator== (const char* lhs, const String& rhs) { return 0 == rhs.compare(lhs); }
+static inline bool operator== (const String& lhs, const char* rhs) { return 0 == lhs.compare(rhs); }
+static inline bool operator!= (const String& lhs, const String& rhs) { return 0 != lhs.compare(rhs); }
+static inline bool operator!= (const char* lhs, const String& rhs) { return 0 != rhs.compare(lhs); }
+static inline bool operator!= (const String& lhs, const char* rhs) { return 0 != lhs.compare(rhs); }
+static inline bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; }
+static inline bool operator< (const char* lhs, const String& rhs) { return rhs.compare(lhs) > 0; }
+static inline bool operator< (const String& lhs, const char* rhs) { return lhs.compare(rhs) < 0; }
+static inline bool operator<= (const String& lhs, const String& rhs) { return lhs.compare(rhs) <= 0; }
+static inline bool operator<= (const char* lhs, const String& rhs) { return rhs.compare(lhs) >= 0; }
+static inline bool operator<= (const String& lhs, const char* rhs) { return lhs.compare(rhs) <= 0; }
+static inline bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; }
+static inline bool operator> (const char* lhs, const String& rhs) { return rhs.compare(lhs) < 0; }
+static inline bool operator> (const String& lhs, const char* rhs) { return lhs.compare(rhs) > 0; }
+static inline bool operator>= (const String& lhs, const String& rhs) { return lhs.compare(rhs) >= 0; }
+static inline bool operator>= (const char* lhs, const String& rhs) { return rhs.compare(lhs) <= 0; }
+static inline bool operator>= (const String& lhs, const char* rhs) { return lhs.compare(rhs) >= 0; }
+
#ifndef OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS
@@ -184,7 +1060,15 @@ static inline std::string toUpperCase(const std::string& str)
#endif // OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS
-//! @} core_basic
+//! @} relates cv::String
+
} // cv
+namespace std
+{
+ static inline void swap(cv::String& a, cv::String& b) { a.swap(b); }
+}
+
+#include "opencv2/core/ptr.inl.hpp"
+
#endif //OPENCV_CORE_CVSTD_HPP
diff --git a/include/opencv2/core/cvstd.inl.hpp b/include/opencv2/core/cvstd.inl.hpp
index 4a85bfd..36c83e2 100755
--- a/include/opencv2/core/cvstd.inl.hpp
+++ b/include/opencv2/core/cvstd.inl.hpp
@@ -46,6 +46,7 @@
#include <complex>
#include <ostream>
+#include <sstream>
//! @cond IGNORED
@@ -73,6 +74,95 @@ public:
typedef Vec<channel_type, channels> vec_type;
};
+inline
+String::String(const std::string& str)
+ : cstr_(0), len_(0)
+{
+ size_t len = str.size();
+ if (len) memcpy(allocate(len), str.c_str(), len);
+}
+
+inline
+String::String(const std::string& str, size_t pos, size_t len)
+ : cstr_(0), len_(0)
+{
+ size_t strlen = str.size();
+ pos = min(pos, strlen);
+ len = min(strlen - pos, len);
+ if (!len) return;
+ memcpy(allocate(len), str.c_str() + pos, len);
+}
+
+inline
+String& String::operator = (const std::string& str)
+{
+ deallocate();
+ size_t len = str.size();
+ if (len) memcpy(allocate(len), str.c_str(), len);
+ return *this;
+}
+
+inline
+String& String::operator += (const std::string& str)
+{
+ *this = *this + str;
+ return *this;
+}
+
+inline
+String::operator std::string() const
+{
+ return std::string(cstr_, len_);
+}
+
+inline
+String operator + (const String& lhs, const std::string& rhs)
+{
+ String s;
+ size_t rhslen = rhs.size();
+ s.allocate(lhs.len_ + rhslen);
+ if (lhs.len_) memcpy(s.cstr_, lhs.cstr_, lhs.len_);
+ if (rhslen) memcpy(s.cstr_ + lhs.len_, rhs.c_str(), rhslen);
+ return s;
+}
+
+inline
+String operator + (const std::string& lhs, const String& rhs)
+{
+ String s;
+ size_t lhslen = lhs.size();
+ s.allocate(lhslen + rhs.len_);
+ if (lhslen) memcpy(s.cstr_, lhs.c_str(), lhslen);
+ if (rhs.len_) memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_);
+ return s;
+}
+
+inline
+FileNode::operator std::string() const
+{
+ String value;
+ read(*this, value, value);
+ return value;
+}
+
+template<> inline
+void operator >> (const FileNode& n, std::string& value)
+{
+ read(n, value, std::string());
+}
+
+template<> inline
+FileStorage& operator << (FileStorage& fs, const std::string& value)
+{
+ return fs << cv::String(value);
+}
+
+static inline
+std::ostream& operator << (std::ostream& os, const String& str)
+{
+ return os << str.c_str();
+}
+
static inline
std::ostream& operator << (std::ostream& out, Ptr<Formatted> fmtd)
{
diff --git a/include/opencv2/core/cvstd_wrapper.hpp b/include/opencv2/core/cvstd_wrapper.hpp
deleted file mode 100755
index e2c2ea5..0000000
--- a/include/opencv2/core/cvstd_wrapper.hpp
+++ /dev/null
@@ -1,154 +0,0 @@
-// This file is part of OpenCV project.
-// It is subject to the license terms in the LICENSE file found in the top-level directory
-// of this distribution and at http://opencv.org/license.html.
-
-#ifndef OPENCV_CORE_CVSTD_WRAPPER_HPP
-#define OPENCV_CORE_CVSTD_WRAPPER_HPP
-
-#include "opencv2/core/cvdef.h"
-
-#include <string>
-#include <memory> // std::shared_ptr
-#include <type_traits> // std::enable_if
-
-namespace cv {
-
-using std::nullptr_t;
-
-//! @addtogroup core_basic
-//! @{
-
-#ifdef CV_DOXYGEN
-
-template <typename _Tp> using Ptr = std::shared_ptr<_Tp>; // In ideal world it should look like this, but we need some compatibility workarounds below
-
-template<typename _Tp, typename ... A1> static inline
-Ptr<_Tp> makePtr(const A1&... a1) { return std::make_shared<_Tp>(a1...); }
-
-#else // cv::Ptr with compatibility workarounds
-
-// It should be defined for C-API types only.
-// C++ types should use regular "delete" operator.
-template<typename Y> struct DefaultDeleter;
-#if 0
-{
- void operator()(Y* p) const;
-};
-#endif
-
-namespace sfinae {
-template<typename C, typename Ret, typename... Args>
-struct has_parenthesis_operator
-{
-private:
- template<typename T>
- static CV_CONSTEXPR std::true_type check(typename std::is_same<typename std::decay<decltype(std::declval<T>().operator()(std::declval<Args>()...))>::type, Ret>::type*);
-
- template<typename> static CV_CONSTEXPR std::false_type check(...);
-
- typedef decltype(check<C>(0)) type;
-
-public:
-#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/)
- static CV_CONSTEXPR bool value = type::value;
-#else
- // support MSVS 2013
- static const int value = type::value;
-#endif
-};
-} // namespace sfinae
-
-template <typename T, typename = void>
-struct has_custom_delete
- : public std::false_type {};
-
-// Force has_custom_delete to std::false_type when NVCC is compiling CUDA source files
-#ifndef __CUDACC__
-template <typename T>
-struct has_custom_delete<T, typename std::enable_if< sfinae::has_parenthesis_operator<DefaultDeleter<T>, void, T*>::value >::type >
- : public std::true_type {};
-#endif
-
-template<typename T>
-struct Ptr : public std::shared_ptr<T>
-{
-#if 0
- using std::shared_ptr<T>::shared_ptr; // GCC 5.x can't handle this
-#else
- inline Ptr() CV_NOEXCEPT : std::shared_ptr<T>() {}
- inline Ptr(nullptr_t) CV_NOEXCEPT : std::shared_ptr<T>(nullptr) {}
- template<typename Y, typename D> inline Ptr(Y* p, D d) : std::shared_ptr<T>(p, d) {}
- template<typename D> inline Ptr(nullptr_t, D d) : std::shared_ptr<T>(nullptr, d) {}
-
- template<typename Y> inline Ptr(const Ptr<Y>& r, T* ptr) CV_NOEXCEPT : std::shared_ptr<T>(r, ptr) {}
-
- inline Ptr(const Ptr<T>& o) CV_NOEXCEPT : std::shared_ptr<T>(o) {}
- inline Ptr(Ptr<T>&& o) CV_NOEXCEPT : std::shared_ptr<T>(std::move(o)) {}
-
- template<typename Y> inline Ptr(const Ptr<Y>& o) CV_NOEXCEPT : std::shared_ptr<T>(o) {}
- template<typename Y> inline Ptr(Ptr<Y>&& o) CV_NOEXCEPT : std::shared_ptr<T>(std::move(o)) {}
-#endif
- inline Ptr(const std::shared_ptr<T>& o) CV_NOEXCEPT : std::shared_ptr<T>(o) {}
- inline Ptr(std::shared_ptr<T>&& o) CV_NOEXCEPT : std::shared_ptr<T>(std::move(o)) {}
-
- // Overload with custom DefaultDeleter: Ptr<IplImage>(...)
- template<typename Y>
- inline Ptr(const std::true_type&, Y* ptr) : std::shared_ptr<T>(ptr, DefaultDeleter<Y>()) {}
-
- // Overload without custom deleter: Ptr<std::string>(...);
- template<typename Y>
- inline Ptr(const std::false_type&, Y* ptr) : std::shared_ptr<T>(ptr) {}
-
- template<typename Y = T>
- inline Ptr(Y* ptr) : Ptr(has_custom_delete<Y>(), ptr) {}
-
- // Overload with custom DefaultDeleter: Ptr<IplImage>(...)
- template<typename Y>
- inline void reset(const std::true_type&, Y* ptr) { std::shared_ptr<T>::reset(ptr, DefaultDeleter<Y>()); }
-
- // Overload without custom deleter: Ptr<std::string>(...);
- template<typename Y>
- inline void reset(const std::false_type&, Y* ptr) { std::shared_ptr<T>::reset(ptr); }
-
- template<typename Y>
- inline void reset(Y* ptr) { Ptr<T>::reset(has_custom_delete<Y>(), ptr); }
-
- template<class Y, class Deleter>
- void reset(Y* ptr, Deleter d) { std::shared_ptr<T>::reset(ptr, d); }
-
- void reset() CV_NOEXCEPT { std::shared_ptr<T>::reset(); }
-
- Ptr& operator=(const Ptr& o) { std::shared_ptr<T>::operator =(o); return *this; }
- template<typename Y> inline Ptr& operator=(const Ptr<Y>& o) { std::shared_ptr<T>::operator =(o); return *this; }
-
- T* operator->() const CV_NOEXCEPT { return std::shared_ptr<T>::get();}
- typename std::add_lvalue_reference<T>::type operator*() const CV_NOEXCEPT { return *std::shared_ptr<T>::get(); }
-
- // OpenCV 3.x methods (not a part of standard C++ library)
- inline void release() { std::shared_ptr<T>::reset(); }
- inline operator T* () const { return std::shared_ptr<T>::get(); }
- inline bool empty() const { return std::shared_ptr<T>::get() == nullptr; }
-
- template<typename Y> inline
- Ptr<Y> staticCast() const CV_NOEXCEPT { return std::static_pointer_cast<Y>(*this); }
-
- template<typename Y> inline
- Ptr<Y> constCast() const CV_NOEXCEPT { return std::const_pointer_cast<Y>(*this); }
-
- template<typename Y> inline
- Ptr<Y> dynamicCast() const CV_NOEXCEPT { return std::dynamic_pointer_cast<Y>(*this); }
-};
-
-template<typename _Tp, typename ... A1> static inline
-Ptr<_Tp> makePtr(const A1&... a1)
-{
- static_assert( !has_custom_delete<_Tp>::value, "Can't use this makePtr with custom DefaultDeleter");
- return (Ptr<_Tp>)std::make_shared<_Tp>(a1...);
-}
-
-#endif // CV_DOXYGEN
-
-//! @} core_basic
-} // cv
-
-#endif //OPENCV_CORE_CVSTD_WRAPPER_HPP
diff --git a/include/opencv2/core/eigen.hpp b/include/opencv2/core/eigen.hpp
index 741648e..51f4147 100755
--- a/include/opencv2/core/eigen.hpp
+++ b/include/opencv2/core/eigen.hpp
@@ -45,20 +45,142 @@
#ifndef OPENCV_CORE_EIGEN_HPP
#define OPENCV_CORE_EIGEN_HPP
+#ifndef EIGEN_WORLD_VERSION
+#error "Wrong usage of OpenCV's Eigen utility header. Include Eigen's headers first. See https://github.com/opencv/opencv/issues/17366"
+#endif
+
#include "opencv2/core.hpp"
#if defined _MSC_VER && _MSC_VER >= 1200
+#define NOMINMAX // fix https://github.com/opencv/opencv/issues/17548
#pragma warning( disable: 4714 ) //__forceinline is not inlined
#pragma warning( disable: 4127 ) //conditional expression is constant
#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data
#endif
+#if !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT)
+#if EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 \
+ && defined(CV_CXX11) && defined(CV_CXX_STD_ARRAY)
+#include <unsupported/Eigen/CXX11/Tensor>
+#define OPENCV_EIGEN_TENSOR_SUPPORT 1
+#endif // EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3
+#endif // !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT)
+
namespace cv
{
-//! @addtogroup core_eigen
+/** @addtogroup core_eigen
+These functions are provided for OpenCV-Eigen interoperability. They convert `Mat`
+objects to corresponding `Eigen::Matrix` objects and vice-versa. Consult the [Eigen
+documentation](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) for
+information about the `Matrix` template type.
+
+@note Using these functions requires the `Eigen/Dense` or similar header to be
+included before this header.
+*/
//! @{
+#if defined(OPENCV_EIGEN_TENSOR_SUPPORT) || defined(CV_DOXYGEN)
+/** @brief Converts an Eigen::Tensor to a cv::Mat.
+
+The method converts an Eigen::Tensor with shape (H x W x C) to a cv::Mat where:
+ H = number of rows
+ W = number of columns
+ C = number of channels
+
+Usage:
+\code
+Eigen::Tensor<float, 3, Eigen::RowMajor> a_tensor(...);
+// populate tensor with values
+Mat a_mat;
+eigen2cv(a_tensor, a_mat);
+\endcode
+*/
+template <typename _Tp, int _layout> static inline
+void eigen2cv( const Eigen::Tensor<_Tp, 3, _layout> &src, OutputArray dst )
+{
+ if( !(_layout & Eigen::RowMajorBit) )
+ {
+ const std::array<int, 3> shuffle{2, 1, 0};
+ Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor = src.swap_layout().shuffle(shuffle);
+ Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), row_major_tensor.data());
+ _src.copyTo(dst);
+ }
+ else
+ {
+ Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), (void *)src.data());
+ _src.copyTo(dst);
+ }
+}
+
+/** @brief Converts a cv::Mat to an Eigen::Tensor.
+
+The method converts a cv::Mat to an Eigen Tensor with shape (H x W x C) where:
+ H = number of rows
+ W = number of columns
+ C = number of channels
+
+Usage:
+\code
+Mat a_mat(...);
+// populate Mat with values
+Eigen::Tensor<float, 3, Eigen::RowMajor> a_tensor(...);
+cv2eigen(a_mat, a_tensor);
+\endcode
+*/
+template <typename _Tp, int _layout> static inline
+void cv2eigen( const Mat &src, Eigen::Tensor<_Tp, 3, _layout> &dst )
+{
+ if( !(_layout & Eigen::RowMajorBit) )
+ {
+ Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor(src.rows, src.cols, src.channels());
+ Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), row_major_tensor.data());
+ if (src.type() == _dst.type())
+ src.copyTo(_dst);
+ else
+ src.convertTo(_dst, _dst.type());
+ const std::array<int, 3> shuffle{2, 1, 0};
+ dst = row_major_tensor.swap_layout().shuffle(shuffle);
+ }
+ else
+ {
+ dst.resize(src.rows, src.cols, src.channels());
+ Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), dst.data());
+ if (src.type() == _dst.type())
+ src.copyTo(_dst);
+ else
+ src.convertTo(_dst, _dst.type());
+ }
+}
+
+/** @brief Maps cv::Mat data to an Eigen::TensorMap.
+
+The method wraps an existing Mat data array with an Eigen TensorMap of shape (H x W x C) where:
+ H = number of rows
+ W = number of columns
+ C = number of channels
+
+Explicit instantiation of the return type is required.
+
+@note Caller should be aware of the lifetime of the cv::Mat instance and take appropriate safety measures.
+The cv::Mat instance will retain ownership of the data and the Eigen::TensorMap will lose access when the cv::Mat data is deallocated.
+
+The example below initializes a cv::Mat and produces an Eigen::TensorMap:
+\code
+float arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
+Mat a_mat(2, 2, CV_32FC3, arr);
+Eigen::TensorMap<Eigen::Tensor<float, 3, Eigen::RowMajor>> a_tensormap = cv2eigen_tensormap<float>(a_mat);
+\endcode
+*/
+template <typename _Tp> static inline
+Eigen::TensorMap<Eigen::Tensor<_Tp, 3, Eigen::RowMajor>> cv2eigen_tensormap(InputArray src)
+{
+ Mat mat = src.getMat();
+ CV_CheckTypeEQ(mat.type(), CV_MAKETYPE(traits::Type<_Tp>::value, mat.channels()), "");
+ return Eigen::TensorMap<Eigen::Tensor<_Tp, 3, Eigen::RowMajor>>((_Tp *)mat.data, mat.rows, mat.cols, mat.channels());
+}
+#endif // OPENCV_EIGEN_TENSOR_SUPPORT
+
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> static inline
void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst )
{
diff --git a/include/opencv2/core/hal/hal.hpp b/include/opencv2/core/hal/hal.hpp
index 0d68078..68900ec 100755
--- a/include/opencv2/core/hal/hal.hpp
+++ b/include/opencv2/core/hal/hal.hpp
@@ -195,12 +195,6 @@ CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2,
CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars );
CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars );
-CV_EXPORTS void cvt16f32f( const float16_t* src, float* dst, int len );
-CV_EXPORTS void cvt32f16f( const float* src, float16_t* dst, int len );
-
-CV_EXPORTS void addRNGBias32f( float* arr, const float* scaleBiasPairs, int len );
-CV_EXPORTS void addRNGBias64f( double* arr, const double* scaleBiasPairs, int len );
-
struct CV_EXPORTS DFT1D
{
static Ptr<DFT1D> create(int len, int count, int depth, int flags, bool * useBuffer = 0);
diff --git a/include/opencv2/core/hal/interface.h b/include/opencv2/core/hal/interface.h
index 6f0a83d..8f64025 100755
--- a/include/opencv2/core/hal/interface.h
+++ b/include/opencv2/core/hal/interface.h
@@ -64,8 +64,6 @@ typedef signed char schar;
# define CV_BIG_UINT(n) n##ULL
#endif
-#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0"
-
#define CV_CN_MAX 512
#define CV_CN_SHIFT 3
#define CV_DEPTH_MAX (1 << CV_CN_SHIFT)
@@ -77,7 +75,7 @@ typedef signed char schar;
#define CV_32S 4
#define CV_32F 5
#define CV_64F 6
-#define CV_16F 7
+#define CV_USRTYPE1 7
#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1)
#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK)
@@ -126,12 +124,6 @@ typedef signed char schar;
#define CV_64FC3 CV_MAKETYPE(CV_64F,3)
#define CV_64FC4 CV_MAKETYPE(CV_64F,4)
#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))
-
-#define CV_16FC1 CV_MAKETYPE(CV_16F,1)
-#define CV_16FC2 CV_MAKETYPE(CV_16F,2)
-#define CV_16FC3 CV_MAKETYPE(CV_16F,3)
-#define CV_16FC4 CV_MAKETYPE(CV_16F,4)
-#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n))
//! @}
//! @name Comparison operation
diff --git a/include/opencv2/core/hal/intrin.hpp b/include/opencv2/core/hal/intrin.hpp
index 5a105a7..52f6b5d 100755
--- a/include/opencv2/core/hal/intrin.hpp
+++ b/include/opencv2/core/hal/intrin.hpp
@@ -99,6 +99,7 @@ enum StoreMode
}
+// TODO FIXIT: Don't use "God" traits. Split on separate cases.
template<typename _Tp> struct V_TypeTraits
{
};
@@ -130,21 +131,51 @@ template<typename _Tp> struct V_TypeTraits
} \
}
+#define CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(type, int_type_, uint_type_, abs_type_, w_type_, sum_type_, nlanes128_) \
+ template<> struct V_TypeTraits<type> \
+ { \
+ typedef type value_type; \
+ typedef int_type_ int_type; \
+ typedef abs_type_ abs_type; \
+ typedef uint_type_ uint_type; \
+ typedef w_type_ w_type; \
+ typedef sum_type_ sum_type; \
+ enum { nlanes128 = nlanes128_ }; \
+ \
+ static inline int_type reinterpret_int(type x) \
+ { \
+ union { type l; int_type i; } v; \
+ v.l = x; \
+ return v.i; \
+ } \
+ \
+ static inline type reinterpret_from_int(int_type x) \
+ { \
+ union { type l; int_type i; } v; \
+ v.i = x; \
+ return v.l; \
+ } \
+ }
+
CV_INTRIN_DEF_TYPE_TRAITS(uchar, schar, uchar, uchar, ushort, unsigned, unsigned, 16);
CV_INTRIN_DEF_TYPE_TRAITS(schar, schar, uchar, uchar, short, int, int, 16);
CV_INTRIN_DEF_TYPE_TRAITS(ushort, short, ushort, ushort, unsigned, uint64, unsigned, 8);
CV_INTRIN_DEF_TYPE_TRAITS(short, short, ushort, ushort, int, int64, int, 8);
-CV_INTRIN_DEF_TYPE_TRAITS(unsigned, int, unsigned, unsigned, uint64, void, unsigned, 4);
-CV_INTRIN_DEF_TYPE_TRAITS(int, int, unsigned, unsigned, int64, void, int, 4);
-CV_INTRIN_DEF_TYPE_TRAITS(float, int, unsigned, float, double, void, float, 4);
-CV_INTRIN_DEF_TYPE_TRAITS(uint64, int64, uint64, uint64, void, void, uint64, 2);
-CV_INTRIN_DEF_TYPE_TRAITS(int64, int64, uint64, uint64, void, void, int64, 2);
-CV_INTRIN_DEF_TYPE_TRAITS(double, int64, uint64, double, void, void, double, 2);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(unsigned, int, unsigned, unsigned, uint64, unsigned, 4);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int, int, unsigned, unsigned, int64, int, 4);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(float, int, unsigned, float, double, float, 4);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(uint64, int64, uint64, uint64, void, uint64, 2);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int64, int64, uint64, uint64, void, int64, 2);
+CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(double, int64, uint64, double, void, double, 2);
#ifndef CV_DOXYGEN
#ifndef CV_CPU_OPTIMIZATION_HAL_NAMESPACE
-#ifdef CV_CPU_DISPATCH_MODE
+#ifdef CV_FORCE_SIMD128_CPP
+ #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_EMULATOR_CPP
+ #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_EMULATOR_CPP {
+ #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END }
+#elif defined(CV_CPU_DISPATCH_MODE)
#define CV_CPU_OPTIMIZATION_HAL_NAMESPACE __CV_CAT(hal_, CV_CPU_DISPATCH_MODE)
#define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) {
#define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END }
@@ -197,7 +228,6 @@ using namespace CV_CPU_OPTIMIZATION_HAL_NAMESPACE;
#else
-#define CV_SIMD128_CPP 1
#include "opencv2/core/hal/intrin_cpp.hpp"
#endif
@@ -242,6 +272,10 @@ CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN
#define CV_SIMD128 0
#endif
+#ifndef CV_SIMD128_CPP
+#define CV_SIMD128_CPP 0
+#endif
+
#ifndef CV_SIMD128_64F
#define CV_SIMD128_64F 0
#endif
@@ -346,7 +380,7 @@ template<typename _Tp> struct V_RegTraits
CV_DEF_REG_TRAITS(v, v_int16x8, short, s16, v_uint16x8, v_int32x4, v_int64x2, v_int16x8, void);
CV_DEF_REG_TRAITS(v, v_uint32x4, unsigned, u32, v_uint32x4, v_uint64x2, void, v_int32x4, void);
CV_DEF_REG_TRAITS(v, v_int32x4, int, s32, v_uint32x4, v_int64x2, void, v_int32x4, void);
-#if CV_SIMD128_64F
+#if CV_SIMD128_64F || CV_SIMD128_CPP
CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, v_float64x2, void, v_int32x4, v_int32x4);
#else
CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, void, void, v_int32x4, v_int32x4);
@@ -433,7 +467,11 @@ namespace CV__SIMD_NAMESPACE {
} // namespace
using namespace CV__SIMD_NAMESPACE;
#elif (CV_SIMD128 || CV_SIMD128_CPP) && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 128)
+#if defined CV_SIMD128_CPP
+#define CV__SIMD_NAMESPACE simd128_cpp
+#else
#define CV__SIMD_NAMESPACE simd128
+#endif
namespace CV__SIMD_NAMESPACE {
#define CV_SIMD CV_SIMD128
#define CV_SIMD_64F CV_SIMD128_64F
diff --git a/include/opencv2/core/hal/intrin_avx.hpp b/include/opencv2/core/hal/intrin_avx.hpp
index 6fc03b7..54e8927 100755
--- a/include/opencv2/core/hal/intrin_avx.hpp
+++ b/include/opencv2/core/hal/intrin_avx.hpp
@@ -159,7 +159,9 @@ struct v_uint8x32
(char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27,
(char)v28, (char)v29, (char)v30, (char)v31);
}
- v_uint8x32() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint8x32() {}
+
uchar get0() const { return (uchar)_v_cvtsi256_si32(val); }
};
@@ -183,7 +185,9 @@ struct v_int8x32
v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20,
v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31);
}
- v_int8x32() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int8x32() {}
+
schar get0() const { return (schar)_v_cvtsi256_si32(val); }
};
@@ -203,7 +207,9 @@ struct v_uint16x16
(short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9,
(short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15);
}
- v_uint16x16() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint16x16() {}
+
ushort get0() const { return (ushort)_v_cvtsi256_si32(val); }
};
@@ -222,7 +228,9 @@ struct v_int16x16
val = _mm256_setr_epi16(v0, v1, v2, v3, v4, v5, v6, v7,
v8, v9, v10, v11, v12, v13, v14, v15);
}
- v_int16x16() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int16x16() {}
+
short get0() const { return (short)_v_cvtsi256_si32(val); }
};
@@ -239,7 +247,9 @@ struct v_uint32x8
val = _mm256_setr_epi32((unsigned)v0, (unsigned)v1, (unsigned)v2,
(unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7);
}
- v_uint32x8() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint32x8() {}
+
unsigned get0() const { return (unsigned)_v_cvtsi256_si32(val); }
};
@@ -255,7 +265,9 @@ struct v_int32x8
{
val = _mm256_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7);
}
- v_int32x8() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int32x8() {}
+
int get0() const { return _v_cvtsi256_si32(val); }
};
@@ -271,7 +283,9 @@ struct v_float32x8
{
val = _mm256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7);
}
- v_float32x8() : val(_mm256_setzero_ps()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_float32x8() {}
+
float get0() const { return _mm_cvtss_f32(_mm256_castps256_ps128(val)); }
};
@@ -284,7 +298,9 @@ struct v_uint64x4
explicit v_uint64x4(__m256i v) : val(v) {}
v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3)
{ val = _mm256_setr_epi64x((int64)v0, (int64)v1, (int64)v2, (int64)v3); }
- v_uint64x4() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint64x4() {}
+
uint64 get0() const
{
#if defined __x86_64__ || defined _M_X64
@@ -306,7 +322,8 @@ struct v_int64x4
explicit v_int64x4(__m256i v) : val(v) {}
v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3)
{ val = _mm256_setr_epi64x(v0, v1, v2, v3); }
- v_int64x4() : val(_mm256_setzero_si256()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int64x4() {}
int64 get0() const
{
@@ -329,7 +346,9 @@ struct v_float64x4
explicit v_float64x4(__m256d v) : val(v) {}
v_float64x4(double v0, double v1, double v2, double v3)
{ val = _mm256_setr_pd(v0, v1, v2, v3); }
- v_float64x4() : val(_mm256_setzero_pd()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_float64x4() {}
+
double get0() const { return _mm_cvtsd_f64(_mm256_castpd256_pd128(val)); }
};
@@ -569,7 +588,7 @@ inline v_int64x4 v256_blend(const v_int64x4& a, const v_int64x4& b)
{ return v_int64x4(v256_blend<m>(v_uint64x4(a.val), v_uint64x4(b.val)).val); }
// shuffle
-// todo: emluate 64bit
+// todo: emulate 64bit
#define OPENCV_HAL_IMPL_AVX_SHUFFLE(_Tpvec, intrin) \
template<int m> \
inline _Tpvec v256_shuffle(const _Tpvec& a) \
@@ -3102,18 +3121,39 @@ OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, un
OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64)
OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64)
+//
// FP16
+//
+
inline v_float32x8 v256_load_expand(const float16_t* ptr)
{
+#if CV_FP16
return v_float32x8(_mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr)));
+#else
+ float CV_DECL_ALIGNED(32) buf[8];
+ for (int i = 0; i < 8; i++)
+ buf[i] = (float)ptr[i];
+ return v256_load_aligned(buf);
+#endif
}
inline void v_pack_store(float16_t* ptr, const v_float32x8& a)
{
+#if CV_FP16
__m128i ah = _mm256_cvtps_ph(a.val, 0);
_mm_storeu_si128((__m128i*)ptr, ah);
+#else
+ float CV_DECL_ALIGNED(32) buf[8];
+ v_store_aligned(buf, a);
+ for (int i = 0; i < 8; i++)
+ ptr[i] = float16_t(buf[i]);
+#endif
}
+//
+// end of FP16
+//
+
inline void v256_cleanup() { _mm256_zeroall(); }
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END
diff --git a/include/opencv2/core/hal/intrin_avx512.hpp b/include/opencv2/core/hal/intrin_avx512.hpp
index 3fa9027..75a3bd4 100755
--- a/include/opencv2/core/hal/intrin_avx512.hpp
+++ b/include/opencv2/core/hal/intrin_avx512.hpp
@@ -144,7 +144,10 @@ struct v_uint8x64
v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16,
v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0);
}
- v_uint8x64() : val(_mm512_setzero_si512()) {}
+ v_uint8x64() {}
+
+ static inline v_uint8x64 zero() { return v_uint8x64(_mm512_setzero_si512()); }
+
uchar get0() const { return (uchar)_v_cvtsi512_si32(val); }
};
@@ -177,7 +180,10 @@ struct v_int8x64
v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16,
v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0);
}
- v_int8x64() : val(_mm512_setzero_si512()) {}
+ v_int8x64() {}
+
+ static inline v_int8x64 zero() { return v_int8x64(_mm512_setzero_si512()); }
+
schar get0() const { return (schar)_v_cvtsi512_si32(val); }
};
@@ -200,7 +206,10 @@ struct v_uint16x32
val = _v512_set_epu16(v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16,
v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0);
}
- v_uint16x32() : val(_mm512_setzero_si512()) {}
+ v_uint16x32() {}
+
+ static inline v_uint16x32 zero() { return v_uint16x32(_mm512_setzero_si512()); }
+
ushort get0() const { return (ushort)_v_cvtsi512_si32(val); }
};
@@ -221,7 +230,10 @@ struct v_int16x32
(ushort)v15, (ushort)v14, (ushort)v13, (ushort)v12, (ushort)v11, (ushort)v10, (ushort)v9 , (ushort)v8,
(ushort)v7 , (ushort)v6 , (ushort)v5 , (ushort)v4 , (ushort)v3 , (ushort)v2 , (ushort)v1 , (ushort)v0);
}
- v_int16x32() : val(_mm512_setzero_si512()) {}
+ v_int16x32() {}
+
+ static inline v_int16x32 zero() { return v_int16x32(_mm512_setzero_si512()); }
+
short get0() const { return (short)_v_cvtsi512_si32(val); }
};
@@ -240,7 +252,10 @@ struct v_uint32x16
val = _mm512_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3, (int)v4, (int)v5, (int)v6, (int)v7,
(int)v8, (int)v9, (int)v10, (int)v11, (int)v12, (int)v13, (int)v14, (int)v15);
}
- v_uint32x16() : val(_mm512_setzero_si512()) {}
+ v_uint32x16() {}
+
+ static inline v_uint32x16 zero() { return v_uint32x16(_mm512_setzero_si512()); }
+
unsigned get0() const { return (unsigned)_v_cvtsi512_si32(val); }
};
@@ -256,7 +271,10 @@ struct v_int32x16
{
val = _mm512_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
}
- v_int32x16() : val(_mm512_setzero_si512()) {}
+ v_int32x16() {}
+
+ static inline v_int32x16 zero() { return v_int32x16(_mm512_setzero_si512()); }
+
int get0() const { return _v_cvtsi512_si32(val); }
};
@@ -272,7 +290,10 @@ struct v_float32x16
{
val = _mm512_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
}
- v_float32x16() : val(_mm512_setzero_ps()) {}
+ v_float32x16() {}
+
+ static inline v_float32x16 zero() { return v_float32x16(_mm512_setzero_ps()); }
+
float get0() const { return _mm_cvtss_f32(_mm512_castps512_ps128(val)); }
};
@@ -285,7 +306,10 @@ struct v_uint64x8
explicit v_uint64x8(__m512i v) : val(v) {}
v_uint64x8(uint64 v0, uint64 v1, uint64 v2, uint64 v3, uint64 v4, uint64 v5, uint64 v6, uint64 v7)
{ val = _mm512_setr_epi64((int64)v0, (int64)v1, (int64)v2, (int64)v3, (int64)v4, (int64)v5, (int64)v6, (int64)v7); }
- v_uint64x8() : val(_mm512_setzero_si512()) {}
+ v_uint64x8() {}
+
+ static inline v_uint64x8 zero() { return v_uint64x8(_mm512_setzero_si512()); }
+
uint64 get0() const
{
#if defined __x86_64__ || defined _M_X64
@@ -307,7 +331,9 @@ struct v_int64x8
explicit v_int64x8(__m512i v) : val(v) {}
v_int64x8(int64 v0, int64 v1, int64 v2, int64 v3, int64 v4, int64 v5, int64 v6, int64 v7)
{ val = _mm512_setr_epi64(v0, v1, v2, v3, v4, v5, v6, v7); }
- v_int64x8() : val(_mm512_setzero_si512()) {}
+ v_int64x8() {}
+
+ static inline v_int64x8 zero() { return v_int64x8(_mm512_setzero_si512()); }
int64 get0() const
{
@@ -330,7 +356,10 @@ struct v_float64x8
explicit v_float64x8(__m512d v) : val(v) {}
v_float64x8(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7)
{ val = _mm512_setr_pd(v0, v1, v2, v3, v4, v5, v6, v7); }
- v_float64x8() : val(_mm512_setzero_pd()) {}
+ v_float64x8() {}
+
+ static inline v_float64x8 zero() { return v_float64x8(_mm512_setzero_pd()); }
+
double get0() const { return _mm_cvtsd_f64(_mm512_castpd512_pd128(val)); }
};
@@ -1030,7 +1059,7 @@ inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b)
enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \
if (imm == 0) return a; \
if (imm == _Tpvec::nlanes) return b; \
- if (imm >= 2*_Tpvec::nlanes) return _Tpvec(); \
+ if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \
return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << SHIFT2)&MASK, b.val), (MASK << (imm))&MASK, a.val)); \
} \
template<int imm> \
@@ -1040,21 +1069,21 @@ inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b)
enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \
if (imm == 0) return a; \
if (imm == _Tpvec::nlanes) return b; \
- if (imm >= 2*_Tpvec::nlanes) return _Tpvec(); \
+ if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \
return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << (imm))&MASK, a.val), (MASK << SHIFT2)&MASK, b.val)); \
} \
template<int imm> \
inline _Tpvec v_rotate_left(const _Tpvec& a) \
{ \
if (imm == 0) return a; \
- if (imm >= _Tpvec::nlanes) return _Tpvec(); \
+ if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \
return _Tpvec(_mm512_maskz_expand_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \
} \
template<int imm> \
inline _Tpvec v_rotate_right(const _Tpvec& a) \
{ \
if (imm == 0) return a; \
- if (imm >= _Tpvec::nlanes) return _Tpvec(); \
+ if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \
return _Tpvec(_mm512_maskz_compress_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \
}
@@ -1553,13 +1582,13 @@ inline v_float64x8 v_cvt_f64(const v_int64x8& v)
return v_float64x8(_mm512_cvtepi64_pd(v.val));
#else
// constants encoded as floating-point
- __m512i magic_i_lo = _mm512_set1_epi64x(0x4330000000000000); // 2^52
- __m512i magic_i_hi32 = _mm512_set1_epi64x(0x4530000080000000); // 2^84 + 2^63
- __m512i magic_i_all = _mm512_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52
+ __m512i magic_i_lo = _mm512_set1_epi64(0x4330000000000000); // 2^52
+ __m512i magic_i_hi32 = _mm512_set1_epi64(0x4530000080000000); // 2^84 + 2^63
+ __m512i magic_i_all = _mm512_set1_epi64(0x4530000080100000); // 2^84 + 2^63 + 2^52
__m512d magic_d_all = _mm512_castsi512_pd(magic_i_all);
// Blend the 32 lowest significant bits of v with magic_int_lo
- __m512i v_lo = _mm512_blend_epi32(magic_i_lo, v.val, 0x55);
+ __m512i v_lo = _mm512_mask_blend_epi32(0x5555, magic_i_lo, v.val);
// Extract the 32 most significant bits of v
__m512i v_hi = _mm512_srli_epi64(v.val, 32);
// Flip the msb of v_hi and blend with 0x45300000
diff --git a/include/opencv2/core/hal/intrin_cpp.hpp b/include/opencv2/core/hal/intrin_cpp.hpp
index 67d3155..859bfd7 100755
--- a/include/opencv2/core/hal/intrin_cpp.hpp
+++ b/include/opencv2/core/hal/intrin_cpp.hpp
@@ -50,6 +50,14 @@
#include <algorithm>
#include "opencv2/core/saturate.hpp"
+//! @cond IGNORED
+#define CV_SIMD128_CPP 1
+#if defined(CV_FORCE_SIMD128_CPP) || defined(CV_DOXYGEN)
+#define CV_SIMD128 1
+#define CV_SIMD128_64F 1
+#endif
+//! @endcond
+
namespace cv
{
@@ -73,7 +81,7 @@ implemented as a structure based on a one SIMD register.
- cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char
- cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short
-- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsgined/signed) - int
+- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsigned/signed) - int
- cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64
- cv::v_float32x4: four 32-bit floating point values (signed) - float
- cv::v_float64x2: two 64-bit floating point values (signed) - double
@@ -135,7 +143,7 @@ Element-wise binary and unary operations.
@ref v_shl, @ref v_shr
- Bitwise logic:
-@ref operator&(const v_reg &a, const v_reg &b) "&",
+@ref operator &(const v_reg &a, const v_reg &b) "&",
@ref operator |(const v_reg &a, const v_reg &b) "|",
@ref operator ^(const v_reg &a, const v_reg &b) "^",
@ref operator ~(const v_reg &a) "~"
@@ -205,7 +213,7 @@ Regular integers:
|min, max | x | x | x | x | x | x |
|absdiff | x | x | x | x | x | x |
|absdiffs | | x | | x | | |
-|reduce | | | | | x | x |
+|reduce | x | x | x | x | x | x |
|mask | x | x | x | x | x | x |
|pack | x | x | x | x | x | x |
|pack_u | x | | x | | | |
@@ -402,50 +410,102 @@ typedef v_reg<uint64, 2> v_uint64x2;
/** @brief Two 64-bit signed integer values */
typedef v_reg<int64, 2> v_int64x2;
-//! @brief Helper macro
-//! @ingroup core_hal_intrin_impl
-#define OPENCV_HAL_IMPL_BIN_OP(bin_op) \
-template<typename _Tp, int n> inline v_reg<_Tp, n> \
- operator bin_op (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
-{ \
- v_reg<_Tp, n> c; \
- for( int i = 0; i < n; i++ ) \
- c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \
- return c; \
-} \
-template<typename _Tp, int n> inline v_reg<_Tp, n>& \
- operator bin_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
-{ \
- for( int i = 0; i < n; i++ ) \
- a.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \
- return a; \
-}
-
/** @brief Add values
For all types. */
-OPENCV_HAL_IMPL_BIN_OP(+)
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator+(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator+=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
/** @brief Subtract values
For all types. */
-OPENCV_HAL_IMPL_BIN_OP(-)
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator-(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator-=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
/** @brief Multiply values
For 16- and 32-bit integer types and floating types. */
-OPENCV_HAL_IMPL_BIN_OP(*)
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator*(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator*=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
/** @brief Divide values
For floating types only. */
-OPENCV_HAL_IMPL_BIN_OP(/)
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator/(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator/=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
-//! @brief Helper macro
-//! @ingroup core_hal_intrin_impl
-#define OPENCV_HAL_IMPL_BIT_OP(bit_op) \
-template<typename _Tp, int n> inline v_reg<_Tp, n> operator bit_op \
- (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
+
+/** @brief Bitwise AND
+
+Only for integer types. */
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator&(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator&=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+
+/** @brief Bitwise OR
+
+Only for integer types. */
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator|(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator|=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+
+/** @brief Bitwise XOR
+
+Only for integer types.*/
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator^(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n>& operator^=(v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b);
+
+/** @brief Bitwise NOT
+
+Only for integer types.*/
+template<typename _Tp, int n> CV_INLINE v_reg<_Tp, n> operator~(const v_reg<_Tp, n>& a);
+
+
+#ifndef CV_DOXYGEN
+
+#define CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, ...) \
+__CV_EXPAND(macro_name(uchar, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(schar, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(ushort, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(short, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(unsigned, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(int, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(uint64, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(int64, __VA_ARGS__)) \
+
+#define CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, ...) \
+__CV_EXPAND(macro_name(float, __VA_ARGS__)) \
+__CV_EXPAND(macro_name(double, __VA_ARGS__)) \
+
+#define CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(macro_name, ...) \
+CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, __VA_ARGS__) \
+CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, __VA_ARGS__) \
+
+#define CV__HAL_INTRIN_IMPL_BIN_OP_(_Tp, bin_op) \
+template<int n> inline \
+v_reg<_Tp, n> operator bin_op (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
+{ \
+ v_reg<_Tp, n> c; \
+ for( int i = 0; i < n; i++ ) \
+ c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \
+ return c; \
+} \
+template<int n> inline \
+v_reg<_Tp, n>& operator bin_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
+{ \
+ for( int i = 0; i < n; i++ ) \
+ a.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \
+ return a; \
+}
+
+#define CV__HAL_INTRIN_IMPL_BIN_OP(bin_op) CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, bin_op)
+
+CV__HAL_INTRIN_IMPL_BIN_OP(+)
+CV__HAL_INTRIN_IMPL_BIN_OP(-)
+CV__HAL_INTRIN_IMPL_BIN_OP(*)
+CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, /)
+
+#define CV__HAL_INTRIN_IMPL_BIT_OP_(_Tp, bit_op) \
+template<int n> CV_INLINE \
+v_reg<_Tp, n> operator bit_op (const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
{ \
v_reg<_Tp, n> c; \
typedef typename V_TypeTraits<_Tp>::int_type itype; \
@@ -454,8 +514,8 @@ template<typename _Tp, int n> inline v_reg<_Tp, n> operator bit_op \
V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \
return c; \
} \
-template<typename _Tp, int n> inline v_reg<_Tp, n>& operator \
- bit_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
+template<int n> CV_INLINE \
+v_reg<_Tp, n>& operator bit_op##= (v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \
{ \
typedef typename V_TypeTraits<_Tp>::int_type itype; \
for( int i = 0; i < n; i++ ) \
@@ -464,33 +524,29 @@ template<typename _Tp, int n> inline v_reg<_Tp, n>& operator \
return a; \
}
-/** @brief Bitwise AND
+#define CV__HAL_INTRIN_IMPL_BIT_OP(bit_op) \
+CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op) \
+CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op) /* TODO: FIXIT remove this after masks refactoring */
-Only for integer types. */
-OPENCV_HAL_IMPL_BIT_OP(&)
-/** @brief Bitwise OR
+CV__HAL_INTRIN_IMPL_BIT_OP(&)
+CV__HAL_INTRIN_IMPL_BIT_OP(|)
+CV__HAL_INTRIN_IMPL_BIT_OP(^)
-Only for integer types. */
-OPENCV_HAL_IMPL_BIT_OP(|)
+#define CV__HAL_INTRIN_IMPL_BITWISE_NOT_(_Tp, dummy) \
+template<int n> CV_INLINE \
+v_reg<_Tp, n> operator ~ (const v_reg<_Tp, n>& a) \
+{ \
+ v_reg<_Tp, n> c; \
+ for( int i = 0; i < n; i++ ) \
+ c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); \
+ return c; \
+} \
-/** @brief Bitwise XOR
+CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BITWISE_NOT_, ~)
-Only for integer types.*/
-OPENCV_HAL_IMPL_BIT_OP(^)
+#endif // !CV_DOXYGEN
-/** @brief Bitwise NOT
-
-Only for integer types.*/
-template<typename _Tp, int n> inline v_reg<_Tp, n> operator ~ (const v_reg<_Tp, n>& a)
-{
- v_reg<_Tp, n> c;
- for( int i = 0; i < n; i++ )
- {
- c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i]));
- }
- return c;
-}
//! @brief Helper macro
//! @ingroup core_hal_intrin_impl
@@ -503,6 +559,27 @@ template<typename _Tp, int n> inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a)
return c; \
}
+//! @brief Helper macro
+//! @ingroup core_hal_intrin_impl
+#define OPENCV_HAL_IMPL_MATH_FUNC_FLOAT(func, cfunc) \
+inline v_reg<int, 4> func(const v_reg<float, 4>& a) \
+{ \
+ v_reg<int, 4> c; \
+ for( int i = 0; i < 4; i++ ) \
+ c.s[i] = cfunc(a.s[i]); \
+ return c; \
+} \
+inline v_reg<int, 4> func(const v_reg<double, 2>& a) \
+{ \
+ v_reg<int, 4> c; \
+ for( int i = 0; i < 2; i++ ) \
+ { \
+ c.s[i] = cfunc(a.s[i]); \
+ c.s[i + 2] = 0; \
+ } \
+ return c; \
+}
+
/** @brief Square root of elements
Only for floating point types.*/
@@ -524,22 +601,22 @@ OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs,
/** @brief Round elements
Only for floating point types.*/
-OPENCV_HAL_IMPL_MATH_FUNC(v_round, cvRound, int)
+OPENCV_HAL_IMPL_MATH_FUNC_FLOAT(v_round, cvRound)
/** @brief Floor elements
Only for floating point types.*/
-OPENCV_HAL_IMPL_MATH_FUNC(v_floor, cvFloor, int)
+OPENCV_HAL_IMPL_MATH_FUNC_FLOAT(v_floor, cvFloor)
/** @brief Ceil elements
Only for floating point types.*/
-OPENCV_HAL_IMPL_MATH_FUNC(v_ceil, cvCeil, int)
+OPENCV_HAL_IMPL_MATH_FUNC_FLOAT(v_ceil, cvCeil)
/** @brief Truncate elements
Only for floating point types.*/
-OPENCV_HAL_IMPL_MATH_FUNC(v_trunc, int, int)
+OPENCV_HAL_IMPL_MATH_FUNC_FLOAT(v_trunc, int)
//! @brief Helper macro
//! @ingroup core_hal_intrin_impl
@@ -593,7 +670,7 @@ Scheme:
@code
{A1 A2 A3 ...} => min(A1,A2,A3,...)
@endcode
-For 32-bit integer and 32-bit floating point types. */
+For all types except 64-bit integer and 64-bit floating point types. */
OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min)
/** @brief Find one max value
@@ -602,7 +679,7 @@ Scheme:
@code
{A1 A2 A3 ...} => max(A1,A2,A3,...)
@endcode
-For 32-bit integer and 32-bit floating point types. */
+For all types except 64-bit integer and 64-bit floating point types. */
OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max)
static const unsigned char popCountTable[] =
@@ -1083,9 +1160,8 @@ OPENCV_HAL_IMPL_SHIFT_OP(<< )
For 16-, 32- and 64-bit integer values. */
OPENCV_HAL_IMPL_SHIFT_OP(>> )
-/** @brief Element shift left among vector
-
-For all type */
+//! @brief Helper macro
+//! @ingroup core_hal_intrin_impl
#define OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(suffix,opA,opB) \
template<int imm, typename _Tp, int n> inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a) \
{ \
@@ -1127,7 +1203,14 @@ template<int imm, typename _Tp, int n> inline v_reg<_Tp, n> v_rotate_##suffix(co
return c; \
}
+/** @brief Element shift left among vector
+
+For all type */
OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(left, -, +)
+
+/** @brief Element shift right among vector
+
+For all type */
OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(right, +, -)
/** @brief Sum packed values
@@ -1136,7 +1219,7 @@ Scheme:
@code
{A1 A2 A3 ...} => sum{A1,A2,A3,...}
@endcode
-For 32-bit integer and 32-bit floating point types.*/
+*/
template<typename _Tp, int n> inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a)
{
typename V_TypeTraits<_Tp>::sum_type c = a.s[0];
@@ -1375,20 +1458,28 @@ template<typename _Tp, int n> inline void v_zip( const v_reg<_Tp, n>& a0, const
@return register object
@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc.
+
+@note Alignment requirement:
+if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough).
+Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`).
*/
template<typename _Tp>
inline v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> v_load(const _Tp* ptr)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
return v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128>(ptr);
}
/** @brief Load register contents from memory (aligned)
-similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary)
+similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary in case of SIMD128, 32-byte - SIMD256, etc)
*/
template<typename _Tp>
inline v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> v_load_aligned(const _Tp* ptr)
{
+ CV_Assert(isAligned<sizeof(v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128>)>(ptr));
return v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128>(ptr);
}
@@ -1404,6 +1495,9 @@ v_int32x4 r = v_load_low(lo);
template<typename _Tp>
inline v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> v_load_low(const _Tp* ptr)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> c;
for( int i = 0; i < c.nlanes/2; i++ )
{
@@ -1425,6 +1519,10 @@ v_int32x4 r = v_load_halves(lo, hi);
template<typename _Tp>
inline v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> v_load_halves(const _Tp* loptr, const _Tp* hiptr)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(loptr));
+ CV_Assert(isAligned<sizeof(_Tp)>(hiptr));
+#endif
v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> c;
for( int i = 0; i < c.nlanes/2; i++ )
{
@@ -1447,6 +1545,9 @@ template<typename _Tp>
inline v_reg<typename V_TypeTraits<_Tp>::w_type, V_TypeTraits<_Tp>::nlanes128 / 2>
v_load_expand(const _Tp* ptr)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
typedef typename V_TypeTraits<_Tp>::w_type w_type;
v_reg<w_type, V_TypeTraits<w_type>::nlanes128> c;
for( int i = 0; i < c.nlanes; i++ )
@@ -1468,6 +1569,9 @@ template<typename _Tp>
inline v_reg<typename V_TypeTraits<_Tp>::q_type, V_TypeTraits<_Tp>::nlanes128 / 4>
v_load_expand_q(const _Tp* ptr)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
typedef typename V_TypeTraits<_Tp>::q_type q_type;
v_reg<q_type, V_TypeTraits<q_type>::nlanes128> c;
for( int i = 0; i < c.nlanes; i++ )
@@ -1488,6 +1592,9 @@ For all types except 64-bit. */
template<typename _Tp, int n> inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a,
v_reg<_Tp, n>& b)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i2;
for( i = i2 = 0; i < n; i++, i2 += 2 )
{
@@ -1507,6 +1614,9 @@ For all types except 64-bit. */
template<typename _Tp, int n> inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a,
v_reg<_Tp, n>& b, v_reg<_Tp, n>& c)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i3;
for( i = i3 = 0; i < n; i++, i3 += 3 )
{
@@ -1529,6 +1639,9 @@ inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a,
v_reg<_Tp, n>& b, v_reg<_Tp, n>& c,
v_reg<_Tp, n>& d)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i4;
for( i = i4 = 0; i < n; i++, i4 += 4 )
{
@@ -1552,6 +1665,9 @@ inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a,
const v_reg<_Tp, n>& b,
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i2;
for( i = i2 = 0; i < n; i++, i2 += 2 )
{
@@ -1573,6 +1689,9 @@ inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a,
const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c,
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i3;
for( i = i3 = 0; i < n; i++, i3 += 3 )
{
@@ -1595,6 +1714,9 @@ template<typename _Tp, int n> inline void v_store_interleave( _Tp* ptr, const v_
const v_reg<_Tp, n>& d,
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
int i, i4;
for( i = i4 = 0; i < n; i++, i4 += 4 )
{
@@ -1616,10 +1738,22 @@ Pointer can be unaligned. */
template<typename _Tp, int n>
inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
for( int i = 0; i < n; i++ )
ptr[i] = a.s[i];
}
+template<typename _Tp, int n>
+inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/)
+{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
+ v_store(ptr, a);
+}
+
/** @brief Store data to memory (lower half)
Store lower half of register contents to memory.
@@ -1630,6 +1764,9 @@ Scheme:
template<typename _Tp, int n>
inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
for( int i = 0; i < (n/2); i++ )
ptr[i] = a.s[i];
}
@@ -1644,6 +1781,9 @@ Scheme:
template<typename _Tp, int n>
inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a)
{
+#if CV_STRONG_ALIGNMENT
+ CV_Assert(isAligned<sizeof(_Tp)>(ptr));
+#endif
for( int i = 0; i < (n/2); i++ )
ptr[i] = a.s[i+(n/2)];
}
@@ -1659,22 +1799,22 @@ Pointer __should__ be aligned by 16-byte boundary. */
template<typename _Tp, int n>
inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a)
{
- for( int i = 0; i < n; i++ )
- ptr[i] = a.s[i];
+ CV_Assert(isAligned<sizeof(v_reg<_Tp, n>)>(ptr));
+ v_store(ptr, a);
}
template<typename _Tp, int n>
inline void v_store_aligned_nocache(_Tp* ptr, const v_reg<_Tp, n>& a)
{
- for( int i = 0; i < n; i++ )
- ptr[i] = a.s[i];
+ CV_Assert(isAligned<sizeof(v_reg<_Tp, n>)>(ptr));
+ v_store(ptr, a);
}
template<typename _Tp, int n>
inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/)
{
- for( int i = 0; i < n; i++ )
- ptr[i] = a.s[i];
+ CV_Assert(isAligned<sizeof(v_reg<_Tp, n>)>(ptr));
+ v_store(ptr, a);
}
/** @brief Combine vector from first elements of two vectors
@@ -1940,6 +2080,17 @@ template<int n> inline v_reg<float, n> v_cvt_f32(const v_reg<int, n>& a)
return c;
}
+template<int n> inline v_reg<float, n*2> v_cvt_f32(const v_reg<double, n>& a)
+{
+ v_reg<float, n*2> c;
+ for( int i = 0; i < n; i++ )
+ {
+ c.s[i] = (float)a.s[i];
+ c.s[i+n] = 0;
+ }
+ return c;
+}
+
template<int n> inline v_reg<float, n*2> v_cvt_f32(const v_reg<double, n>& a, const v_reg<double, n>& b)
{
v_reg<float, n*2> c;
@@ -1954,36 +2105,76 @@ template<int n> inline v_reg<float, n*2> v_cvt_f32(const v_reg<double, n>& a, co
/** @brief Convert to double
Supported input type is cv::v_int32x4. */
-template<int n> inline v_reg<double, n> v_cvt_f64(const v_reg<int, n*2>& a)
+CV_INLINE v_reg<double, 2> v_cvt_f64(const v_reg<int, 4>& a)
{
+ enum { n = 2 };
v_reg<double, n> c;
for( int i = 0; i < n; i++ )
c.s[i] = (double)a.s[i];
return c;
}
+/** @brief Convert to double high part of vector
+
+Supported input type is cv::v_int32x4. */
+CV_INLINE v_reg<double, 2> v_cvt_f64_high(const v_reg<int, 4>& a)
+{
+ enum { n = 2 };
+ v_reg<double, n> c;
+ for( int i = 0; i < n; i++ )
+ c.s[i] = (double)a.s[i + 2];
+ return c;
+}
+
/** @brief Convert to double
Supported input type is cv::v_float32x4. */
-template<int n> inline v_reg<double, n> v_cvt_f64(const v_reg<float, n*2>& a)
+CV_INLINE v_reg<double, 2> v_cvt_f64(const v_reg<float, 4>& a)
{
+ enum { n = 2 };
v_reg<double, n> c;
for( int i = 0; i < n; i++ )
c.s[i] = (double)a.s[i];
return c;
}
+/** @brief Convert to double high part of vector
+
+Supported input type is cv::v_float32x4. */
+CV_INLINE v_reg<double, 2> v_cvt_f64_high(const v_reg<float, 4>& a)
+{
+ enum { n = 2 };
+ v_reg<double, n> c;
+ for( int i = 0; i < n; i++ )
+ c.s[i] = (double)a.s[i + 2];
+ return c;
+}
+
/** @brief Convert to double
Supported input type is cv::v_int64x2. */
-template<int n> inline v_reg<double, n> v_cvt_f64(const v_reg<int64, n>& a)
+CV_INLINE v_reg<double, 2> v_cvt_f64(const v_reg<int64, 2>& a)
{
+ enum { n = 2 };
v_reg<double, n> c;
for( int i = 0; i < n; i++ )
c.s[i] = (double)a.s[i];
return c;
}
+/** @brief Convert to double high part of vector
+
+Supported input type is cv::v_int64x2. */
+CV_INLINE v_reg<double, 2> v_cvt_f64_high(const v_reg<int64, 2>& a)
+{
+ enum { n = 2 };
+ v_reg<double, n> c;
+ for( int i = 0; i < n; i++ )
+ c.s[i] = (double)a.s[i];
+ return c;
+}
+
+
template<typename _Tp> inline v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> v_lut(const _Tp* tab, const int* idx)
{
v_reg<_Tp, V_TypeTraits<_Tp>::nlanes128> c;
@@ -2038,6 +2229,28 @@ template<int n> inline v_reg<double, n> v_lut(const double* tab, const v_reg<int
return c;
}
+
+inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec)
+{
+ return v_lut(tab, idxvec.s);
+}
+
+inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec)
+{
+ return v_lut(tab, idxvec.s);
+}
+
+inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec)
+{
+ return v_lut(tab, idxvec.s);
+}
+
+inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec)
+{
+ return v_lut(tab, idxvec.s);
+}
+
+
template<int n> inline void v_lut_deinterleave(const float* tab, const v_reg<int, n>& idx,
v_reg<float, n>& x, v_reg<float, n>& y)
{
@@ -2062,7 +2275,7 @@ template<int n> inline void v_lut_deinterleave(const double* tab, const v_reg<in
template<typename _Tp, int n> inline v_reg<_Tp, n> v_interleave_pairs(const v_reg<_Tp, n>& vec)
{
- v_reg<float, n> c;
+ v_reg<_Tp, n> c;
for (int i = 0; i < n/4; i++)
{
c.s[4*i ] = vec.s[4*i ];
@@ -2075,7 +2288,7 @@ template<typename _Tp, int n> inline v_reg<_Tp, n> v_interleave_pairs(const v_re
template<typename _Tp, int n> inline v_reg<_Tp, n> v_interleave_quads(const v_reg<_Tp, n>& vec)
{
- v_reg<float, n> c;
+ v_reg<_Tp, n> c;
for (int i = 0; i < n/8; i++)
{
c.s[8*i ] = vec.s[8*i ];
@@ -2092,7 +2305,7 @@ template<typename _Tp, int n> inline v_reg<_Tp, n> v_interleave_quads(const v_re
template<typename _Tp, int n> inline v_reg<_Tp, n> v_pack_triplets(const v_reg<_Tp, n>& vec)
{
- v_reg<float, n> c;
+ v_reg<_Tp, n> c;
for (int i = 0; i < n/4; i++)
{
c.s[3*i ] = vec.s[4*i ];
@@ -2523,6 +2736,17 @@ inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0,
v.s[0]*m0.s[3] + v.s[1]*m1.s[3] + v.s[2]*m2.s[3] + m3.s[3]);
}
+
+inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b)
+{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_cvt_f64_high(a) * v_cvt_f64_high(b)); }
+inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c)
+{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); }
+
+inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b)
+{ return v_dotprod_expand(a, b); }
+inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c)
+{ return v_dotprod_expand(a, b, c); }
+
////// FP16 support ///////
inline v_reg<float, V_TypeTraits<float>::nlanes128>
@@ -2537,7 +2761,7 @@ v_load_expand(const float16_t* ptr)
}
inline void
-v_pack_store(float16_t* ptr, v_reg<float, V_TypeTraits<float>::nlanes128>& v)
+v_pack_store(float16_t* ptr, const v_reg<float, V_TypeTraits<float>::nlanes128>& v)
{
for( int i = 0; i < v.nlanes; i++ )
{
diff --git a/include/opencv2/core/hal/intrin_msa.hpp b/include/opencv2/core/hal/intrin_msa.hpp
index 0db137b..a1fbb09 100755
--- a/include/opencv2/core/hal/intrin_msa.hpp
+++ b/include/opencv2/core/hal/intrin_msa.hpp
@@ -25,7 +25,7 @@ struct v_uint8x16
typedef uchar lane_type;
enum { nlanes = 16 };
- v_uint8x16() : val(msa_dupq_n_u8(0)) {}
+ v_uint8x16() {}
explicit v_uint8x16(v16u8 v) : val(v) {}
v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7,
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
@@ -33,6 +33,7 @@ struct v_uint8x16
uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = msa_ld1q_u8(v);
}
+
uchar get0() const
{
return msa_getq_lane_u8(val, 0);
@@ -46,7 +47,7 @@ struct v_int8x16
typedef schar lane_type;
enum { nlanes = 16 };
- v_int8x16() : val(msa_dupq_n_s8(0)) {}
+ v_int8x16() {}
explicit v_int8x16(v16i8 v) : val(v) {}
v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7,
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
@@ -54,6 +55,7 @@ struct v_int8x16
schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = msa_ld1q_s8(v);
}
+
schar get0() const
{
return msa_getq_lane_s8(val, 0);
@@ -67,13 +69,14 @@ struct v_uint16x8
typedef ushort lane_type;
enum { nlanes = 8 };
- v_uint16x8() : val(msa_dupq_n_u16(0)) {}
+ v_uint16x8() {}
explicit v_uint16x8(v8u16 v) : val(v) {}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
{
ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = msa_ld1q_u16(v);
}
+
ushort get0() const
{
return msa_getq_lane_u16(val, 0);
@@ -87,13 +90,14 @@ struct v_int16x8
typedef short lane_type;
enum { nlanes = 8 };
- v_int16x8() : val(msa_dupq_n_s16(0)) {}
+ v_int16x8() {}
explicit v_int16x8(v8i16 v) : val(v) {}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
{
short v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = msa_ld1q_s16(v);
}
+
short get0() const
{
return msa_getq_lane_s16(val, 0);
@@ -107,13 +111,14 @@ struct v_uint32x4
typedef unsigned int lane_type;
enum { nlanes = 4 };
- v_uint32x4() : val(msa_dupq_n_u32(0)) {}
+ v_uint32x4() {}
explicit v_uint32x4(v4u32 v) : val(v) {}
v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3)
{
unsigned int v[] = {v0, v1, v2, v3};
val = msa_ld1q_u32(v);
}
+
unsigned int get0() const
{
return msa_getq_lane_u32(val, 0);
@@ -127,17 +132,19 @@ struct v_int32x4
typedef int lane_type;
enum { nlanes = 4 };
- v_int32x4() : val(msa_dupq_n_s32(0)) {}
+ v_int32x4() {}
explicit v_int32x4(v4i32 v) : val(v) {}
v_int32x4(int v0, int v1, int v2, int v3)
{
int v[] = {v0, v1, v2, v3};
val = msa_ld1q_s32(v);
}
+
int get0() const
{
return msa_getq_lane_s32(val, 0);
}
+
v4i32 val;
};
@@ -146,17 +153,19 @@ struct v_float32x4
typedef float lane_type;
enum { nlanes = 4 };
- v_float32x4() : val(msa_dupq_n_f32(0.0f)) {}
+ v_float32x4() {}
explicit v_float32x4(v4f32 v) : val(v) {}
v_float32x4(float v0, float v1, float v2, float v3)
{
float v[] = {v0, v1, v2, v3};
val = msa_ld1q_f32(v);
}
+
float get0() const
{
return msa_getq_lane_f32(val, 0);
}
+
v4f32 val;
};
@@ -165,17 +174,19 @@ struct v_uint64x2
typedef uint64 lane_type;
enum { nlanes = 2 };
- v_uint64x2() : val(msa_dupq_n_u64(0)) {}
+ v_uint64x2() {}
explicit v_uint64x2(v2u64 v) : val(v) {}
v_uint64x2(uint64 v0, uint64 v1)
{
uint64 v[] = {v0, v1};
val = msa_ld1q_u64(v);
}
+
uint64 get0() const
{
return msa_getq_lane_u64(val, 0);
}
+
v2u64 val;
};
@@ -184,17 +195,19 @@ struct v_int64x2
typedef int64 lane_type;
enum { nlanes = 2 };
- v_int64x2() : val(msa_dupq_n_s64(0)) {}
+ v_int64x2() {}
explicit v_int64x2(v2i64 v) : val(v) {}
v_int64x2(int64 v0, int64 v1)
{
int64 v[] = {v0, v1};
val = msa_ld1q_s64(v);
}
+
int64 get0() const
{
return msa_getq_lane_s64(val, 0);
}
+
v2i64 val;
};
@@ -203,17 +216,19 @@ struct v_float64x2
typedef double lane_type;
enum { nlanes = 2 };
- v_float64x2() : val(msa_dupq_n_f64(0.0f)) {}
+ v_float64x2() {}
explicit v_float64x2(v2f64 v) : val(v) {}
v_float64x2(double v0, double v1)
{
double v[] = {v0, v1};
val = msa_ld1q_f64(v);
}
+
double get0() const
{
return msa_getq_lane_f64(val, 0);
}
+
v2f64 val;
};
@@ -1000,6 +1015,22 @@ OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min)
+
+#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \
+inline scalartype v_reduce_##func(const _Tpvec& a) \
+{ \
+ _Tpvec2 a1, a2; \
+ v_expand(a, a1, a2); \
+ return (scalartype)v_reduce_##func(v_##func(a1, a2)); \
+}
+
+OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min)
+OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max)
+OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min)
+OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max)
+
+
+
#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \
inline scalartype v_reduce_sum(const _Tpvec& a) \
{ \
@@ -1805,7 +1836,7 @@ inline v_float32x4 v_broadcast_element(const v_float32x4& a)
return v_setall_f32(v_extract_n<i>(a));
}
-////// FP16 suport ///////
+////// FP16 support ///////
#if CV_FP16
inline v_float32x4 v_load_expand(const float16_t* ptr)
{
diff --git a/include/opencv2/core/hal/intrin_neon.hpp b/include/opencv2/core/hal/intrin_neon.hpp
index 7411b28..280691b 100755
--- a/include/opencv2/core/hal/intrin_neon.hpp
+++ b/include/opencv2/core/hal/intrin_neon.hpp
@@ -1241,6 +1241,20 @@ inline int v_reduce_sum(const v_int16x8& a)
return vget_lane_s32(vpadd_s32(t1, t1), 0);
}
+#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \
+inline scalartype v_reduce_##func(const _Tpvec& a) \
+{ \
+ _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \
+ a0 = vp##vectorfunc##_##suffix(a0, a0); \
+ a0 = vp##vectorfunc##_##suffix(a0, a0); \
+ return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \
+}
+
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, max, max, u8)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, min, min, u8)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, max, max, s8)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, min, min, s8)
+
#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
{ \
@@ -1249,10 +1263,10 @@ inline scalartype v_reduce_##func(const _Tpvec& a) \
return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \
}
-OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, unsigned int, max, max, u16)
-OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, unsigned int, min, min, u16)
-OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, int, max, max, s16)
-OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, int, min, min, s16)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, max, max, u16)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, min, min, u16)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16)
+OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16)
#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
@@ -2129,10 +2143,12 @@ inline v_float32x4 v_lut(const float* tab, const int* idx)
}
inline v_float32x4 v_lut_pairs(const float* tab, const int* idx)
{
+ typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64;
+
uint64 CV_DECL_ALIGNED(32) elems[2] =
{
- *(uint64*)(tab + idx[0]),
- *(uint64*)(tab + idx[1])
+ *(unaligned_uint64*)(tab + idx[0]),
+ *(unaligned_uint64*)(tab + idx[1])
};
return v_float32x4(vreinterpretq_f32_u64(vld1q_u64(elems)));
}
diff --git a/include/opencv2/core/hal/intrin_sse.hpp b/include/opencv2/core/hal/intrin_sse.hpp
index 867ff55..f4b43a2 100755
--- a/include/opencv2/core/hal/intrin_sse.hpp
+++ b/include/opencv2/core/hal/intrin_sse.hpp
@@ -75,7 +75,8 @@ struct v_uint8x16
typedef __m128i vector_type;
enum { nlanes = 16 };
- v_uint8x16() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint8x16() {}
explicit v_uint8x16(__m128i v) : val(v) {}
v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7,
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
@@ -85,6 +86,7 @@ struct v_uint8x16
(char)v8, (char)v9, (char)v10, (char)v11,
(char)v12, (char)v13, (char)v14, (char)v15);
}
+
uchar get0() const
{
return (uchar)_mm_cvtsi128_si32(val);
@@ -99,7 +101,8 @@ struct v_int8x16
typedef __m128i vector_type;
enum { nlanes = 16 };
- v_int8x16() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int8x16() {}
explicit v_int8x16(__m128i v) : val(v) {}
v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7,
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
@@ -109,6 +112,7 @@ struct v_int8x16
(char)v8, (char)v9, (char)v10, (char)v11,
(char)v12, (char)v13, (char)v14, (char)v15);
}
+
schar get0() const
{
return (schar)_mm_cvtsi128_si32(val);
@@ -123,13 +127,15 @@ struct v_uint16x8
typedef __m128i vector_type;
enum { nlanes = 8 };
- v_uint16x8() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint16x8() {}
explicit v_uint16x8(__m128i v) : val(v) {}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
{
val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3,
(short)v4, (short)v5, (short)v6, (short)v7);
}
+
ushort get0() const
{
return (ushort)_mm_cvtsi128_si32(val);
@@ -144,13 +150,15 @@ struct v_int16x8
typedef __m128i vector_type;
enum { nlanes = 8 };
- v_int16x8() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int16x8() {}
explicit v_int16x8(__m128i v) : val(v) {}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
{
val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3,
(short)v4, (short)v5, (short)v6, (short)v7);
}
+
short get0() const
{
return (short)_mm_cvtsi128_si32(val);
@@ -165,12 +173,14 @@ struct v_uint32x4
typedef __m128i vector_type;
enum { nlanes = 4 };
- v_uint32x4() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint32x4() {}
explicit v_uint32x4(__m128i v) : val(v) {}
v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3)
{
val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3);
}
+
unsigned get0() const
{
return (unsigned)_mm_cvtsi128_si32(val);
@@ -185,12 +195,14 @@ struct v_int32x4
typedef __m128i vector_type;
enum { nlanes = 4 };
- v_int32x4() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int32x4() {}
explicit v_int32x4(__m128i v) : val(v) {}
v_int32x4(int v0, int v1, int v2, int v3)
{
val = _mm_setr_epi32(v0, v1, v2, v3);
}
+
int get0() const
{
return _mm_cvtsi128_si32(val);
@@ -205,12 +217,14 @@ struct v_float32x4
typedef __m128 vector_type;
enum { nlanes = 4 };
- v_float32x4() : val(_mm_setzero_ps()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_float32x4() {}
explicit v_float32x4(__m128 v) : val(v) {}
v_float32x4(float v0, float v1, float v2, float v3)
{
val = _mm_setr_ps(v0, v1, v2, v3);
}
+
float get0() const
{
return _mm_cvtss_f32(val);
@@ -225,12 +239,14 @@ struct v_uint64x2
typedef __m128i vector_type;
enum { nlanes = 2 };
- v_uint64x2() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_uint64x2() {}
explicit v_uint64x2(__m128i v) : val(v) {}
v_uint64x2(uint64 v0, uint64 v1)
{
val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32));
}
+
uint64 get0() const
{
#if !defined(__x86_64__) && !defined(_M_X64)
@@ -251,12 +267,14 @@ struct v_int64x2
typedef __m128i vector_type;
enum { nlanes = 2 };
- v_int64x2() : val(_mm_setzero_si128()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_int64x2() {}
explicit v_int64x2(__m128i v) : val(v) {}
v_int64x2(int64 v0, int64 v1)
{
val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32));
}
+
int64 get0() const
{
#if !defined(__x86_64__) && !defined(_M_X64)
@@ -277,12 +295,14 @@ struct v_float64x2
typedef __m128d vector_type;
enum { nlanes = 2 };
- v_float64x2() : val(_mm_setzero_pd()) {}
+ /* coverity[uninit_ctor]: suppress warning */
+ v_float64x2() {}
explicit v_float64x2(__m128d v) : val(v) {}
v_float64x2(double v0, double v1)
{
val = _mm_setr_pd(v0, v1);
}
+
double get0() const
{
return _mm_cvtsd_f64(val);
diff --git a/include/opencv2/core/hal/intrin_vsx.hpp b/include/opencv2/core/hal/intrin_vsx.hpp
index bda1d85..b198643 100755
--- a/include/opencv2/core/hal/intrin_vsx.hpp
+++ b/include/opencv2/core/hal/intrin_vsx.hpp
@@ -28,7 +28,7 @@ struct v_uint8x16
explicit v_uint8x16(const vec_uchar16& v) : val(v)
{}
- v_uint8x16() : val(vec_uchar16_z)
+ v_uint8x16()
{}
v_uint8x16(vec_bchar16 v) : val(vec_uchar16_c(v))
{}
@@ -36,6 +36,9 @@ struct v_uint8x16
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
: val(vec_uchar16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15))
{}
+
+ static inline v_uint8x16 zero() { return v_uint8x16(vec_uchar16_z); }
+
uchar get0() const
{ return vec_extract(val, 0); }
};
@@ -48,7 +51,7 @@ struct v_int8x16
explicit v_int8x16(const vec_char16& v) : val(v)
{}
- v_int8x16() : val(vec_char16_z)
+ v_int8x16()
{}
v_int8x16(vec_bchar16 v) : val(vec_char16_c(v))
{}
@@ -56,6 +59,9 @@ struct v_int8x16
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
: val(vec_char16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15))
{}
+
+ static inline v_int8x16 zero() { return v_int8x16(vec_char16_z); }
+
schar get0() const
{ return vec_extract(val, 0); }
};
@@ -68,13 +74,16 @@ struct v_uint16x8
explicit v_uint16x8(const vec_ushort8& v) : val(v)
{}
- v_uint16x8() : val(vec_ushort8_z)
+ v_uint16x8()
{}
v_uint16x8(vec_bshort8 v) : val(vec_ushort8_c(v))
{}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
: val(vec_ushort8_set(v0, v1, v2, v3, v4, v5, v6, v7))
{}
+
+ static inline v_uint16x8 zero() { return v_uint16x8(vec_ushort8_z); }
+
ushort get0() const
{ return vec_extract(val, 0); }
};
@@ -87,13 +96,16 @@ struct v_int16x8
explicit v_int16x8(const vec_short8& v) : val(v)
{}
- v_int16x8() : val(vec_short8_z)
+ v_int16x8()
{}
v_int16x8(vec_bshort8 v) : val(vec_short8_c(v))
{}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
: val(vec_short8_set(v0, v1, v2, v3, v4, v5, v6, v7))
{}
+
+ static inline v_int16x8 zero() { return v_int16x8(vec_short8_z); }
+
short get0() const
{ return vec_extract(val, 0); }
};
@@ -106,12 +118,15 @@ struct v_uint32x4
explicit v_uint32x4(const vec_uint4& v) : val(v)
{}
- v_uint32x4() : val(vec_uint4_z)
+ v_uint32x4()
{}
v_uint32x4(vec_bint4 v) : val(vec_uint4_c(v))
{}
v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) : val(vec_uint4_set(v0, v1, v2, v3))
{}
+
+ static inline v_uint32x4 zero() { return v_uint32x4(vec_uint4_z); }
+
uint get0() const
{ return vec_extract(val, 0); }
};
@@ -124,12 +139,15 @@ struct v_int32x4
explicit v_int32x4(const vec_int4& v) : val(v)
{}
- v_int32x4() : val(vec_int4_z)
+ v_int32x4()
{}
v_int32x4(vec_bint4 v) : val(vec_int4_c(v))
{}
v_int32x4(int v0, int v1, int v2, int v3) : val(vec_int4_set(v0, v1, v2, v3))
{}
+
+ static inline v_int32x4 zero() { return v_int32x4(vec_int4_z); }
+
int get0() const
{ return vec_extract(val, 0); }
};
@@ -142,12 +160,15 @@ struct v_float32x4
explicit v_float32x4(const vec_float4& v) : val(v)
{}
- v_float32x4() : val(vec_float4_z)
+ v_float32x4()
{}
v_float32x4(vec_bint4 v) : val(vec_float4_c(v))
{}
v_float32x4(float v0, float v1, float v2, float v3) : val(vec_float4_set(v0, v1, v2, v3))
{}
+
+ static inline v_float32x4 zero() { return v_float32x4(vec_float4_z); }
+
float get0() const
{ return vec_extract(val, 0); }
};
@@ -160,12 +181,15 @@ struct v_uint64x2
explicit v_uint64x2(const vec_udword2& v) : val(v)
{}
- v_uint64x2() : val(vec_udword2_z)
+ v_uint64x2()
{}
v_uint64x2(vec_bdword2 v) : val(vec_udword2_c(v))
{}
v_uint64x2(uint64 v0, uint64 v1) : val(vec_udword2_set(v0, v1))
{}
+
+ static inline v_uint64x2 zero() { return v_uint64x2(vec_udword2_z); }
+
uint64 get0() const
{ return vec_extract(val, 0); }
};
@@ -178,12 +202,15 @@ struct v_int64x2
explicit v_int64x2(const vec_dword2& v) : val(v)
{}
- v_int64x2() : val(vec_dword2_z)
+ v_int64x2()
{}
v_int64x2(vec_bdword2 v) : val(vec_dword2_c(v))
{}
v_int64x2(int64 v0, int64 v1) : val(vec_dword2_set(v0, v1))
{}
+
+ static inline v_int64x2 zero() { return v_int64x2(vec_dword2_z); }
+
int64 get0() const
{ return vec_extract(val, 0); }
};
@@ -196,12 +223,15 @@ struct v_float64x2
explicit v_float64x2(const vec_double2& v) : val(v)
{}
- v_float64x2() : val(vec_double2_z)
+ v_float64x2()
{}
v_float64x2(vec_bdword2 v) : val(vec_double2_c(v))
{}
v_float64x2(double v0, double v1) : val(vec_double2_set(v0, v1))
{}
+
+ static inline v_float64x2 zero() { return v_float64x2(vec_double2_z); }
+
double get0() const
{ return vec_extract(val, 0); }
};
@@ -229,7 +259,7 @@ OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float64x2, double)
* if vec_xxx_c defined as C++ cast, clang-5 will pass it
*/
#define OPENCV_HAL_IMPL_VSX_INITVEC(_Tpvec, _Tp, suffix, cast) \
-inline _Tpvec v_setzero_##suffix() { return _Tpvec(); } \
+inline _Tpvec v_setzero_##suffix() { return _Tpvec(vec_splats((_Tp)0)); } \
inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(vec_splats((_Tp)v));} \
template<typename _Tpvec0> inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0 &a) \
{ return _Tpvec((cast)a.val); }
@@ -660,7 +690,7 @@ inline _Tpvec v_rotate_##suffix(const _Tpvec& a)
{ \
const int wd = imm * sizeof(typename _Tpvec::lane_type); \
if (wd > 15) \
- return _Tpvec(); \
+ return _Tpvec::zero(); \
return _Tpvec((cast)shf(vec_uchar16_c(a.val), vec_uchar16_sp(wd << 3))); \
}
@@ -973,7 +1003,7 @@ inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signm
template<typename _Tpvec>
inline bool v_check_all(const _Tpvec& a)
-{ return vec_all_lt(a.val, _Tpvec().val); }
+{ return vec_all_lt(a.val, _Tpvec::zero().val); }
inline bool v_check_all(const v_uint8x16& a)
{ return v_check_all(v_reinterpret_as_s8(a)); }
inline bool v_check_all(const v_uint16x8& a)
@@ -989,7 +1019,7 @@ inline bool v_check_all(const v_float64x2& a)
template<typename _Tpvec>
inline bool v_check_any(const _Tpvec& a)
-{ return vec_any_lt(a.val, _Tpvec().val); }
+{ return vec_any_lt(a.val, _Tpvec::zero().val); }
inline bool v_check_any(const v_uint8x16& a)
{ return v_check_any(v_reinterpret_as_s8(a)); }
inline bool v_check_any(const v_uint16x8& a)
@@ -1338,7 +1368,7 @@ inline v_float32x4 v_load_expand(const float16_t* ptr)
return v_float32x4(vec_extract_fp_from_shorth(vf16));
#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM)
vec_float4 vf32;
- __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wf" (vf32) : "wa" (vec_mergeh(vf16, vf16)));
+ __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wa" (vf32) : "wa" (vec_mergeh(vf16, vf16)));
return v_float32x4(vf32);
#else
const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000);
@@ -1363,7 +1393,7 @@ inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
// fixme: Is there any builtin op or intrinsic that cover "xvcvsphp"?
#if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM)
vec_ushort8 vf16;
- __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wf" (v.val));
+ __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wa" (v.val));
vec_st_l8(vec_mergesqe(vf16, vf16), ptr);
#else
const vec_int4 signmask = vec_int4_sp(0x80000000);
@@ -1564,81 +1594,10 @@ OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_uint32x4, vec_uint4)
OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_int32x4, vec_int4)
OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_float32x4, vec_float4)
-template<int i>
-inline v_int8x16 v_broadcast_element(v_int8x16 v)
-{
- return v_int8x16(vec_perm(v.val, v.val, vec_splats((unsigned char)i)));
-}
-
-template<int i>
-inline v_uint8x16 v_broadcast_element(v_uint8x16 v)
-{
- return v_uint8x16(vec_perm(v.val, v.val, vec_splats((unsigned char)i)));
-}
-
-template<int i>
-inline v_int16x8 v_broadcast_element(v_int16x8 v)
-{
- unsigned char t0 = 2*i, t1 = 2*i + 1;
- vec_uchar16 p = {t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1};
- return v_int16x8(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_uint16x8 v_broadcast_element(v_uint16x8 v)
-{
- unsigned char t0 = 2*i, t1 = 2*i + 1;
- vec_uchar16 p = {t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1, t0, t1};
- return v_uint16x8(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_int32x4 v_broadcast_element(v_int32x4 v)
-{
- unsigned char t0 = 4*i, t1 = 4*i + 1, t2 = 4*i + 2, t3 = 4*i + 3;
- vec_uchar16 p = {t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3};
- return v_int32x4(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_uint32x4 v_broadcast_element(v_uint32x4 v)
-{
- unsigned char t0 = 4*i, t1 = 4*i + 1, t2 = 4*i + 2, t3 = 4*i + 3;
- vec_uchar16 p = {t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3};
- return v_uint32x4(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_int64x2 v_broadcast_element(v_int64x2 v)
-{
- unsigned char t0 = 8*i, t1 = 8*i + 1, t2 = 8*i + 2, t3 = 8*i + 3, t4 = 8*i + 4, t5 = 8*i + 5, t6 = 8*i + 6, t7 = 8*i + 7;
- vec_uchar16 p = {t0, t1, t2, t3, t4, t5, t6, t7, t0, t1, t2, t3, t4, t5, t6, t7};
- return v_int64x2(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_uint64x2 v_broadcast_element(v_uint64x2 v)
-{
- unsigned char t0 = 8*i, t1 = 8*i + 1, t2 = 8*i + 2, t3 = 8*i + 3, t4 = 8*i + 4, t5 = 8*i + 5, t6 = 8*i + 6, t7 = 8*i + 7;
- vec_uchar16 p = {t0, t1, t2, t3, t4, t5, t6, t7, t0, t1, t2, t3, t4, t5, t6, t7};
- return v_uint64x2(vec_perm(v.val, v.val, p));
-}
-
-template<int i>
-inline v_float32x4 v_broadcast_element(v_float32x4 v)
-{
- unsigned char t0 = 4*i, t1 = 4*i + 1, t2 = 4*i + 2, t3 = 4*i + 3;
- vec_uchar16 p = {t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3, t0, t1, t2, t3};
- return v_float32x4(vec_perm(v.val, v.val, p));
-}
+template<int i, typename Tvec>
+inline Tvec v_broadcast_element(const Tvec& v)
+{ return Tvec(vec_splat(v.val, i)); }
-template<int i>
-inline v_float64x2 v_broadcast_element(v_float64x2 v)
-{
- unsigned char t0 = 8*i, t1 = 8*i + 1, t2 = 8*i + 2, t3 = 8*i + 3, t4 = 8*i + 4, t5 = 8*i + 5, t6 = 8*i + 6, t7 = 8*i + 7;
- vec_uchar16 p = {t0, t1, t2, t3, t4, t5, t6, t7, t0, t1, t2, t3, t4, t5, t6, t7};
- return v_float64x2(vec_perm(v.val, v.val, p));
-}
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END
diff --git a/include/opencv2/core/hal/intrin_wasm.hpp b/include/opencv2/core/hal/intrin_wasm.hpp
index 7b3259f..22c4a34 100755
--- a/include/opencv2/core/hal/intrin_wasm.hpp
+++ b/include/opencv2/core/hal/intrin_wasm.hpp
@@ -41,7 +41,7 @@ struct v_uint8x16
typedef v128_t vector_type;
enum { nlanes = 16 };
- v_uint8x16() : val(wasm_i8x16_splat(0)) {}
+ v_uint8x16() {}
explicit v_uint8x16(v128_t v) : val(v) {}
v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7,
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
@@ -49,6 +49,7 @@ struct v_uint8x16
uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = wasm_v128_load(v);
}
+
uchar get0() const
{
return (uchar)wasm_i8x16_extract_lane(val, 0);
@@ -63,7 +64,7 @@ struct v_int8x16
typedef v128_t vector_type;
enum { nlanes = 16 };
- v_int8x16() : val(wasm_i8x16_splat(0)) {}
+ v_int8x16() {}
explicit v_int8x16(v128_t v) : val(v) {}
v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7,
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
@@ -71,6 +72,7 @@ struct v_int8x16
schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = wasm_v128_load(v);
}
+
schar get0() const
{
return wasm_i8x16_extract_lane(val, 0);
@@ -85,16 +87,17 @@ struct v_uint16x8
typedef v128_t vector_type;
enum { nlanes = 8 };
- v_uint16x8() : val(wasm_i16x8_splat(0)) {}
+ v_uint16x8() {}
explicit v_uint16x8(v128_t v) : val(v) {}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
{
ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = wasm_v128_load(v);
}
+
ushort get0() const
{
- return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemeted yet
+ return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemented yet
}
v128_t val;
@@ -106,13 +109,14 @@ struct v_int16x8
typedef v128_t vector_type;
enum { nlanes = 8 };
- v_int16x8() : val(wasm_i16x8_splat(0)) {}
+ v_int16x8() {}
explicit v_int16x8(v128_t v) : val(v) {}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
{
short v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = wasm_v128_load(v);
}
+
short get0() const
{
return wasm_i16x8_extract_lane(val, 0);
@@ -127,13 +131,14 @@ struct v_uint32x4
typedef v128_t vector_type;
enum { nlanes = 4 };
- v_uint32x4() : val(wasm_i32x4_splat(0)) {}
+ v_uint32x4() {}
explicit v_uint32x4(v128_t v) : val(v) {}
v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3)
{
unsigned v[] = {v0, v1, v2, v3};
val = wasm_v128_load(v);
}
+
unsigned get0() const
{
return (unsigned)wasm_i32x4_extract_lane(val, 0);
@@ -148,13 +153,14 @@ struct v_int32x4
typedef v128_t vector_type;
enum { nlanes = 4 };
- v_int32x4() : val(wasm_i32x4_splat(0)) {}
+ v_int32x4() {}
explicit v_int32x4(v128_t v) : val(v) {}
v_int32x4(int v0, int v1, int v2, int v3)
{
int v[] = {v0, v1, v2, v3};
val = wasm_v128_load(v);
}
+
int get0() const
{
return wasm_i32x4_extract_lane(val, 0);
@@ -169,13 +175,14 @@ struct v_float32x4
typedef v128_t vector_type;
enum { nlanes = 4 };
- v_float32x4() : val(wasm_f32x4_splat(0)) {}
+ v_float32x4() {}
explicit v_float32x4(v128_t v) : val(v) {}
v_float32x4(float v0, float v1, float v2, float v3)
{
float v[] = {v0, v1, v2, v3};
val = wasm_v128_load(v);
}
+
float get0() const
{
return wasm_f32x4_extract_lane(val, 0);
@@ -190,26 +197,17 @@ struct v_uint64x2
typedef v128_t vector_type;
enum { nlanes = 2 };
-#ifdef __wasm_unimplemented_simd128__
- v_uint64x2() : val(wasm_i64x2_splat(0)) {}
-#else
- v_uint64x2() : val(wasm_i32x4_splat(0)) {}
-#endif
+ v_uint64x2() {}
explicit v_uint64x2(v128_t v) : val(v) {}
v_uint64x2(uint64 v0, uint64 v1)
{
uint64 v[] = {v0, v1};
val = wasm_v128_load(v);
}
+
uint64 get0() const
{
-#ifdef __wasm_unimplemented_simd128__
return (uint64)wasm_i64x2_extract_lane(val, 0);
-#else
- uint64 des[2];
- wasm_v128_store(des, val);
- return des[0];
-#endif
}
v128_t val;
@@ -221,26 +219,17 @@ struct v_int64x2
typedef v128_t vector_type;
enum { nlanes = 2 };
-#ifdef __wasm_unimplemented_simd128__
- v_int64x2() : val(wasm_i64x2_splat(0)) {}
-#else
- v_int64x2() : val(wasm_i32x4_splat(0)) {}
-#endif
+ v_int64x2() {}
explicit v_int64x2(v128_t v) : val(v) {}
v_int64x2(int64 v0, int64 v1)
{
int64 v[] = {v0, v1};
val = wasm_v128_load(v);
}
+
int64 get0() const
{
-#ifdef __wasm_unimplemented_simd128__
return wasm_i64x2_extract_lane(val, 0);
-#else
- int64 des[2];
- wasm_v128_store(des, val);
- return des[0];
-#endif
}
v128_t val;
@@ -252,26 +241,17 @@ struct v_float64x2
typedef v128_t vector_type;
enum { nlanes = 2 };
-#ifdef __wasm_unimplemented_simd128__
- v_float64x2() : val(wasm_f64x2_splat(0)) {}
-#else
- v_float64x2() : val(wasm_f32x4_splat(0)) {}
-#endif
+ v_float64x2() {}
explicit v_float64x2(v128_t v) : val(v) {}
v_float64x2(double v0, double v1)
{
double v[] = {v0, v1};
val = wasm_v128_load(v);
}
+
double get0() const
{
-#ifdef __wasm_unimplemented_simd128__
return wasm_f64x2_extract_lane(val, 0);
-#else
- double des[2];
- wasm_v128_store(des, val);
- return des[0];
-#endif
}
v128_t val;
@@ -1799,22 +1779,9 @@ OPENCV_HAL_IMPL_WASM_INITVEC(v_int16x8, short, s16, i16x8, short)
OPENCV_HAL_IMPL_WASM_INITVEC(v_uint32x4, unsigned, u32, i32x4, int)
OPENCV_HAL_IMPL_WASM_INITVEC(v_int32x4, int, s32, i32x4, int)
OPENCV_HAL_IMPL_WASM_INITVEC(v_float32x4, float, f32, f32x4, float)
-
-#ifdef __wasm_unimplemented_simd128__
OPENCV_HAL_IMPL_WASM_INITVEC(v_uint64x2, uint64, u64, i64x2, int64)
OPENCV_HAL_IMPL_WASM_INITVEC(v_int64x2, int64, s64, i64x2, int64)
OPENCV_HAL_IMPL_WASM_INITVEC(v_float64x2, double, f64, f64x2, double)
-#else
-#define OPENCV_HAL_IMPL_FALLBACK_INITVEC(_Tpvec, _Tp, suffix, _Tps) \
-inline _Tpvec v_setzero_##suffix() { return _Tpvec((_Tps)0, (_Tps)0); } \
-inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec((_Tps)v, (_Tps)v); } \
-template<typename _Tpvec0> inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \
-{ return _Tpvec(a.val); }
-
-OPENCV_HAL_IMPL_FALLBACK_INITVEC(v_uint64x2, uint64, u64, int64)
-OPENCV_HAL_IMPL_FALLBACK_INITVEC(v_int64x2, int64, s64, int64)
-OPENCV_HAL_IMPL_FALLBACK_INITVEC(v_float64x2, double, f64, double)
-#endif
//////////////// PACK ///////////////
inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b)
@@ -1933,28 +1900,18 @@ inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b)
template<int n>
inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1)));
v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n);
v128_t b1 = wasm_u64x2_shr(wasm_i64x2_add(b.val, delta), n);
return v_uint32x4(wasm_v8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27));
-#else
- fallback::v_uint64x2 a_(a), b_(b);
- return fallback::v_rshr_pack<n>(a_, b_);
-#endif
}
template<int n>
inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1)));
v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n);
v128_t b1 = wasm_i64x2_shr(wasm_i64x2_add(b.val, delta), n);
return v_int32x4(wasm_v8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27));
-#else
- fallback::v_int64x2 a_(a), b_(b);
- return fallback::v_rshr_pack<n>(a_, b_);
-#endif
}
template<int n>
inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b)
@@ -2141,7 +2098,6 @@ inline void v_rshr_pack_store(short* ptr, const v_int32x4& a)
template<int n>
inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1)));
v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n);
v128_t r = wasm_v8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11);
@@ -2150,15 +2106,10 @@ inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a)
for (int i=0; i<2; ++i) {
ptr[i] = t_ptr[i];
}
-#else
- fallback::v_uint64x2 _a(a);
- fallback::v_rshr_pack_store<n>(ptr, _a);
-#endif
}
template<int n>
inline void v_rshr_pack_store(int* ptr, const v_int64x2& a)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1)));
v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n);
v128_t r = wasm_v8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11);
@@ -2167,10 +2118,6 @@ inline void v_rshr_pack_store(int* ptr, const v_int64x2& a)
for (int i=0; i<2; ++i) {
ptr[i] = t_ptr[i];
}
-#else
- fallback::v_int64x2 _a(a);
- fallback::v_rshr_pack_store<n>(ptr, _a);
-#endif
}
template<int n>
inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a)
@@ -2230,7 +2177,6 @@ inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uin
const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f,
const v_uint64x2& g, const v_uint64x2& h)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t maxval = wasm_i32x4_splat(255);
v128_t a1 = wasm_v128_bitselect(maxval, a.val, ((__u64x2)(a.val) > (__u64x2)maxval));
v128_t b1 = wasm_v128_bitselect(maxval, b.val, ((__u64x2)(b.val) > (__u64x2)maxval));
@@ -2247,10 +2193,6 @@ inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uin
v128_t abcd = wasm_v8x16_shuffle(ab, cd, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19);
v128_t efgh = wasm_v8x16_shuffle(ef, gh, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19);
return v_uint8x16(wasm_v8x16_shuffle(abcd, efgh, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23));
-#else
- fallback::v_uint64x2 a_(a), b_(b), c_(c), d_(d), e_(e), f_(f), g_(g), h_(h);
- return fallback::v_pack_b(a_, b_, c_, d_, e_, f_, g_, h_);
-#endif
}
inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0,
@@ -2312,8 +2254,6 @@ OPENCV_HAL_IMPL_WASM_BIN_OP(+, v_float32x4, wasm_f32x4_add)
OPENCV_HAL_IMPL_WASM_BIN_OP(-, v_float32x4, wasm_f32x4_sub)
OPENCV_HAL_IMPL_WASM_BIN_OP(*, v_float32x4, wasm_f32x4_mul)
OPENCV_HAL_IMPL_WASM_BIN_OP(/, v_float32x4, wasm_f32x4_div)
-
-#ifdef __wasm_unimplemented_simd128__
OPENCV_HAL_IMPL_WASM_BIN_OP(+, v_uint64x2, wasm_i64x2_add)
OPENCV_HAL_IMPL_WASM_BIN_OP(-, v_uint64x2, wasm_i64x2_sub)
OPENCV_HAL_IMPL_WASM_BIN_OP(+, v_int64x2, wasm_i64x2_add)
@@ -2322,30 +2262,6 @@ OPENCV_HAL_IMPL_WASM_BIN_OP(+, v_float64x2, wasm_f64x2_add)
OPENCV_HAL_IMPL_WASM_BIN_OP(-, v_float64x2, wasm_f64x2_sub)
OPENCV_HAL_IMPL_WASM_BIN_OP(*, v_float64x2, wasm_f64x2_mul)
OPENCV_HAL_IMPL_WASM_BIN_OP(/, v_float64x2, wasm_f64x2_div)
-#else
-#define OPENCV_HAL_IMPL_FALLBACK_BIN_OP(bin_op, _Tpvec) \
-inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \
-{ \
- fallback::_Tpvec a_(a), b_(b); \
- return _Tpvec((a_) bin_op (b_)); \
-} \
-inline _Tpvec& operator bin_op##= (_Tpvec& a, const _Tpvec& b) \
-{ \
- fallback::_Tpvec a_(a), b_(b); \
- a_ bin_op##= b_; \
- a = _Tpvec(a_); \
- return a; \
-}
-
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(+, v_uint64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(-, v_uint64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(+, v_int64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(-, v_int64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(+, v_float64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(-, v_float64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(*, v_float64x2)
-OPENCV_HAL_IMPL_FALLBACK_BIN_OP(/, v_float64x2)
-#endif
// saturating multiply 8-bit, 16-bit
#define OPENCV_HAL_IMPL_WASM_MUL_SAT(_Tpvec, _Tpwvec) \
@@ -2407,19 +2323,11 @@ inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b,
inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b,
v_uint64x2& c, v_uint64x2& d)
{
-#ifdef __wasm_unimplemented_simd128__
v_uint64x2 a0, a1, b0, b1;
v_expand(a, a0, a1);
v_expand(b, b0, b1);
c.val = ((__u64x2)(a0.val) * (__u64x2)(b0.val));
d.val = ((__u64x2)(a1.val) * (__u64x2)(b1.val));
-#else
- fallback::v_uint32x4 a_(a), b_(b);
- fallback::v_uint64x2 c_, d_;
- fallback::v_mul_expand(a_, b_, c_, d_);
- c = v_uint64x2(c_);
- d = v_uint64x2(d_);
-#endif
}
inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b)
@@ -2459,7 +2367,6 @@ inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32
inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t a0 = wasm_i64x2_shr(wasm_i64x2_shl(a.val, 32), 32);
v128_t a1 = wasm_i64x2_shr(a.val, 32);
v128_t b0 = wasm_i64x2_shr(wasm_i64x2_shl(b.val, 32), 32);
@@ -2467,22 +2374,10 @@ inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b)
v128_t c = (v128_t)((__i64x2)a0 * (__i64x2)b0);
v128_t d = (v128_t)((__i64x2)a1 * (__i64x2)b1);
return v_int64x2(wasm_i64x2_add(c, d));
-#else
- fallback::v_int32x4 a_(a);
- fallback::v_int32x4 b_(b);
- return fallback::v_dotprod(a_, b_);
-#endif
}
inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c)
{
-#ifdef __wasm_unimplemented_simd128__
return v_dotprod(a, b) + c;
-#else
- fallback::v_int32x4 a_(a);
- fallback::v_int32x4 b_(b);
- fallback::v_int64x2 c_(c);
- return fallback::v_dotprod(a_, b_, c_);
-#endif
}
// 8 >> 32
@@ -2517,32 +2412,32 @@ inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const
// 16 >> 64
inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b)
{
- fallback::v_uint16x8 a_(a);
- fallback::v_uint16x8 b_(b);
- return fallback::v_dotprod_expand(a_, b_);
+ v128_t a0 = wasm_u32x4_shr(wasm_i32x4_shl(a.val, 16), 16);
+ v128_t a1 = wasm_u32x4_shr(a.val, 16);
+ v128_t b0 = wasm_u32x4_shr(wasm_i32x4_shl(b.val, 16), 16);
+ v128_t b1 = wasm_u32x4_shr(b.val, 16);
+ return v_uint64x2((
+ v_dotprod(v_int32x4(a0), v_int32x4(b0)) +
+ v_dotprod(v_int32x4(a1), v_int32x4(b1))).val
+ );
}
inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c)
-{
- fallback::v_uint16x8 a_(a);
- fallback::v_uint16x8 b_(b);
- fallback::v_uint64x2 c_(c);
- return fallback::v_dotprod_expand(a_, b_, c_);
-}
+{ return v_dotprod_expand(a, b) + c; }
inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b)
{
- fallback::v_int16x8 a_(a);
- fallback::v_int16x8 b_(b);
- return fallback::v_dotprod_expand(a_, b_);
+ v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16);
+ v128_t a1 = wasm_i32x4_shr(a.val, 16);
+ v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16);
+ v128_t b1 = wasm_i32x4_shr(b.val, 16);
+ return v_int64x2((
+ v_dotprod(v_int32x4(a0), v_int32x4(b0)) +
+ v_dotprod(v_int32x4(a1), v_int32x4(b1)))
+ );
}
inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c)
-{
- fallback::v_int16x8 a_(a);
- fallback::v_int16x8 b_(b);
- fallback::v_int64x2 c_(c);
- return fallback::v_dotprod_expand(a_, b_, c_);
-}
+{ return v_dotprod_expand(a, b) + c; }
// 32 >> 64f
inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b)
@@ -2612,44 +2507,24 @@ OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float64x2)
inline v_float32x4 v_sqrt(const v_float32x4& x)
{
-#ifdef __wasm_unimplemented_simd128__
return v_float32x4(wasm_f32x4_sqrt(x.val));
-#else
- fallback::v_float32x4 x_(x);
- return fallback::v_sqrt(x_);
-#endif
}
inline v_float32x4 v_invsqrt(const v_float32x4& x)
{
-#ifdef __wasm_unimplemented_simd128__
const v128_t _1_0 = wasm_f32x4_splat(1.0);
return v_float32x4(wasm_f32x4_div(_1_0, wasm_f32x4_sqrt(x.val)));
-#else
- fallback::v_float32x4 x_(x);
- return fallback::v_invsqrt(x_);
-#endif
}
inline v_float64x2 v_sqrt(const v_float64x2& x)
{
-#ifdef __wasm_unimplemented_simd128__
return v_float64x2(wasm_f64x2_sqrt(x.val));
-#else
- fallback::v_float64x2 x_(x);
- return fallback::v_sqrt(x_);
-#endif
}
inline v_float64x2 v_invsqrt(const v_float64x2& x)
{
-#ifdef __wasm_unimplemented_simd128__
const v128_t _1_0 = wasm_f64x2_splat(1.0);
return v_float64x2(wasm_f64x2_div(_1_0, wasm_f64x2_sqrt(x.val)));
-#else
- fallback::v_float64x2 x_(x);
- return fallback::v_invsqrt(x_);
-#endif
}
#define OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(_Tpuvec, _Tpsvec, suffix, zsuffix, shiftWidth) \
@@ -2668,12 +2543,7 @@ inline v_float32x4 v_abs(const v_float32x4& x)
{ return v_float32x4(wasm_f32x4_abs(x.val)); }
inline v_float64x2 v_abs(const v_float64x2& x)
{
-#ifdef __wasm_unimplemented_simd128__
return v_float64x2(wasm_f64x2_abs(x.val));
-#else
- fallback::v_float64x2 x_(x);
- return fallback::v_abs(x_);
-#endif
}
// TODO: exp, log, sin, cos
@@ -2684,23 +2554,18 @@ inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \
return _Tpvec(intrin(a.val, b.val)); \
}
+#define OPENCV_HAL_IMPL_WASM_BIN_FUNC_FALLBACK(_Tpvec, func, intrin) \
+inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \
+{ \
+ fallback::_Tpvec a_(a); \
+ fallback::_Tpvec b_(b); \
+ return _Tpvec(fallback::func(a_, b_)); \
+}
+
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_min, wasm_f32x4_min)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_max, wasm_f32x4_max)
-
-#ifdef __wasm_unimplemented_simd128__
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_min, wasm_f64x2_min)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_max, wasm_f64x2_max)
-#else
-#define OPENCV_HAL_IMPL_WASM_MINMAX_64f_FUNC(func) \
-inline v_float64x2 func(const v_float64x2& a, const v_float64x2& b) \
-{ \
- fallback::v_float64x2 a_(a), b_(b); \
- return fallback::func(a_, b_); \
-}
-
-OPENCV_HAL_IMPL_WASM_MINMAX_64f_FUNC(v_min)
-OPENCV_HAL_IMPL_WASM_MINMAX_64f_FUNC(v_max)
-#endif
#define OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(_Tpvec, suffix) \
inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \
@@ -2755,24 +2620,7 @@ OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int16x8, i16x8, i16x8)
OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint32x4, u32x4, i32x4)
OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int32x4, i32x4, i32x4)
OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float32x4, f32x4, f32x4)
-
-#ifdef __wasm_unimplemented_simd128__
OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float64x2, f64x2, f64x2)
-#else
-#define OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(_Tpvec, bin_op) \
-inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \
-{ \
- fallback::_Tpvec a_(a), b_(b); \
- return _Tpvec((a_) bin_op (b_));\
-} \
-
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, ==)
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, !=)
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, <)
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, >)
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, <=)
-OPENCV_HAL_IMPL_INIT_FALLBACK_CMP_OP(v_float64x2, >=)
-#endif
#define OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(_Tpvec, cast) \
inline _Tpvec operator == (const _Tpvec& a, const _Tpvec& b) \
@@ -2791,14 +2639,9 @@ inline v_float32x4 v_not_nan(const v_float32x4& a)
}
inline v_float64x2 v_not_nan(const v_float64x2& a)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t z = wasm_i64x2_splat(0x7fffffffffffffff);
v128_t t = wasm_i64x2_splat(0x7ff0000000000000);
return v_float64x2((__u64x2)(wasm_v128_and(a.val, z)) < (__u64x2)t);
-#else
- fallback::v_float64x2 a_(a);
- return fallback::v_not_nan(a_);
-#endif
}
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_add_wrap, wasm_i8x16_add)
@@ -2809,8 +2652,14 @@ OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_sub_wrap, wasm_i8x16_sub)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_sub_wrap, wasm_i8x16_sub)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_sub_wrap, wasm_i16x8_sub)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_sub_wrap, wasm_i16x8_sub)
+#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) >= (2000000)
+// details: https://github.com/opencv/opencv/issues/18097 ( https://github.com/emscripten-core/emscripten/issues/12018 )
+OPENCV_HAL_IMPL_WASM_BIN_FUNC_FALLBACK(v_uint8x16, v_mul_wrap, wasm_i8x16_mul)
+OPENCV_HAL_IMPL_WASM_BIN_FUNC_FALLBACK(v_int8x16, v_mul_wrap, wasm_i8x16_mul)
+#else
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_mul_wrap, wasm_i8x16_mul)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_mul_wrap, wasm_i8x16_mul)
+#endif
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_mul_wrap, wasm_i16x8_mul)
OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_mul_wrap, wasm_i16x8_mul)
@@ -2879,32 +2728,30 @@ inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b)
}
inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b)
{
-#ifdef __wasm_unimplemented_simd128__
v128_t absmask_vec = wasm_u64x2_shr(wasm_i32x4_splat(-1), 1);
return v_float64x2(wasm_v128_and(wasm_f64x2_sub(a.val, b.val), absmask_vec));
-#else
- fallback::v_float64x2 a_(a), b_(b);
- return fallback::v_absdiff(a_, b_);
-#endif
}
-#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec) \
+#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec, suffix) \
inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \
{ \
- fallback::_Tpvec a_(a), b_(b); \
- return fallback::v_magnitude(a_, b_); \
+ v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \
+ v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \
+ return _Tpvec(wasm_##suffix##_sqrt(wasm_##suffix##_add(a_Square, b_Square))); \
} \
inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \
{ \
- return v_fma(a, a, b*b); \
+ v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \
+ v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \
+ return _Tpvec(wasm_##suffix##_add(a_Square, b_Square)); \
} \
inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \
{ \
- return v_fma(a, b, c); \
+ return _Tpvec(wasm_##suffix##_add(wasm_##suffix##_mul(a.val, b.val), c.val)); \
}
-OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4)
-OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2)
+OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4, f32x4)
+OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2, f64x2)
#define OPENCV_HAL_IMPL_WASM_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, ssuffix) \
inline _Tpuvec operator << (const _Tpuvec& a, int imm) \
@@ -2947,37 +2794,7 @@ inline _Tpsvec v_shr(const _Tpsvec& a) \
OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint8x16, v_int8x16, i8x16, u8x16)
OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint16x8, v_int16x8, i16x8, u16x8)
OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint32x4, v_int32x4, i32x4, u32x4)
-
-#ifdef __wasm_unimplemented_simd128__
OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint64x2, v_int64x2, i64x2, u64x2)
-#else
-#define OPENCV_HAL_IMPL_FALLBACK_SHIFT_OP(_Tpvec) \
-inline _Tpvec operator << (const _Tpvec& a, int imm) \
-{ \
- fallback::_Tpvec a_(a); \
- return a_ << imm; \
-} \
-inline _Tpvec operator >> (const _Tpvec& a, int imm) \
-{ \
- fallback::_Tpvec a_(a); \
- return a_ >> imm; \
-} \
-template<int imm> \
-inline _Tpvec v_shl(const _Tpvec& a) \
-{ \
- fallback::_Tpvec a_(a); \
- return fallback::v_shl<imm>(a_); \
-} \
-template<int imm> \
-inline _Tpvec v_shr(const _Tpvec& a) \
-{ \
- fallback::_Tpvec a_(a); \
- return fallback::v_shr<imm>(a_); \
-} \
-
-OPENCV_HAL_IMPL_FALLBACK_SHIFT_OP(v_uint64x2)
-OPENCV_HAL_IMPL_FALLBACK_SHIFT_OP(v_int64x2)
-#endif
namespace hal_wasm_internal
{
@@ -3182,9 +2999,18 @@ OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint8x16, unsigned)
OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int8x16, int)
OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint16x8, unsigned)
OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int16x8, int)
-OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint64x2, uint64)
-OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int64x2, int64)
-OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_float64x2, double)
+
+
+#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \
+inline scalartype v_reduce_sum(const _Tpvec& a) \
+{ \
+ regtype val = a.val; \
+ val = wasm_##suffix##_add(val, wasm_v8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \
+ return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \
+}
+OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_uint64x2, uint64, v128_t, i64x2, i64x2)
+OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_int64x2, int64, v128_t, i64x2, i64x2)
+OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_float64x2, double, v128_t, f64x2,f64x2)
inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b,
const v_float32x4& c, const v_float32x4& d)
@@ -3320,30 +3146,27 @@ OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int16x8, i16x8, short)
OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint32x4, i32x4, int)
OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int32x4, i32x4, int)
OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float32x4, i32x4, float)
+OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float64x2, f64x2, double)
+
+#define OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(_Tpvec, suffix, esuffix) \
+inline bool v_check_all(const _Tpvec& a) \
+{ \
+ v128_t masked = v_reinterpret_as_##esuffix(a).val; \
+ masked = wasm_i32x4_replace_lane(masked, 0, 0xffffffff); \
+ masked = wasm_i32x4_replace_lane(masked, 2, 0xffffffff); \
+ return wasm_i8x16_all_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \
+} \
+inline bool v_check_any(const _Tpvec& a) \
+{ \
+ v128_t masked = v_reinterpret_as_##esuffix(a).val; \
+ masked = wasm_i32x4_replace_lane(masked, 0, 0x0); \
+ masked = wasm_i32x4_replace_lane(masked, 2, 0x0); \
+ return wasm_i8x16_any_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \
+} \
+
+OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_int64x2, i32x4, s32)
+OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_uint64x2, i32x4, u32)
-inline int v_signmask(const v_float64x2& a)
-{
- fallback::v_float64x2 a_(a);
- return fallback::v_signmask(a_);
-}
-inline bool v_check_all(const v_float64x2& a)
-{
-#ifdef __wasm_unimplemented_simd128__
- return wasm_i8x16_all_true((__i64x2)(a.val) < (__i64x2)(wasm_i64x2_splat(0)));
-#else
- fallback::v_float64x2 a_(a);
- return fallback::v_check_all(a_);
-#endif
-}
-inline bool v_check_any(const v_float64x2& a)
-{
-#ifdef __wasm_unimplemented_simd128__
- return wasm_i8x16_any_true((__i64x2)(a.val) < (__i64x2)(wasm_i64x2_splat(0)));;
-#else
- fallback::v_float64x2 a_(a);
- return fallback::v_check_any(a_);
-#endif
-}
inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); }
inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); }
@@ -3368,8 +3191,8 @@ OPENCV_HAL_IMPL_WASM_SELECT(v_uint16x8)
OPENCV_HAL_IMPL_WASM_SELECT(v_int16x8)
OPENCV_HAL_IMPL_WASM_SELECT(v_uint32x4)
OPENCV_HAL_IMPL_WASM_SELECT(v_int32x4)
-// OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2)
-// OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2)
+OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2)
+OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2)
OPENCV_HAL_IMPL_WASM_SELECT(v_float32x4)
OPENCV_HAL_IMPL_WASM_SELECT(v_float64x2)
diff --git a/include/opencv2/core/hal/msa_macros.h b/include/opencv2/core/hal/msa_macros.h
index 3ed6e58..bd6ddb1 100755
--- a/include/opencv2/core/hal/msa_macros.h
+++ b/include/opencv2/core/hal/msa_macros.h
@@ -50,7 +50,7 @@ typedef double v1f64 __attribute__ ((vector_size(8), aligned(8)));
#define msa_ld1q_f32(__a) ((v4f32)__builtin_msa_ld_w(__a, 0))
#define msa_ld1q_f64(__a) ((v2f64)__builtin_msa_ld_d(__a, 0))
-/* Store 64bits vector elments values to the given memory address. */
+/* Store 64bits vector elements values to the given memory address. */
#define msa_st1_s8(__a, __b) (*((v8i8*)(__a)) = __b)
#define msa_st1_s16(__a, __b) (*((v4i16*)(__a)) = __b)
#define msa_st1_s32(__a, __b) (*((v2i32*)(__a)) = __b)
@@ -377,7 +377,7 @@ typedef double v1f64 __attribute__ ((vector_size(8), aligned(8)));
})
/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector.
- Input is signed and outpus is unsigned. */
+ Input is signed and output is unsigned. */
#define msa_qrshrun_n_s16(__a, __b) \
({ \
v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__b)); \
diff --git a/include/opencv2/core/mat.hpp b/include/opencv2/core/mat.hpp
index adabeca..98f451c 100755
--- a/include/opencv2/core/mat.hpp
+++ b/include/opencv2/core/mat.hpp
@@ -53,7 +53,9 @@
#include "opencv2/core/bufferpool.hpp"
+#ifdef CV_CXX11
#include <type_traits>
+#endif
namespace cv
{
@@ -61,10 +63,8 @@ namespace cv
//! @addtogroup core_basic
//! @{
-enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
+enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
-CV_ENUM_FLAGS(AccessFlag)
-__CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag)
CV__DEBUG_NS_BEGIN
@@ -158,7 +158,7 @@ Custom type is wrapped as Mat-compatible `CV_8UC<N>` values (N = sizeof(T), N <=
class CV_EXPORTS _InputArray
{
public:
- enum KindFlag {
+ enum {
KIND_SHIFT = 16,
FIXED_TYPE = 0x8000 << KIND_SHIFT,
FIXED_SIZE = 0x4000 << KIND_SHIFT,
@@ -170,7 +170,7 @@ public:
STD_VECTOR = 3 << KIND_SHIFT,
STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
STD_VECTOR_MAT = 5 << KIND_SHIFT,
- EXPR = 6 << KIND_SHIFT,
+ EXPR = 6 << KIND_SHIFT, //!< removed
OPENGL_BUFFER = 7 << KIND_SHIFT,
CUDA_HOST_MEM = 8 << KIND_SHIFT,
CUDA_GPU_MAT = 9 << KIND_SHIFT,
@@ -191,7 +191,7 @@ public:
template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
_InputArray(const std::vector<bool>& vec);
template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
- _InputArray(const std::vector<std::vector<bool> >&) = delete; // not supported
+ _InputArray(const std::vector<std::vector<bool> >&);
template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputArray(const _Tp* vec, int n);
template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
@@ -204,11 +204,15 @@ public:
_InputArray(const UMat& um);
_InputArray(const std::vector<UMat>& umv);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _InputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _InputArray(const std::array<Mat, _Nm>& arr);
+#endif
template<typename _Tp> static _InputArray rawIn(const std::vector<_Tp>& vec);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> static _InputArray rawIn(const std::array<_Tp, _Nm>& arr);
+#endif
Mat getMat(int idx=-1) const;
Mat getMat_(int idx=-1) const;
@@ -223,7 +227,7 @@ public:
void* getObj() const;
Size getSz() const;
- _InputArray::KindFlag kind() const;
+ int kind() const;
int dims(int i=-1) const;
int cols(int i=-1) const;
int rows(int i=-1) const;
@@ -259,8 +263,7 @@ protected:
void init(int _flags, const void* _obj);
void init(int _flags, const void* _obj, Size _sz);
};
-CV_ENUM_FLAGS(_InputArray::KindFlag)
-__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag)
+
/** @brief This type is very similar to InputArray except that it is used for input/output and output function
parameters.
@@ -290,7 +293,7 @@ generators:
class CV_EXPORTS _OutputArray : public _InputArray
{
public:
- enum DepthMask
+ enum
{
DEPTH_MASK_8U = 1 << CV_8U,
DEPTH_MASK_8S = 1 << CV_8S,
@@ -299,10 +302,8 @@ public:
DEPTH_MASK_32S = 1 << CV_32S,
DEPTH_MASK_32F = 1 << CV_32F,
DEPTH_MASK_64F = 1 << CV_64F,
- DEPTH_MASK_16F = 1 << CV_16F,
DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
- DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1,
DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
};
@@ -316,9 +317,9 @@ public:
_OutputArray(cuda::HostMem& cuda_mem);
template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
- _OutputArray(std::vector<bool>& vec) = delete; // not supported
+ _OutputArray(std::vector<bool>& vec);
template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
- _OutputArray(std::vector<std::vector<bool> >&) = delete; // not supported
+ _OutputArray(std::vector<std::vector<bool> >&);
template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
template<typename _Tp> _OutputArray(_Tp* vec, int n);
@@ -342,13 +343,17 @@ public:
_OutputArray(const UMat& m);
_OutputArray(const std::vector<UMat>& vec);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _OutputArray(std::array<_Tp, _Nm>& arr);
template<typename _Tp, std::size_t _Nm> _OutputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _OutputArray(std::array<Mat, _Nm>& arr);
template<std::size_t _Nm> _OutputArray(const std::array<Mat, _Nm>& arr);
+#endif
template<typename _Tp> static _OutputArray rawOut(std::vector<_Tp>& vec);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> static _OutputArray rawOut(std::array<_Tp, _Nm>& arr);
+#endif
bool fixedSize() const;
bool fixedType() const;
@@ -359,9 +364,9 @@ public:
std::vector<cuda::GpuMat>& getGpuMatVecRef() const;
ogl::Buffer& getOGlBufferRef() const;
cuda::HostMem& getHostMemRef() const;
- void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
- void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
- void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const;
+ void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
+ void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
+ void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
void createSameSize(const _InputArray& arr, int mtype) const;
void release() const;
void clear() const;
@@ -390,7 +395,7 @@ public:
_InputOutputArray(cuda::HostMem& cuda_mem);
template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
- _InputOutputArray(std::vector<bool>& vec) = delete; // not supported
+ _InputOutputArray(std::vector<bool>& vec);
template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
@@ -415,13 +420,17 @@ public:
_InputOutputArray(const UMat& m);
_InputOutputArray(const std::vector<UMat>& vec);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _InputOutputArray(std::array<_Tp, _Nm>& arr);
template<typename _Tp, std::size_t _Nm> _InputOutputArray(const std::array<_Tp, _Nm>& arr);
template<std::size_t _Nm> _InputOutputArray(std::array<Mat, _Nm>& arr);
template<std::size_t _Nm> _InputOutputArray(const std::array<Mat, _Nm>& arr);
+#endif
template<typename _Tp> static _InputOutputArray rawInOut(std::vector<_Tp>& vec);
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr);
+#endif
};
@@ -473,10 +482,10 @@ public:
// uchar*& datastart, uchar*& data, size_t* step) = 0;
//virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
virtual UMatData* allocate(int dims, const int* sizes, int type,
- void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0;
- virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0;
+ void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
+ virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
virtual void deallocate(UMatData* data) const = 0;
- virtual void map(UMatData* data, AccessFlag accessflags) const;
+ virtual void map(UMatData* data, int accessflags) const;
virtual void unmap(UMatData* data) const;
virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
@@ -529,7 +538,7 @@ protected:
// it should be explicitly initialized using init().
struct CV_EXPORTS UMatData
{
- enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
+ enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64,
ASYNC_CLEANUP=128
@@ -559,14 +568,13 @@ struct CV_EXPORTS UMatData
uchar* origdata;
size_t size;
- UMatData::MemoryFlag flags;
+ int flags;
void* handle;
void* userdata;
int allocatorFlags_;
int mapcount;
UMatData* originalUMatData;
};
-CV_ENUM_FLAGS(UMatData::MemoryFlag)
struct CV_EXPORTS MatSize
@@ -617,11 +625,12 @@ Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[
that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane,
and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .
-So, the data layout in Mat is compatible with the majority of dense array types from the standard
-toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others,
-that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel.
-Due to this compatibility, it is possible to make a Mat header for user-allocated data and process
-it in-place using OpenCV functions.
+So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV
+1.x. It is also compatible with the majority of dense array types from the standard toolkits and
+SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any
+array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this
+compatibility, it is possible to make a Mat header for user-allocated data and process it in-place
+using OpenCV functions.
There are many different ways to create a Mat object. The most popular options are listed below:
@@ -693,11 +702,16 @@ sub-matrices.
-# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or
a processing module for gstreamer, and so on). For example:
@code
- void process_video_frame(const unsigned char* pixels,
- int width, int height, int step)
+ Mat process_video_frame(const unsigned char* pixels,
+ int width, int height, int step)
{
- Mat img(height, width, CV_8UC3, pixels, step);
- GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
+ // wrap input buffer
+ Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step);
+
+ Mat result;
+ GaussianBlur(img, result, Size(7, 7), 1.5, 1.5);
+
+ return result;
}
@endcode
-# Quickly initialize small matrices and/or get a super-fast element access.
@@ -706,6 +720,10 @@ sub-matrices.
Mat M = Mat(3, 3, CV_64F, m).inv();
@endcode
.
+ Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and
+ IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or
+ IplImage and the optional flag indicating whether to copy the data or not.
+ @snippet samples/cpp/image.cpp iplimage
- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
@code
@@ -1004,6 +1022,7 @@ public:
*/
template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
+#ifdef CV_CXX11
/** @overload
*/
template<typename _Tp, typename = typename std::enable_if<std::is_arithmetic<_Tp>::value>::type>
@@ -1012,10 +1031,13 @@ public:
/** @overload
*/
template<typename _Tp> explicit Mat(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> list);
+#endif
+#ifdef CV_CXX_STD_ARRAY
/** @overload
*/
template<typename _Tp, size_t _Nm> explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false);
+#endif
/** @overload
*/
@@ -1063,7 +1085,7 @@ public:
Mat& operator = (const MatExpr& expr);
//! retrieve UMat from Mat
- UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
+ UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
/** @brief Creates a matrix header for the specified matrix row.
@@ -1639,11 +1661,20 @@ public:
*/
Mat operator()(const std::vector<Range>& ranges) const;
+ // //! converts header to CvMat; no data is copied
+ // operator CvMat() const;
+ // //! converts header to CvMatND; no data is copied
+ // operator CvMatND() const;
+ // //! converts header to IplImage; no data is copied
+ // operator IplImage() const;
+
template<typename _Tp> operator std::vector<_Tp>() const;
template<typename _Tp, int n> operator Vec<_Tp, n>() const;
template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
+#endif
/** @brief Reports whether the matrix is continuous or not.
@@ -2067,8 +2098,10 @@ public:
/** @overload */
template<typename _Tp, typename Functor> void forEach(const Functor& operation) const;
+#ifdef CV_CXX_MOVE_SEMANTICS
Mat(Mat&& m);
Mat& operator = (Mat&& m);
+#endif
enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
@@ -2222,10 +2255,14 @@ public:
explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
+#ifdef CV_CXX11
Mat_(std::initializer_list<_Tp> values);
explicit Mat_(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> values);
+#endif
+#ifdef CV_CXX_STD_ARRAY
template <std::size_t _Nm> explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false);
+#endif
Mat_& operator = (const Mat& m);
Mat_& operator = (const Mat_& m);
@@ -2323,14 +2360,17 @@ public:
//! conversion to vector.
operator std::vector<_Tp>() const;
+#ifdef CV_CXX_STD_ARRAY
//! conversion to array.
template<std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
+#endif
//! conversion to Vec
template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
//! conversion to Matx
template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
+#ifdef CV_CXX_MOVE_SEMANTICS
Mat_(Mat_&& m);
Mat_& operator = (Mat_&& m);
@@ -2338,6 +2378,7 @@ public:
Mat_& operator = (Mat&& m);
Mat_(MatExpr&& e);
+#endif
};
typedef Mat_<uchar> Mat1b;
@@ -2396,26 +2437,17 @@ public:
UMat(const UMat& m, const Rect& roi);
UMat(const UMat& m, const Range* ranges);
UMat(const UMat& m, const std::vector<Range>& ranges);
+
+ // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0)
//! builds matrix from std::vector with or without copying the data
template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
- //! builds matrix from cv::Vec; the data is copied by default
- template<typename _Tp, int n> explicit UMat(const Vec<_Tp, n>& vec, bool copyData=true);
- //! builds matrix from cv::Matx; the data is copied by default
- template<typename _Tp, int m, int n> explicit UMat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
- //! builds matrix from a 2D point
- template<typename _Tp> explicit UMat(const Point_<_Tp>& pt, bool copyData=true);
- //! builds matrix from a 3D point
- template<typename _Tp> explicit UMat(const Point3_<_Tp>& pt, bool copyData=true);
- //! builds matrix from comma initializer
- template<typename _Tp> explicit UMat(const MatCommaInitializer_<_Tp>& commaInitializer);
-
//! destructor - calls release()
~UMat();
//! assignment operators
UMat& operator = (const UMat& m);
- Mat getMat(AccessFlag flags) const;
+ Mat getMat(int flags) const;
//! returns a new matrix header for the specified row
UMat row(int y) const;
@@ -2534,14 +2566,16 @@ public:
//! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
+#ifdef CV_CXX_MOVE_SEMANTICS
UMat(UMat&& m);
UMat& operator = (UMat&& m);
+#endif
/*! Returns the OpenCL buffer handle on which UMat operates on.
The UMat instance should be kept alive during the use of the handle to prevent the buffer to be
returned to the OpenCV buffer pool.
*/
- void* handle(AccessFlag accessFlags) const;
+ void* handle(int accessFlags) const;
void ndoffset(size_t* ofs) const;
enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
@@ -3542,6 +3576,8 @@ public:
Mat cross(const Mat& m) const;
double dot(const Mat& m) const;
+ void swap(MatExpr& b);
+
const MatOp* op;
int flags;
diff --git a/include/opencv2/core/mat.inl.hpp b/include/opencv2/core/mat.inl.hpp
index 44628fa..b6ffd81 100755
--- a/include/opencv2/core/mat.inl.hpp
+++ b/include/opencv2/core/mat.inl.hpp
@@ -54,6 +54,21 @@
#pragma warning( disable: 4127 )
#endif
+#if defined(CV_SKIP_DISABLE_CLANG_ENUM_WARNINGS)
+ // nothing
+#elif defined(CV_FORCE_DISABLE_CLANG_ENUM_WARNINGS)
+ #define CV_DISABLE_CLANG_ENUM_WARNINGS
+#elif defined(__clang__) && defined(__has_warning)
+ #if __has_warning("-Wdeprecated-enum-enum-conversion") && __has_warning("-Wdeprecated-anon-enum-enum-conversion")
+ #define CV_DISABLE_CLANG_ENUM_WARNINGS
+ #endif
+#endif
+#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"
+#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion"
+#endif
+
namespace cv
{
CV__DEBUG_NS_BEGIN
@@ -83,7 +98,7 @@ inline void* _InputArray::getObj() const { return obj; }
inline int _InputArray::getFlags() const { return flags; }
inline Size _InputArray::getSz() const { return sz; }
-inline _InputArray::_InputArray() { init(0 + NONE, 0); }
+inline _InputArray::_InputArray() { init(NONE, 0); }
inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); }
inline _InputArray::_InputArray(const Mat& m) { init(MAT+ACCESS_READ, &m); }
inline _InputArray::_InputArray(const std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_READ, &vec); }
@@ -94,6 +109,7 @@ template<typename _Tp> inline
_InputArray::_InputArray(const std::vector<_Tp>& vec)
{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); }
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_InputArray::_InputArray(const std::array<_Tp, _Nm>& arr)
{ init(FIXED_TYPE + FIXED_SIZE + STD_ARRAY + traits::Type<_Tp>::value + ACCESS_READ, arr.data(), Size(1, _Nm)); }
@@ -101,6 +117,7 @@ _InputArray::_InputArray(const std::array<_Tp, _Nm>& arr)
template<std::size_t _Nm> inline
_InputArray::_InputArray(const std::array<Mat, _Nm>& arr)
{ init(STD_ARRAY_MAT + ACCESS_READ, arr.data(), Size(1, _Nm)); }
+#endif
inline
_InputArray::_InputArray(const std::vector<bool>& vec)
@@ -110,6 +127,10 @@ template<typename _Tp> inline
_InputArray::_InputArray(const std::vector<std::vector<_Tp> >& vec)
{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); }
+inline
+_InputArray::_InputArray(const std::vector<std::vector<bool> >&)
+{ CV_Error(Error::StsUnsupportedFormat, "std::vector<std::vector<bool> > is not supported!\n"); }
+
template<typename _Tp> inline
_InputArray::_InputArray(const std::vector<Mat_<_Tp> >& vec)
{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_READ, &vec); }
@@ -129,9 +150,6 @@ _InputArray::_InputArray(const Mat_<_Tp>& m)
inline _InputArray::_InputArray(const double& val)
{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); }
-inline _InputArray::_InputArray(const MatExpr& expr)
-{ init(FIXED_TYPE + FIXED_SIZE + EXPR + ACCESS_READ, &expr); }
-
inline _InputArray::_InputArray(const cuda::GpuMat& d_mat)
{ init(CUDA_GPU_MAT + ACCESS_READ, &d_mat); }
@@ -153,6 +171,7 @@ _InputArray _InputArray::rawIn(const std::vector<_Tp>& vec)
return v;
}
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr)
{
@@ -162,6 +181,7 @@ _InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr)
v.sz = Size(1, _Nm);
return v;
}
+#endif
inline _InputArray::~_InputArray() {}
@@ -185,17 +205,18 @@ inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::
////////////////////////////////////////////////////////////////////////////////////////
-inline _OutputArray::_OutputArray() { init(NONE + ACCESS_WRITE, 0); }
-inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags + ACCESS_WRITE, _obj); }
+inline _OutputArray::_OutputArray() { init(ACCESS_WRITE, 0); }
+inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags|ACCESS_WRITE, _obj); }
inline _OutputArray::_OutputArray(Mat& m) { init(MAT+ACCESS_WRITE, &m); }
-inline _OutputArray::_OutputArray(std::vector<Mat>& vec) { init(STD_VECTOR_MAT + ACCESS_WRITE, &vec); }
-inline _OutputArray::_OutputArray(UMat& m) { init(UMAT + ACCESS_WRITE, &m); }
-inline _OutputArray::_OutputArray(std::vector<UMat>& vec) { init(STD_VECTOR_UMAT + ACCESS_WRITE, &vec); }
+inline _OutputArray::_OutputArray(std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_WRITE, &vec); }
+inline _OutputArray::_OutputArray(UMat& m) { init(UMAT+ACCESS_WRITE, &m); }
+inline _OutputArray::_OutputArray(std::vector<UMat>& vec) { init(STD_VECTOR_UMAT+ACCESS_WRITE, &vec); }
template<typename _Tp> inline
_OutputArray::_OutputArray(std::vector<_Tp>& vec)
{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); }
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr)
{ init(FIXED_TYPE + FIXED_SIZE + STD_ARRAY + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); }
@@ -203,11 +224,20 @@ _OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr)
template<std::size_t _Nm> inline
_OutputArray::_OutputArray(std::array<Mat, _Nm>& arr)
{ init(STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); }
+#endif
+
+inline
+_OutputArray::_OutputArray(std::vector<bool>&)
+{ CV_Error(Error::StsUnsupportedFormat, "std::vector<bool> cannot be an output array\n"); }
template<typename _Tp> inline
_OutputArray::_OutputArray(std::vector<std::vector<_Tp> >& vec)
{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); }
+inline
+_OutputArray::_OutputArray(std::vector<std::vector<bool> >&)
+{ CV_Error(Error::StsUnsupportedFormat, "std::vector<std::vector<bool> > cannot be an output array\n"); }
+
template<typename _Tp> inline
_OutputArray::_OutputArray(std::vector<Mat_<_Tp> >& vec)
{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); }
@@ -228,6 +258,7 @@ template<typename _Tp> inline
_OutputArray::_OutputArray(const std::vector<_Tp>& vec)
{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); }
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr)
{ init(FIXED_TYPE + FIXED_SIZE + STD_ARRAY + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); }
@@ -235,6 +266,7 @@ _OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr)
template<std::size_t _Nm> inline
_OutputArray::_OutputArray(const std::array<Mat, _Nm>& arr)
{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); }
+#endif
template<typename _Tp> inline
_OutputArray::_OutputArray(const std::vector<std::vector<_Tp> >& vec)
@@ -299,6 +331,7 @@ _OutputArray _OutputArray::rawOut(std::vector<_Tp>& vec)
return v;
}
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr)
{
@@ -308,11 +341,12 @@ _OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr)
v.sz = Size(1, _Nm);
return v;
}
+#endif
///////////////////////////////////////////////////////////////////////////////////////////
-inline _InputOutputArray::_InputOutputArray() { init(0+ACCESS_RW, 0); }
-inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags+ACCESS_RW, _obj); }
+inline _InputOutputArray::_InputOutputArray() { init(ACCESS_RW, 0); }
+inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags|ACCESS_RW, _obj); }
inline _InputOutputArray::_InputOutputArray(Mat& m) { init(MAT+ACCESS_RW, &m); }
inline _InputOutputArray::_InputOutputArray(std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_RW, &vec); }
inline _InputOutputArray::_InputOutputArray(UMat& m) { init(UMAT+ACCESS_RW, &m); }
@@ -322,6 +356,7 @@ template<typename _Tp> inline
_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec)
{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); }
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr)
{ init(FIXED_TYPE + FIXED_SIZE + STD_ARRAY + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); }
@@ -329,6 +364,10 @@ _InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr)
template<std::size_t _Nm> inline
_InputOutputArray::_InputOutputArray(std::array<Mat, _Nm>& arr)
{ init(STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); }
+#endif
+
+inline _InputOutputArray::_InputOutputArray(std::vector<bool>&)
+{ CV_Error(Error::StsUnsupportedFormat, "std::vector<bool> cannot be an input/output array\n"); }
template<typename _Tp> inline
_InputOutputArray::_InputOutputArray(std::vector<std::vector<_Tp> >& vec)
@@ -354,6 +393,7 @@ template<typename _Tp> inline
_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec)
{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); }
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr)
{ init(FIXED_TYPE + FIXED_SIZE + STD_ARRAY + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); }
@@ -361,6 +401,7 @@ _InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr)
template<std::size_t _Nm> inline
_InputOutputArray::_InputOutputArray(const std::array<Mat, _Nm>& arr)
{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); }
+#endif
template<typename _Tp> inline
_InputOutputArray::_InputOutputArray(const std::vector<std::vector<_Tp> >& vec)
@@ -427,6 +468,7 @@ _InputOutputArray _InputOutputArray::rawInOut(std::vector<_Tp>& vec)
return v;
}
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
_InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr)
{
@@ -436,6 +478,7 @@ _InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr)
v.sz = Size(1, _Nm);
return v;
}
+#endif
template<typename _Tp> static inline _InputArray rawIn(_Tp& v) { return _InputArray::rawIn(v); }
@@ -446,161 +489,9 @@ CV__DEBUG_NS_END
//////////////////////////////////////////// Mat //////////////////////////////////////////
-inline
-Mat::Mat()
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{}
-
-inline
-Mat::Mat(int _rows, int _cols, int _type)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_rows, _cols, _type);
-}
-
-inline
-Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_rows, _cols, _type);
- *this = _s;
-}
-
-inline
-Mat::Mat(Size _sz, int _type)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create( _sz.height, _sz.width, _type );
-}
-
-inline
-Mat::Mat(Size _sz, int _type, const Scalar& _s)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_sz.height, _sz.width, _type);
- *this = _s;
-}
-
-inline
-Mat::Mat(int _dims, const int* _sz, int _type)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_dims, _sz, _type);
-}
-
-inline
-Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_dims, _sz, _type);
- *this = _s;
-}
-
-inline
-Mat::Mat(const std::vector<int>& _sz, int _type)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_sz, _type);
-}
-
-inline
-Mat::Mat(const std::vector<int>& _sz, int _type, const Scalar& _s)
- : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
- datalimit(0), allocator(0), u(0), size(&rows), step(0)
-{
- create(_sz, _type);
- *this = _s;
-}
-
-inline
-Mat::Mat(const Mat& m)
- : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data),
- datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator),
- u(m.u), size(&rows), step(0)
-{
- if( u )
- CV_XADD(&u->refcount, 1);
- if( m.dims <= 2 )
- {
- step[0] = m.step[0]; step[1] = m.step[1];
- }
- else
- {
- dims = 0;
- copySize(m);
- }
-}
-
-inline
-Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step)
- : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_rows), cols(_cols),
- data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0),
- allocator(0), u(0), size(&rows)
-{
- CV_Assert(total() == 0 || data != NULL);
-
- size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type);
- size_t minstep = cols * esz;
- if( _step == AUTO_STEP )
- {
- _step = minstep;
- }
- else
- {
- CV_DbgAssert( _step >= minstep );
- if (_step % esz1 != 0)
- {
- CV_Error(Error::BadStep, "Step must be a multiple of esz1");
- }
- }
- step[0] = _step;
- step[1] = esz;
- datalimit = datastart + _step * rows;
- dataend = datalimit - _step + minstep;
- updateContinuityFlag();
-}
-
-inline
-Mat::Mat(Size _sz, int _type, void* _data, size_t _step)
- : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_sz.height), cols(_sz.width),
- data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0),
- allocator(0), u(0), size(&rows)
-{
- CV_Assert(total() == 0 || data != NULL);
-
- size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type);
- size_t minstep = cols*esz;
- if( _step == AUTO_STEP )
- {
- _step = minstep;
- }
- else
- {
- CV_DbgAssert( _step >= minstep );
-
- if (_step % esz1 != 0)
- {
- CV_Error(Error::BadStep, "Step must be a multiple of esz1");
- }
- }
- step[0] = _step;
- step[1] = esz;
- datalimit = datastart + _step*rows;
- dataend = datalimit - _step + minstep;
- updateContinuityFlag();
-}
-
template<typename _Tp> inline
Mat::Mat(const std::vector<_Tp>& vec, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()),
cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if(vec.empty())
@@ -615,6 +506,7 @@ Mat::Mat(const std::vector<_Tp>& vec, bool copyData)
Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this);
}
+#ifdef CV_CXX11
template<typename _Tp, typename> inline
Mat::Mat(const std::initializer_list<_Tp> list)
: Mat()
@@ -634,10 +526,12 @@ Mat::Mat(const std::initializer_list<int> sizes, const std::initializer_list<_Tp
CV_Assert(size_total == list.size());
Mat((int)sizes.size(), (int*)sizes.begin(), traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this);
}
+#endif
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()),
cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if(arr.empty())
@@ -651,10 +545,11 @@ Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData)
else
Mat((int)arr.size(), 1, traits::Type<_Tp>::value, (uchar*)arr.data()).copyTo(*this);
}
+#endif
template<typename _Tp, int n> inline
Mat::Mat(const Vec<_Tp, n>& vec, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0),
datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if( !copyData )
@@ -670,7 +565,7 @@ Mat::Mat(const Vec<_Tp, n>& vec, bool copyData)
template<typename _Tp, int m, int n> inline
Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0),
datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if( !copyData )
@@ -686,7 +581,7 @@ Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData)
template<typename _Tp> inline
Mat::Mat(const Point_<_Tp>& pt, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0),
datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if( !copyData )
@@ -705,7 +600,7 @@ Mat::Mat(const Point_<_Tp>& pt, bool copyData)
template<typename _Tp> inline
Mat::Mat(const Point3_<_Tp>& pt, bool copyData)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0),
datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
if( !copyData )
@@ -725,49 +620,12 @@ Mat::Mat(const Point3_<_Tp>& pt, bool copyData)
template<typename _Tp> inline
Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer)
- : flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0),
+ : flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0),
datastart(0), dataend(0), allocator(0), u(0), size(&rows)
{
*this = commaInitializer.operator Mat_<_Tp>();
}
-inline
-Mat::~Mat()
-{
- release();
- if( step.p != step.buf )
- fastFree(step.p);
-}
-
-inline
-Mat& Mat::operator = (const Mat& m)
-{
- if( this != &m )
- {
- if( m.u )
- CV_XADD(&m.u->refcount, 1);
- release();
- flags = m.flags;
- if( dims <= 2 && m.dims <= 2 )
- {
- dims = m.dims;
- rows = m.rows;
- cols = m.cols;
- step[0] = m.step[0];
- step[1] = m.step[1];
- }
- else
- copySize(m);
- data = m.data;
- datastart = m.datastart;
- dataend = m.dataend;
- datalimit = m.datalimit;
- allocator = m.allocator;
- u = m.u;
- }
- return *this;
-}
-
inline
Mat Mat::row(int y) const
{
@@ -804,67 +662,6 @@ Mat Mat::colRange(const Range& r) const
return Mat(*this, Range::all(), r);
}
-inline
-Mat Mat::clone() const
-{
- Mat m;
- copyTo(m);
- return m;
-}
-
-inline
-void Mat::assignTo( Mat& m, int _type ) const
-{
- if( _type < 0 )
- m = *this;
- else
- convertTo(m, _type);
-}
-
-inline
-void Mat::create(int _rows, int _cols, int _type)
-{
- _type &= TYPE_MASK;
- if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data )
- return;
- int sz[] = {_rows, _cols};
- create(2, sz, _type);
-}
-
-inline
-void Mat::create(Size _sz, int _type)
-{
- create(_sz.height, _sz.width, _type);
-}
-
-inline
-void Mat::addref()
-{
- if( u )
- CV_XADD(&u->refcount, 1);
-}
-
-inline
-void Mat::release()
-{
- if( u && CV_XADD(&u->refcount, -1) == 1 )
- deallocate();
- u = NULL;
- datastart = dataend = datalimit = data = 0;
- for(int i = 0; i < dims; i++)
- size.p[i] = 0;
-#ifdef _DEBUG
- flags = MAGIC_VAL;
- dims = rows = cols = 0;
- if(step.p != step.buf)
- {
- fastFree(step.p);
- step.p = step.buf;
- size.p = &rows;
- }
-#endif
-}
-
inline
Mat Mat::operator()( Range _rowRange, Range _colRange ) const
{
@@ -933,40 +730,6 @@ int Mat::channels() const
return CV_MAT_CN(flags);
}
-inline
-size_t Mat::step1(int i) const
-{
- return step.p[i] / elemSize1();
-}
-
-inline
-bool Mat::empty() const
-{
- return data == 0 || total() == 0 || dims == 0;
-}
-
-inline
-size_t Mat::total() const
-{
- if( dims <= 2 )
- return (size_t)rows * cols;
- size_t p = 1;
- for( int i = 0; i < dims; i++ )
- p *= size[i];
- return p;
-}
-
-inline
-size_t Mat::total(int startDim, int endDim) const
-{
- CV_Assert( 0 <= startDim && startDim <= endDim);
- size_t p = 1;
- int endDim_ = endDim <= dims ? endDim : dims;
- for( int i = startDim; i < endDim_; i++ )
- p *= size[i];
- return p;
-}
-
inline
uchar* Mat::ptr(int y)
{
@@ -1254,6 +1017,8 @@ const _Tp& Mat::at(const Vec<int, n>& idx) const
template<typename _Tp> inline
MatConstIterator_<_Tp> Mat::begin() const
{
+ if (empty())
+ return MatConstIterator_<_Tp>();
CV_DbgAssert( elemSize() == sizeof(_Tp) );
return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this);
}
@@ -1261,6 +1026,8 @@ MatConstIterator_<_Tp> Mat::begin() const
template<typename _Tp> inline
MatConstIterator_<_Tp> Mat::end() const
{
+ if (empty())
+ return MatConstIterator_<_Tp>();
CV_DbgAssert( elemSize() == sizeof(_Tp) );
MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this);
it += total();
@@ -1270,6 +1037,8 @@ MatConstIterator_<_Tp> Mat::end() const
template<typename _Tp> inline
MatIterator_<_Tp> Mat::begin()
{
+ if (empty())
+ return MatIterator_<_Tp>();
CV_DbgAssert( elemSize() == sizeof(_Tp) );
return MatIterator_<_Tp>((Mat_<_Tp>*)this);
}
@@ -1277,6 +1046,8 @@ MatIterator_<_Tp> Mat::begin()
template<typename _Tp> inline
MatIterator_<_Tp> Mat::end()
{
+ if (empty())
+ return MatIterator_<_Tp>();
CV_DbgAssert( elemSize() == sizeof(_Tp) );
MatIterator_<_Tp> it((Mat_<_Tp>*)this);
it += total();
@@ -1302,6 +1073,7 @@ Mat::operator std::vector<_Tp>() const
return v;
}
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp, std::size_t _Nm> inline
Mat::operator std::array<_Tp, _Nm>() const
{
@@ -1309,6 +1081,7 @@ Mat::operator std::array<_Tp, _Nm>() const
copyTo(v);
return v;
}
+#endif
template<typename _Tp, int n> inline
Mat::operator Vec<_Tp, n>() const
@@ -1376,6 +1149,8 @@ void Mat::push_back(const std::vector<_Tp>& v)
push_back(Mat(v));
}
+#ifdef CV_CXX_MOVE_SEMANTICS
+
inline
Mat::Mat(Mat&& m)
: flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data),
@@ -1437,6 +1212,8 @@ Mat& Mat::operator = (Mat&& m)
return *this;
}
+#endif
+
///////////////////////////// MatSize ////////////////////////////
@@ -1483,22 +1260,6 @@ MatSize::operator const int*() const
return p;
}
-inline
-bool MatSize::operator == (const MatSize& sz) const
-{
- int d = dims();
- int dsz = sz.dims();
- if( d != dsz )
- return false;
- if( d == 2 )
- return p[0] == sz.p[0] && p[1] == sz.p[1];
-
- for( int i = 0; i < d; i++ )
- if( p[i] != sz.p[i] )
- return false;
- return true;
-}
-
inline
bool MatSize::operator != (const MatSize& sz) const
{
@@ -1554,7 +1315,7 @@ template<typename _Tp> inline
Mat_<_Tp>::Mat_()
: Mat()
{
- flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value;
+ flags = (flags & ~CV_MAT_TYPE_MASK) | traits::Type<_Tp>::value;
}
template<typename _Tp> inline
@@ -1611,7 +1372,7 @@ template<typename _Tp> inline
Mat_<_Tp>::Mat_(const Mat& m)
: Mat()
{
- flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value;
+ flags = (flags & ~CV_MAT_TYPE_MASK) | traits::Type<_Tp>::value;
*this = m;
}
@@ -1681,6 +1442,7 @@ Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData)
: Mat(vec, copyData)
{}
+#ifdef CV_CXX11
template<typename _Tp> inline
Mat_<_Tp>::Mat_(std::initializer_list<_Tp> list)
: Mat(list)
@@ -1690,11 +1452,14 @@ template<typename _Tp> inline
Mat_<_Tp>::Mat_(const std::initializer_list<int> sizes, std::initializer_list<_Tp> list)
: Mat(sizes, list)
{}
+#endif
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp> template<std::size_t _Nm> inline
Mat_<_Tp>::Mat_(const std::array<_Tp, _Nm>& arr, bool copyData)
: Mat(arr, copyData)
{}
+#endif
template<typename _Tp> inline
Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m)
@@ -1755,9 +1520,7 @@ template<typename _Tp> inline
void Mat_<_Tp>::release()
{
Mat::release();
-#ifdef _DEBUG
- flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value;
-#endif
+ flags = (flags & ~CV_MAT_TYPE_MASK) | traits::Type<_Tp>::value;
}
template<typename _Tp> inline
@@ -1987,6 +1750,7 @@ Mat_<_Tp>::operator std::vector<_Tp>() const
return v;
}
+#ifdef CV_CXX_STD_ARRAY
template<typename _Tp> template<std::size_t _Nm> inline
Mat_<_Tp>::operator std::array<_Tp, _Nm>() const
{
@@ -1994,6 +1758,7 @@ Mat_<_Tp>::operator std::array<_Tp, _Nm>() const
copyTo(a);
return a;
}
+#endif
template<typename _Tp> template<int n> inline
Mat_<_Tp>::operator Vec<typename DataType<_Tp>::channel_type, n>() const
@@ -2057,6 +1822,8 @@ void Mat_<_Tp>::forEach(const Functor& operation) const {
Mat::forEach<_Tp, Functor>(operation);
}
+#ifdef CV_CXX_MOVE_SEMANTICS
+
template<typename _Tp> inline
Mat_<_Tp>::Mat_(Mat_&& m)
: Mat(std::move(m))
@@ -2074,7 +1841,7 @@ template<typename _Tp> inline
Mat_<_Tp>::Mat_(Mat&& m)
: Mat()
{
- flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value;
+ flags = (flags & ~CV_MAT_TYPE_MASK) | traits::Type<_Tp>::value;
*this = std::move(m);
}
@@ -2105,58 +1872,14 @@ template<typename _Tp> inline
Mat_<_Tp>::Mat_(MatExpr&& e)
: Mat()
{
- flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value;
+ flags = (flags & ~CV_MAT_TYPE_MASK) | traits::Type<_Tp>::value;
*this = Mat(e);
}
+#endif
///////////////////////////// SparseMat /////////////////////////////
-inline
-SparseMat::SparseMat()
- : flags(MAGIC_VAL), hdr(0)
-{}
-
-inline
-SparseMat::SparseMat(int _dims, const int* _sizes, int _type)
- : flags(MAGIC_VAL), hdr(0)
-{
- create(_dims, _sizes, _type);
-}
-
-inline
-SparseMat::SparseMat(const SparseMat& m)
- : flags(m.flags), hdr(m.hdr)
-{
- addref();
-}
-
-inline
-SparseMat::~SparseMat()
-{
- release();
-}
-
-inline
-SparseMat& SparseMat::operator = (const SparseMat& m)
-{
- if( this != &m )
- {
- if( m.hdr )
- CV_XADD(&m.hdr->refcount, 1);
- release();
- flags = m.flags;
- hdr = m.hdr;
- }
- return *this;
-}
-
-inline
-SparseMat& SparseMat::operator = (const Mat& m)
-{
- return (*this = SparseMat(m));
-}
-
inline
SparseMat SparseMat::clone() const
{
@@ -2165,30 +1888,6 @@ SparseMat SparseMat::clone() const
return temp;
}
-inline
-void SparseMat::assignTo( SparseMat& m, int _type ) const
-{
- if( _type < 0 )
- m = *this;
- else
- convertTo(m, _type);
-}
-
-inline
-void SparseMat::addref()
-{
- if( hdr )
- CV_XADD(&hdr->refcount, 1);
-}
-
-inline
-void SparseMat::release()
-{
- if( hdr && CV_XADD(&hdr->refcount, -1) == 1 )
- delete hdr;
- hdr = 0;
-}
-
inline
size_t SparseMat::elemSize() const
{
@@ -2248,36 +1947,6 @@ size_t SparseMat::nzcount() const
return hdr ? hdr->nodeCount : 0;
}
-inline
-size_t SparseMat::hash(int i0) const
-{
- return (size_t)i0;
-}
-
-inline
-size_t SparseMat::hash(int i0, int i1) const
-{
- return (size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1;
-}
-
-inline
-size_t SparseMat::hash(int i0, int i1, int i2) const
-{
- return ((size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1) * HASH_SCALE + (unsigned)i2;
-}
-
-inline
-size_t SparseMat::hash(const int* idx) const
-{
- size_t h = (unsigned)idx[0];
- if( !hdr )
- return 0;
- int d = hdr->dims;
- for(int i = 1; i < d; i++ )
- h = h * HASH_SCALE + (unsigned)idx[i];
- return h;
-}
-
template<typename _Tp> inline
_Tp& SparseMat::ref(int i0, size_t* hashval)
{
@@ -2441,7 +2110,7 @@ SparseMatConstIterator_<_Tp> SparseMat::end() const
template<typename _Tp> inline
SparseMat_<_Tp>::SparseMat_()
{
- flags = MAGIC_VAL + traits::Type<_Tp>::value;
+ flags = MAGIC_VAL | traits::Type<_Tp>::value;
}
template<typename _Tp> inline
@@ -2625,6 +2294,7 @@ MatConstIterator::MatConstIterator(const Mat* _m)
{
if( m && m->isContinuous() )
{
+ CV_Assert(!m->empty());
sliceStart = m->ptr();
sliceEnd = sliceStart + m->total()*elemSize;
}
@@ -2638,6 +2308,7 @@ MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col)
CV_Assert(m && m->dims <= 2);
if( m->isContinuous() )
{
+ CV_Assert(!m->empty());
sliceStart = m->ptr();
sliceEnd = sliceStart + m->total()*elemSize;
}
@@ -2652,6 +2323,7 @@ MatConstIterator::MatConstIterator(const Mat* _m, Point _pt)
CV_Assert(m && m->dims <= 2);
if( m->isContinuous() )
{
+ CV_Assert(!m->empty());
sliceStart = m->ptr();
sliceEnd = sliceStart + m->total()*elemSize;
}
@@ -3594,77 +3266,9 @@ const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b)
//////////////////////////////// UMat ////////////////////////////////
-inline
-UMat::UMat(UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{}
-
-inline
-UMat::UMat(int _rows, int _cols, int _type, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create(_rows, _cols, _type);
-}
-
-inline
-UMat::UMat(int _rows, int _cols, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create(_rows, _cols, _type);
- *this = _s;
-}
-
-inline
-UMat::UMat(Size _sz, int _type, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create( _sz.height, _sz.width, _type );
-}
-
-inline
-UMat::UMat(Size _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create(_sz.height, _sz.width, _type);
- *this = _s;
-}
-
-inline
-UMat::UMat(int _dims, const int* _sz, int _type, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create(_dims, _sz, _type);
-}
-
-inline
-UMat::UMat(int _dims, const int* _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
-: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
-{
- create(_dims, _sz, _type);
- *this = _s;
-}
-
-inline
-UMat::UMat(const UMat& m)
-: flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator),
- usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(&rows)
-{
- addref();
- if( m.dims <= 2 )
- {
- step[0] = m.step[0]; step[1] = m.step[1];
- }
- else
- {
- dims = 0;
- copySize(m);
- }
-}
-
-
template<typename _Tp> inline
UMat::UMat(const std::vector<_Tp>& vec, bool copyData)
-: flags(MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()),
+: flags(MAGIC_VAL | traits::Type<_Tp>::value | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()),
cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows)
{
if(vec.empty())
@@ -3678,33 +3282,6 @@ cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows)
Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this);
}
-inline
-UMat& UMat::operator = (const UMat& m)
-{
- if( this != &m )
- {
- const_cast<UMat&>(m).addref();
- release();
- flags = m.flags;
- if( dims <= 2 && m.dims <= 2 )
- {
- dims = m.dims;
- rows = m.rows;
- cols = m.cols;
- step[0] = m.step[0];
- step[1] = m.step[1];
- }
- else
- copySize(m);
- allocator = m.allocator;
- if (usageFlags == USAGE_DEFAULT)
- usageFlags = m.usageFlags;
- u = m.u;
- offset = m.offset;
- }
- return *this;
-}
-
inline
UMat UMat::row(int y) const
{
@@ -3741,55 +3318,6 @@ UMat UMat::colRange(const Range& r) const
return UMat(*this, Range::all(), r);
}
-inline
-UMat UMat::clone() const
-{
- UMat m;
- copyTo(m);
- return m;
-}
-
-inline
-void UMat::assignTo( UMat& m, int _type ) const
-{
- if( _type < 0 )
- m = *this;
- else
- convertTo(m, _type);
-}
-
-inline
-void UMat::create(int _rows, int _cols, int _type, UMatUsageFlags _usageFlags)
-{
- _type &= TYPE_MASK;
- if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && u )
- return;
- int sz[] = {_rows, _cols};
- create(2, sz, _type, _usageFlags);
-}
-
-inline
-void UMat::create(Size _sz, int _type, UMatUsageFlags _usageFlags)
-{
- create(_sz.height, _sz.width, _type, _usageFlags);
-}
-
-inline
-void UMat::addref()
-{
- if( u )
- CV_XADD(&(u->urefcount), 1);
-}
-
-inline void UMat::release()
-{
- if( u && CV_XADD(&(u->urefcount), -1) == 1 )
- deallocate();
- for(int i = 0; i < dims; i++)
- size.p[i] = 0;
- u = 0;
-}
-
inline
UMat UMat::operator()( Range _rowRange, Range _colRange ) const
{
@@ -3864,22 +3392,7 @@ size_t UMat::step1(int i) const
return step.p[i] / elemSize1();
}
-inline
-bool UMat::empty() const
-{
- return u == 0 || total() == 0 || dims == 0;
-}
-
-inline
-size_t UMat::total() const
-{
- if( dims <= 2 )
- return (size_t)rows * cols;
- size_t p = 1;
- for( int i = 0; i < dims; i++ )
- p *= size[i];
- return p;
-}
+#ifdef CV_CXX_MOVE_SEMANTICS
inline
UMat::UMat(UMat&& m)
@@ -3941,6 +3454,8 @@ UMat& UMat::operator = (UMat&& m)
return *this;
}
+#endif
+
inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; }
inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; }
@@ -3974,10 +3489,18 @@ inline void UMatData::markDeviceCopyObsolete(bool flag)
//! @endcond
+static inline
+void swap(MatExpr& a, MatExpr& b) { a.swap(b); }
+
} //cv
#ifdef _MSC_VER
#pragma warning( pop )
#endif
+#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS
+#undef CV_DISABLE_CLANG_ENUM_WARNINGS
+#pragma clang diagnostic pop
+#endif
+
#endif
diff --git a/include/opencv2/core/matx.hpp b/include/opencv2/core/matx.hpp
index de34da4..733f675 100755
--- a/include/opencv2/core/matx.hpp
+++ b/include/opencv2/core/matx.hpp
@@ -53,7 +53,9 @@
#include "opencv2/core/traits.hpp"
#include "opencv2/core/saturate.hpp"
+#ifdef CV_CXX11
#include <initializer_list>
+#endif
namespace cv
{
@@ -140,14 +142,25 @@ public:
_Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix
explicit Matx(const _Tp* vals); //!< initialize from a plain array
+#ifdef CV_CXX11
Matx(std::initializer_list<_Tp>); //!< initialize from an initializer list
+#endif
static Matx all(_Tp alpha);
static Matx zeros();
static Matx ones();
static Matx eye();
static Matx diag(const diag_type& d);
+ /** @brief Generates uniformly distributed random numbers
+ @param a Range boundary.
+ @param b The other range boundary (boundaries don't have to be ordered, the lower boundary is inclusive,
+ the upper one is exclusive).
+ */
static Matx randu(_Tp a, _Tp b);
+ /** @brief Generates normally distributed random numbers
+ @param a Mean value.
+ @param b Standard deviation.
+ */
static Matx randn(_Tp a, _Tp b);
//! dot product computed with the default precision
@@ -358,7 +371,9 @@ public:
Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor
explicit Vec(const _Tp* values);
+#ifdef CV_CXX11
Vec(std::initializer_list<_Tp>);
+#endif
Vec(const Vec<_Tp, cn>& v);
@@ -664,6 +679,7 @@ Matx<_Tp, m, n>::Matx(const _Tp* values)
for( int i = 0; i < channels; i++ ) val[i] = values[i];
}
+#ifdef CV_CXX11
template<typename _Tp, int m, int n> inline
Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list)
{
@@ -674,6 +690,7 @@ Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list)
val[i++] = elem;
}
}
+#endif
template<typename _Tp, int m, int n> inline
Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha)
@@ -1016,9 +1033,11 @@ template<typename _Tp, int cn> inline
Vec<_Tp, cn>::Vec(const _Tp* values)
: Matx<_Tp, cn, 1>(values) {}
+#ifdef CV_CXX11
template<typename _Tp, int cn> inline
Vec<_Tp, cn>::Vec(std::initializer_list<_Tp> list)
: Matx<_Tp, cn, 1>(list) {}
+#endif
template<typename _Tp, int cn> inline
Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m)
@@ -1269,6 +1288,34 @@ Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a)
return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp());
}
+template<typename _Tp, int m, int n> static inline
+Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha)
+{
+ for( int i = 0; i < m*n; i++ )
+ a.val[i] = a.val[i] / alpha;
+ return a;
+}
+
+template<typename _Tp, int m, int n> static inline
+Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha)
+{
+ for( int i = 0; i < m*n; i++ )
+ a.val[i] = a.val[i] / alpha;
+ return a;
+}
+
+template<typename _Tp, int m, int n> static inline
+Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha)
+{
+ return Matx<_Tp, m, n>(a, 1.f/alpha, Matx_ScaleOp());
+}
+
+template<typename _Tp, int m, int n> static inline
+Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha)
+{
+ return Matx<_Tp, m, n>(a, 1./alpha, Matx_ScaleOp());
+}
+
template<typename _Tp, int m, int n> static inline
Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a)
{
diff --git a/include/opencv2/core/ocl.hpp b/include/opencv2/core/ocl.hpp
index 115f5d1..ca46cdc 100755
--- a/include/opencv2/core/ocl.hpp
+++ b/include/opencv2/core/ocl.hpp
@@ -407,28 +407,161 @@ public:
template<typename _Tp> int set(int i, const _Tp& value)
{ return set(i, &value, sizeof(value)); }
+ template<typename _Tp0>
+ Kernel& args(const _Tp0& a0)
+ {
+ set(0, a0); return *this;
+ }
-protected:
- template<typename _Tp0> inline
- int set_args_(int i, const _Tp0& a0) { return set(i, a0); }
- template<typename _Tp0, typename... _Tps> inline
- int set_args_(int i, const _Tp0& a0, const _Tps&... rest_args) { i = set(i, a0); return set_args_(i, rest_args...); }
-public:
- /** @brief Setup OpenCL Kernel arguments.
- Avoid direct using of set(i, ...) methods.
- @code
- bool ok = kernel
- .args(
- srcUMat, dstUMat,
- (float)some_float_param
- ).run(ndims, globalSize, localSize);
- if (!ok) return false;
- @endcode
- */
- template<typename... _Tps> inline
- Kernel& args(const _Tps&... kernel_args) { set_args_(0, kernel_args...); return *this; }
+ template<typename _Tp0, typename _Tp1>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1)
+ {
+ int i = set(0, a0); set(i, a1); return *this;
+ }
+ template<typename _Tp0, typename _Tp1, typename _Tp2>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2)
+ {
+ int i = set(0, a0); i = set(i, a1); set(i, a2); return *this;
+ }
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3, typename _Tp4>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2,
+ const _Tp3& a3, const _Tp4& a4)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2);
+ i = set(i, a3); set(i, a4); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2,
+ typename _Tp3, typename _Tp4, typename _Tp5>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2,
+ const _Tp3& a3, const _Tp4& a4, const _Tp5& a5)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2);
+ i = set(i, a3); i = set(i, a4); set(i, a5); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3);
+ i = set(i, a4); i = set(i, a5); set(i, a6); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3);
+ i = set(i, a4); i = set(i, a5); i = set(i, a6); set(i, a7); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3, typename _Tp4,
+ typename _Tp5, typename _Tp6, typename _Tp7, typename _Tp8>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4);
+ i = set(i, a5); i = set(i, a6); i = set(i, a7); set(i, a8); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3, typename _Tp4,
+ typename _Tp5, typename _Tp6, typename _Tp7, typename _Tp8, typename _Tp9>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); set(i, a9); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); set(i, a10); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10, typename _Tp11>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); set(i, a11); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10, typename _Tp11, typename _Tp12>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11,
+ const _Tp12& a12)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11);
+ set(i, a12); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10, typename _Tp11, typename _Tp12,
+ typename _Tp13>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11,
+ const _Tp12& a12, const _Tp13& a13)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11);
+ i = set(i, a12); set(i, a13); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10, typename _Tp11, typename _Tp12,
+ typename _Tp13, typename _Tp14>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11,
+ const _Tp12& a12, const _Tp13& a13, const _Tp14& a14)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11);
+ i = set(i, a12); i = set(i, a13); set(i, a14); return *this;
+ }
+
+ template<typename _Tp0, typename _Tp1, typename _Tp2, typename _Tp3,
+ typename _Tp4, typename _Tp5, typename _Tp6, typename _Tp7,
+ typename _Tp8, typename _Tp9, typename _Tp10, typename _Tp11, typename _Tp12,
+ typename _Tp13, typename _Tp14, typename _Tp15>
+ Kernel& args(const _Tp0& a0, const _Tp1& a1, const _Tp2& a2, const _Tp3& a3,
+ const _Tp4& a4, const _Tp5& a5, const _Tp6& a6, const _Tp7& a7,
+ const _Tp8& a8, const _Tp9& a9, const _Tp10& a10, const _Tp11& a11,
+ const _Tp12& a12, const _Tp13& a13, const _Tp14& a14, const _Tp15& a15)
+ {
+ int i = set(0, a0); i = set(i, a1); i = set(i, a2); i = set(i, a3); i = set(i, a4); i = set(i, a5);
+ i = set(i, a6); i = set(i, a7); i = set(i, a8); i = set(i, a9); i = set(i, a10); i = set(i, a11);
+ i = set(i, a12); i = set(i, a13); i = set(i, a14); set(i, a15); return *this;
+ }
/** @brief Run the OpenCL kernel.
@param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3.
@param globalsize work items for each dimension. It is not the final globalsize passed to
@@ -587,7 +720,12 @@ public:
String name() const;
String vendor() const;
+
+ /// See CL_PLATFORM_VERSION
String version() const;
+ int versionMajor() const;
+ int versionMinor() const;
+
int deviceNumber() const;
void getDevice(Device& device, int d) const;
diff --git a/include/opencv2/core/opencl/ocl_defs.hpp b/include/opencv2/core/opencl/ocl_defs.hpp
index 14df750..605a65f 100755
--- a/include/opencv2/core/opencl/ocl_defs.hpp
+++ b/include/opencv2/core/opencl/ocl_defs.hpp
@@ -59,18 +59,11 @@ static inline bool isOpenCLActivated() { return false; }
}
#else
#define CV_OCL_RUN_(condition, func, ...) \
-try \
-{ \
if (cv::ocl::isOpenCLActivated() && (condition) && func) \
{ \
CV_IMPL_ADD(CV_IMPL_OCL); \
return __VA_ARGS__; \
- } \
-} \
-catch (const cv::Exception& e) \
-{ \
- CV_UNUSED(e); /* TODO: Add some logging here */ \
-}
+ }
#endif
#else
diff --git a/include/opencv2/core/opencl/opencl_info.hpp b/include/opencv2/core/opencl/opencl_info.hpp
index 21b3672..5e5c846 100755
--- a/include/opencv2/core/opencl/opencl_info.hpp
+++ b/include/opencv2/core/opencl/opencl_info.hpp
@@ -62,7 +62,7 @@ static String getDeviceTypeString(const cv::ocl::Device& device)
}
}
- return "unkown";
+ return "unknown";
}
} // namespace
diff --git a/include/opencv2/core/opengl.hpp b/include/opencv2/core/opengl.hpp
index a311ce2..a6288be 100755
--- a/include/opencv2/core/opengl.hpp
+++ b/include/opencv2/core/opengl.hpp
@@ -548,7 +548,7 @@ calling unmapGLBuffer() function.
@param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE).
@return Returns UMat object
*/
-CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, AccessFlag accessFlags = ACCESS_READ | ACCESS_WRITE);
+CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, int accessFlags = ACCESS_READ|ACCESS_WRITE);
/** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer).
diff --git a/include/opencv2/core/operations.hpp b/include/opencv2/core/operations.hpp
index 92943a6..ef1808a 100755
--- a/include/opencv2/core/operations.hpp
+++ b/include/opencv2/core/operations.hpp
@@ -51,16 +51,6 @@
#include <cstdio>
-#if defined(__GNUC__) || defined(__clang__) // at least GCC 3.1+, clang 3.5+
-# if defined(__MINGW_PRINTF_FORMAT) // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
-# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (__MINGW_PRINTF_FORMAT, string_idx, first_to_check)))
-# else
-# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check)))
-# endif
-#else
-# define CV_FORMAT_PRINTF(A, B)
-#endif
-
//! @cond IGNORED
namespace cv
@@ -266,21 +256,21 @@ Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) c
template<typename _Tp, int m, int n> static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \
template<typename _Tp, int m, int n> static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; }
-CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Scalar)
-CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Scalar)
-CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a,Mat(b),a), Mat)
-CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a,Mat(b),a), Mat_<_Tp>)
-
-CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Scalar)
-CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Scalar)
-CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a,Mat(b),a), Mat)
-CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a,Mat(b),a), Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Scalar)
+CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Scalar)
+CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
+
+CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Scalar)
+CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Scalar)
+CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat)
CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat)
@@ -290,37 +280,37 @@ CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double)
CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat)
CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR (/=, cv::divide(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR (/=, cv::divide(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double)
CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double)
-CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), a), Mat)
-CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), a), Mat_<_Tp>)
-
-CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Scalar)
-CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Scalar)
-CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), a), Mat)
-CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), a), Mat_<_Tp>)
-
-CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Scalar)
-CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Scalar)
-CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), a), Mat)
-CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), a), Mat_<_Tp>)
-
-CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Mat)
-CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Scalar)
-CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat)
-CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Scalar)
-CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
-CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), a), Mat)
-CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), a), Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
+
+CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Scalar)
+CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Scalar)
+CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
+
+CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Scalar)
+CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Scalar)
+CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
+
+CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Mat)
+CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Scalar)
+CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat)
+CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Scalar)
+CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>)
+CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat)
+CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat_<_Tp>)
#undef CV_MAT_AUG_OPERATOR_TN
#undef CV_MAT_AUG_OPERATOR_T
@@ -415,24 +405,13 @@ template<typename _Tp> static inline _Tp randu()
The function acts like sprintf but forms and returns an STL string. It can be used to form an error
message in the Exception constructor.
@param fmt printf-compatible formatting specifiers.
-
-**Note**:
-|Type|Specifier|
-|-|-|
-|`const char*`|`%s`|
-|`char`|`%c`|
-|`float` / `double`|`%f`,`%g`|
-|`int`, `long`, `long long`|`%d`, `%ld`, ``%lld`|
-|`unsigned`, `unsigned long`, `unsigned long long`|`%u`, `%lu`, `%llu`|
-|`uint64` -> `uintmax_t`, `int64` -> `intmax_t`|`%ju`, `%jd`|
-|`size_t`|`%zu`|
*/
-CV_EXPORTS String format( const char* fmt, ... ) CV_FORMAT_PRINTF(1, 2);
+CV_EXPORTS String format( const char* fmt, ... );
///////////////////////////////// Formatted output of cv::Mat /////////////////////////////////
static inline
-Ptr<Formatted> format(InputArray mtx, Formatter::FormatType fmt)
+Ptr<Formatted> format(InputArray mtx, int fmt)
{
return Formatter::get(fmt)->format(mtx.getMat());
}
diff --git a/include/opencv2/core/optim.hpp b/include/opencv2/core/optim.hpp
index 70e037f..5a09400 100755
--- a/include/opencv2/core/optim.hpp
+++ b/include/opencv2/core/optim.hpp
@@ -165,7 +165,7 @@ public:
/** @brief Sets the initial step that will be used in downhill simplex algorithm.
- Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional
+ Step, together with initial point (given in DownhillSolver::minimize) are two `n`-dimensional
vectors that are used to determine the shape of initial simplex. Roughly said, initial point
determines the position of a simplex (it will become simplex's centroid), while step determines the
spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are
@@ -293,7 +293,7 @@ and the remaining to \f$A\f$. It should contain 32- or 64-bit floating point num
formulation above. It will contain 64-bit floating point numbers.
@return One of cv::SolveLPResult
*/
-CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z);
+CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z);
//! @}
diff --git a/include/opencv2/core/persistence.hpp b/include/opencv2/core/persistence.hpp
index 5e00e68..e3026e3 100755
--- a/include/opencv2/core/persistence.hpp
+++ b/include/opencv2/core/persistence.hpp
@@ -94,6 +94,10 @@ The same functions can read and write data in both formats; the particular forma
the extension of the opened file, ".xml" for XML files, ".yml" or ".yaml" for YAML and ".json" for
JSON.
*/
+typedef struct CvFileStorage CvFileStorage;
+typedef struct CvFileNode CvFileNode;
+typedef struct CvMat CvMat;
+typedef struct CvMatND CvMatND;
//! @} core_c
@@ -310,7 +314,7 @@ public:
WRITE = 1, //!< value, open the file for writing
APPEND = 2, //!< value, open the file for appending
MEMORY = 4, //!< flag, read data from source or write data to the internal buffer (which is
- //!< returned by FileStorage::release)
+ //!< returned by FileStorage::release)
FORMAT_MASK = (7<<3), //!< mask for format flags
FORMAT_AUTO = 0, //!< flag, auto format
FORMAT_XML = (1<<3), //!< flag, XML format
@@ -320,7 +324,7 @@ public:
BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64)
WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64
};
- enum State
+ enum
{
UNDEFINED = 0,
VALUE_EXPECTED = 1,
@@ -330,77 +334,105 @@ public:
/** @brief The constructors.
- The full constructor opens the file. Alternatively you can use the default constructor and then
- call FileStorage::open.
+ The full constructor opens the file. Alternatively you can use the default constructor and then
+ call FileStorage::open.
*/
CV_WRAP FileStorage();
/** @overload
- @copydoc open()
- */
+ @copydoc open()
+ */
CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String());
+ /** @overload */
+ FileStorage(CvFileStorage* fs, bool owning=true);
+
//! the destructor. calls release()
virtual ~FileStorage();
/** @brief Opens a file.
- See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release
- before opening the file.
- @param filename Name of the file to open or the text string to read the data from.
- Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON
- 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.). A file name can also contain parameters.
- You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to
- FileStorage::BASE64 flag.
- @param flags Mode of operation. One of FileStorage::Mode
- @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.
+ See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release
+ before opening the file.
+ @param filename Name of the file to open or the text string to read the data from.
+ Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON
+ 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.). A file name can also contain parameters.
+ You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to
+ FileStorage::BASE64 flag.
+ @param flags Mode of operation. One of FileStorage::Mode
+ @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.
*/
CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String());
/** @brief Checks whether the file is opened.
- @returns true if the object is associated with the current file and false otherwise. It is a
- good practice to call this method after you tried to open a file.
+ @returns true if the object is associated with the current file and false otherwise. It is a
+ good practice to call this method after you tried to open a file.
*/
CV_WRAP virtual bool isOpened() const;
/** @brief 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.
*/
CV_WRAP virtual void release();
/** @brief Closes the file and releases all the memory buffers.
- 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
+ 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
*/
CV_WRAP virtual String releaseAndGetString();
/** @brief Returns the first element of the top-level mapping.
- @returns The first element of the top-level mapping.
+ @returns The first element of the top-level mapping.
*/
CV_WRAP FileNode getFirstTopLevelNode() const;
/** @brief Returns the top-level mapping
- @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file.
- However, YAML supports multiple streams and so there can be several.
- @returns The top-level mapping.
+ @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file.
+ However, YAML supports multiple streams and so there can be several.
+ @returns The top-level mapping.
*/
CV_WRAP FileNode root(int streamidx=0) const;
/** @brief Returns the specified element of the top-level mapping.
- @param nodename Name of the file node.
- @returns Node with the given name.
+ @param nodename Name of the file node.
+ @returns Node with the given name.
*/
FileNode operator[](const String& nodename) const;
/** @overload */
CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const;
+ /** @brief Returns the obsolete C FileStorage structure.
+ @returns Pointer to the underlying C FileStorage structure
+ */
+ CvFileStorage* operator *() { return fs.get(); }
+
+ /** @overload */
+ const CvFileStorage* operator *() const { return fs.get(); }
+
+ /** @brief Writes multiple numbers.
+
+ Writes one or more numbers of the specified format to the currently written structure. Usually it is
+ more convenient to use operator `<<` instead of this method.
+ @param fmt Specification of each array element, see @ref format_spec "format specification"
+ @param vec Pointer to the written array.
+ @param len Number of the uchar elements to write.
+ */
+ void writeRaw( const String& fmt, const uchar* vec, size_t len );
+
+ /** @brief Writes the registered C structure (CvMat, CvMatND, CvSeq).
+ @param name Name of the written object.
+ @param obj Pointer to the object.
+ @see cvWrite for details.
+ */
+ void writeObj( const String& name, const void* obj );
+
/**
* @brief Simplified writing API to use with bindings.
* @param name Name of the written object
@@ -412,36 +444,32 @@ public:
/// @overload
CV_WRAP void write(const String& name, const String& val);
/// @overload
- CV_WRAP void write(const String& name, const Mat& val);
- /// @overload
- CV_WRAP void write(const String& name, const std::vector<String>& val);
-
- /** @brief Writes multiple numbers.
-
- Writes one or more numbers of the specified format to the currently written structure. Usually it is
- more convenient to use operator `<<` instead of this method.
- @param fmt Specification of each array element, see @ref format_spec "format specification"
- @param vec Pointer to the written array.
- @param len Number of the uchar elements to write.
- */
- void writeRaw( const String& fmt, const void* vec, size_t len );
+ CV_WRAP void write(const String& name, InputArray val);
/** @brief Writes a comment.
- The function writes a comment into file storage. The comments are skipped when the storage is read.
- @param comment The written comment, single-line or multi-line
- @param append If true, the function tries to put the comment at the end of current line.
- Else 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.
+ @param comment The written comment, single-line or multi-line
+ @param append If true, the function tries to put the comment at the end of current line.
+ Else 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.
*/
CV_WRAP void writeComment(const String& comment, bool append = false);
- void startWriteStruct(const String& name, int flags, const String& typeName);
- void endWriteStruct();
+ /** @brief Starts to write a nested structure (sequence or a mapping).
+ @param name name of the structure (if it's a member of parent mapping, otherwise it should be empty
+ @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)).
+ @param typeName usually an empty string
+ */
+ CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String());
+
+ /** @brief Finishes writing nested structure (should pair startWriteStruct())
+ */
+ CV_WRAP void endWriteStruct();
/** @brief Returns the normalized object name for the specified name of a file.
- @param filename Name of a file
- @returns The normalized object name.
+ @param filename Name of a file
+ @returns The normalized object name.
*/
static String getDefaultObjectName(const String& filename);
@@ -450,13 +478,14 @@ public:
*/
CV_WRAP int getFormat() const;
- int state;
- std::string elname;
-
- class Impl;
- Ptr<Impl> p;
+ Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
+ String elname; //!< the currently written element
+ std::vector<char> structs; //!< the stack of written structures
+ int state; //!< the writer state
};
+template<> CV_EXPORTS void DefaultDeleter<CvFileStorage>::operator ()(CvFileStorage* obj) const;
+
/** @brief File Storage Node class.
The node is used to store each and every element of the file storage opened for reading. When
@@ -473,7 +502,7 @@ class CV_EXPORTS_W_SIMPLE FileNode
{
public:
//! type of the file storage node
- enum
+ enum Type
{
NONE = 0, //!< empty node
INT = 1, //!< an integer
@@ -481,60 +510,58 @@ public:
FLOAT = REAL, //!< synonym or REAL
STR = 3, //!< text string in UTF-8 encoding
STRING = STR, //!< synonym for STR
- SEQ = 4, //!< sequence
- MAP = 5, //!< mapping
+ REF = 4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
+ SEQ = 5, //!< sequence
+ MAP = 6, //!< mapping
TYPE_MASK = 7,
-
FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer
- UNIFORM = 8, //!< if set, means that all the collection elements are numbers of the same type (real's or int's).
- //!< UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit
- EMPTY = 16, //!< empty structure (sequence or mapping)
- NAMED = 32 //!< the node has a name (i.e. it is element of a mapping).
+ USER = 16, //!< a registered object (e.g. a matrix)
+ EMPTY = 32, //!< empty structure (sequence or mapping)
+ NAMED = 64 //!< the node has a name (i.e. it is element of a mapping)
};
/** @brief The constructors.
- These constructors are used to create a default file node, construct it from obsolete structures or
- from the another file node.
+ These constructors are used to create a default file node, construct it from obsolete structures or
+ from the another file node.
*/
CV_WRAP FileNode();
/** @overload
- @param fs Pointer to the file storage structure.
- @param blockIdx Index of the memory block where the file node is stored
- @param ofs Offset in bytes from the beginning of the serialized storage
- */
- FileNode(const FileStorage* fs, size_t blockIdx, size_t ofs);
+ @param fs Pointer to the obsolete file storage structure.
+ @param node File node to be used as initialization for the created file node.
+ */
+ FileNode(const CvFileStorage* fs, const CvFileNode* node);
/** @overload
- @param node File node to be used as initialization for the created file node.
- */
+ @param node File node to be used as initialization for the created file node.
+ */
FileNode(const FileNode& node);
FileNode& operator=(const FileNode& node);
/** @brief Returns element of a mapping node or a sequence node.
- @param nodename Name of an element in the mapping node.
- @returns Returns the element with the given identifier.
+ @param nodename Name of an element in the mapping node.
+ @returns Returns the element with the given identifier.
*/
FileNode operator[](const String& nodename) const;
/** @overload
- @param nodename Name of an element in the mapping node.
- */
+ @param nodename Name of an element in the mapping node.
+ */
CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const;
/** @overload
- @param i Index of an element in the sequence node.
- */
+ @param i Index of an element in the sequence node.
+ */
CV_WRAP_AS(at) FileNode operator[](int i) const;
/** @brief Returns keys of a mapping node.
- @returns Keys of a mapping node.
+ @returns Keys of a mapping node.
*/
CV_WRAP std::vector<String> keys() const;
/** @brief Returns type of the node.
- @returns Type of the node. See FileNode::Type
+ @returns Type of the node. See FileNode::Type
*/
CV_WRAP int type() const;
@@ -555,11 +582,9 @@ public:
//! returns true if the node has a name
CV_WRAP bool isNamed() const;
//! returns the node name or an empty string if the node is nameless
- CV_WRAP std::string name() const;
+ CV_WRAP String name() const;
//! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
CV_WRAP size_t size() const;
- //! returns raw size of the FileNode in bytes
- CV_WRAP size_t rawSize() const;
//! returns the node content as an integer. If the node stores floating-point number, it is rounded.
operator int() const;
//! returns the node content as float
@@ -567,16 +592,13 @@ public:
//! returns the node content as double
operator double() const;
//! returns the node content as text string
- inline operator std::string() const { return this->string(); }
-
- static bool isMap(int flags);
- static bool isSeq(int flags);
- static bool isCollection(int flags);
- static bool isEmptyCollection(int flags);
- static bool isFlow(int flags);
+ operator String() const;
+ operator std::string() const;
- uchar* ptr();
- const uchar* ptr() const;
+ //! returns pointer to the underlying file node
+ CvFileNode* operator *();
+ //! returns pointer to the underlying file node
+ const CvFileNode* operator* () const;
//! returns iterator pointing to the first node element
FileNodeIterator begin() const;
@@ -591,68 +613,70 @@ public:
@param len Number of bytes to read (buffer size limit). If it is greater than number of
remaining elements then all of them will be read.
*/
- void readRaw( const String& fmt, void* vec, size_t len ) const;
+ void readRaw( const String& fmt, uchar* vec, size_t len ) const;
- /** Internal method used when reading FileStorage.
- Sets the type (int, real or string) and value of the previously created node.
- */
- void setValue( int type, const void* value, int len=-1 );
+ //! reads the registered object and returns pointer to it
+ void* readObj() const;
//! Simplified reading API to use with bindings.
CV_WRAP double real() const;
//! Simplified reading API to use with bindings.
- CV_WRAP std::string string() const;
+ CV_WRAP String string() const;
//! Simplified reading API to use with bindings.
CV_WRAP Mat mat() const;
- //protected:
- const FileStorage* fs;
- size_t blockIdx;
- size_t ofs;
+ // do not use wrapper pointer classes for better efficiency
+ const CvFileStorage* fs;
+ const CvFileNode* node;
};
/** @brief used to iterate through sequences and mappings.
- A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a
- sequence, stored in node. See the data reading sample in the beginning of the section.
+A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a
+sequence, stored in node. See the data reading sample in the beginning of the section.
*/
class CV_EXPORTS FileNodeIterator
{
public:
/** @brief The constructors.
- These constructors are used to create a default iterator, set it to specific element in a file node
- or construct it from another iterator.
+ These constructors are used to create a default iterator, set it to specific element in a file node
+ or construct it from another iterator.
*/
FileNodeIterator();
/** @overload
- @param node File node - the collection to iterate over;
- it can be a scalar (equivalent to 1-element collection) or "none" (equivalent to empty collection).
- @param seekEnd - true if iterator needs to be set after the last element of the node;
- that is:
- * node.begin() => FileNodeIterator(node, false)
- * node.end() => FileNodeIterator(node, true)
- */
- FileNodeIterator(const FileNode& node, bool seekEnd);
+ @param fs File storage for the iterator.
+ @param node File node for the iterator.
+ @param ofs Index of the element in the node. The created iterator will point to this element.
+ */
+ FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
/** @overload
- @param it Iterator to be used as initialization for the created iterator.
- */
+ @param it Iterator to be used as initialization for the created iterator.
+ */
FileNodeIterator(const FileNodeIterator& it);
FileNodeIterator& operator=(const FileNodeIterator& it);
//! returns the currently observed element
FileNode operator *() const;
+ //! accesses the currently observed element methods
+ FileNode operator ->() const;
//! moves iterator to the next node
FileNodeIterator& operator ++ ();
//! moves iterator to the next node
FileNodeIterator operator ++ (int);
+ //! moves iterator to the previous node
+ FileNodeIterator& operator -- ();
+ //! moves iterator to the previous node
+ FileNodeIterator operator -- (int);
//! moves iterator forward by the specified offset (possibly negative)
FileNodeIterator& operator += (int ofs);
+ //! moves iterator backward by the specified offset (possibly negative)
+ FileNodeIterator& operator -= (int ofs);
/** @brief Reads node elements to the buffer with the specified format.
@@ -661,22 +685,27 @@ public:
@param vec Pointer to the destination array.
@param len Number of bytes to read (buffer size limit). If it is greater than number of
remaining elements then all of them will be read.
+
*/
- FileNodeIterator& readRaw( const String& fmt, void* vec,
+ FileNodeIterator& readRaw( const String& fmt, uchar* vec,
size_t len=(size_t)INT_MAX );
- //! returns the number of remaining (not read yet) elements
- size_t remaining() const;
-
- bool equalTo(const FileNodeIterator& it) const;
+ struct SeqReader
+ {
+ int header_size;
+ void* seq; /* sequence, beign read; CvSeq */
+ void* block; /* current block; CvSeqBlock */
+ schar* ptr; /* pointer to element be read next */
+ schar* block_min; /* pointer to the beginning of block */
+ schar* block_max; /* pointer to the end of block */
+ int delta_index;/* = seq->first->start_index */
+ schar* prev_elem; /* pointer to previous element */
+ };
-protected:
- const FileStorage* fs;
- size_t blockIdx;
- size_t ofs;
- size_t blockSize;
- size_t nodeNElems;
- size_t idx;
+ const CvFileStorage* fs;
+ const CvFileNode* container;
+ SeqReader reader;
+ size_t remaining;
};
//! @} core_xml
@@ -710,6 +739,7 @@ CV_EXPORTS void writeScalar( FileStorage& fs, const String& value );
CV_EXPORTS void read(const FileNode& node, int& value, int default_value);
CV_EXPORTS void read(const FileNode& node, float& value, float default_value);
CV_EXPORTS void read(const FileNode& node, double& value, double default_value);
+CV_EXPORTS void read(const FileNode& node, String& value, const String& default_value);
CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value);
CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() );
CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() );
@@ -758,17 +788,6 @@ template<typename _Tp, int cn> static inline void read(const FileNode& node, Vec
value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]);
}
-template<typename _Tp, int m, int n> static inline void read(const FileNode& node, Matx<_Tp, m, n>& value, const Matx<_Tp, m, n>& default_matx = Matx<_Tp, m, n>())
-{
- Mat temp;
- read(node, temp); // read as a Mat class
-
- if (temp.empty())
- value = default_matx;
- else
- value = Matx<_Tp, m, n>(temp);
-}
-
template<typename _Tp> static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value)
{
std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
@@ -837,7 +856,7 @@ namespace internal
VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
void operator()(std::vector<_Tp>& vec, size_t count) const
{
- count = std::min(count, it->remaining());
+ count = std::min(count, it->remaining);
vec.resize(count);
for (size_t i = 0; i < count; i++, ++(*it))
read(**it, vec[i], _Tp());
@@ -852,14 +871,14 @@ namespace internal
VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
void operator()(std::vector<_Tp>& vec, size_t count) const
{
- size_t remaining = it->remaining();
+ size_t remaining = it->remaining;
size_t cn = DataType<_Tp>::channels;
int _fmt = traits::SafeFmt<_Tp>::fmt;
CV_Assert((_fmt >> 8) < 9);
char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' };
CV_Assert((remaining % cn) == 0);
size_t remaining1 = remaining / cn;
- count = count > remaining1 ? remaining1 : count;
+ count = count < remaining1 ? count : remaining1;
vec.resize(count);
it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp));
}
@@ -949,12 +968,6 @@ void write(FileStorage& fs, const Vec<_Tp, cn>& v )
write(fs, v.val[i]);
}
-template<typename _Tp, int m, int n> static inline
-void write(FileStorage& fs, const Matx<_Tp, m, n>& x )
-{
- write(fs, Mat(x)); // write as a Mat class
-}
-
template<typename _Tp> static inline
void write(FileStorage& fs, const Scalar_<_Tp>& s )
{
@@ -1020,12 +1033,6 @@ void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v )
write(fs, v);
}
-template<typename _Tp, int m, int n> static inline
-void write(FileStorage& fs, const String& name, const Matx<_Tp, m, n>& x )
-{
- write(fs, name, Mat(x)); // write as a Mat class
-}
-
template<typename _Tp> static inline
void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s )
{
@@ -1063,12 +1070,6 @@ void write(FileStorage& fs, const String& name, const DMatch& m)
write(fs, m.distance);
}
-template<typename _Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type* = nullptr>
-static inline void write( FileStorage& fs, const String& name, const _Tp& val )
-{
- write(fs, name, static_cast<int>(val));
-}
-
template<typename _Tp> static inline
void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec )
{
@@ -1157,18 +1158,10 @@ void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_
r(vec, maxCount);
}
-template<typename _Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type* = nullptr>
-static inline void read(const FileNode& node, _Tp& value, const _Tp& default_value = static_cast<_Tp>(0))
-{
- int temp;
- read(node, temp, static_cast<int>(default_value));
- value = static_cast<_Tp>(temp);
-}
-
template<typename _Tp> static inline
void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() )
{
- if(node.empty())
+ if(!node.node)
vec = default_value;
else
{
@@ -1180,7 +1173,7 @@ void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>&
static inline
void read( const FileNode& node, std::vector<KeyPoint>& vec, const std::vector<KeyPoint>& default_value )
{
- if(node.empty())
+ if(!node.node)
vec = default_value;
else
read(node, vec);
@@ -1189,7 +1182,7 @@ void read( const FileNode& node, std::vector<KeyPoint>& vec, const std::vector<K
static inline
void read( const FileNode& node, std::vector<DMatch>& vec, const std::vector<DMatch>& default_value )
{
- if(node.empty())
+ if(!node.node)
vec = default_value;
else
read(node, vec);
@@ -1315,23 +1308,76 @@ void operator >> (const FileNode& n, DMatch& m)
//! @relates cv::FileNodeIterator
//! @{
-CV_EXPORTS bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2);
-CV_EXPORTS bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2);
+static inline
+bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2)
+{
+ return it1.fs == it2.fs && it1.container == it2.container &&
+ it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining;
+}
+
+static inline
+bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2)
+{
+ return !(it1 == it2);
+}
static inline
ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2)
{
- return it2.remaining() - it1.remaining();
+ return it2.remaining - it1.remaining;
}
static inline
bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2)
{
- return it1.remaining() > it2.remaining();
+ return it1.remaining > it2.remaining;
}
//! @} FileNodeIterator
+//! @cond IGNORED
+
+inline FileNode FileStorage::getFirstTopLevelNode() const { FileNode r = root(); FileNodeIterator it = r.begin(); return it != r.end() ? *it : FileNode(); }
+inline FileNode::FileNode() : fs(0), node(0) {}
+inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) : fs(_fs), node(_node) {}
+inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {}
+inline FileNode& FileNode::operator=(const FileNode& _node) { fs = _node.fs; node = _node.node; return *this; }
+inline bool FileNode::empty() const { return node == 0; }
+inline bool FileNode::isNone() const { return type() == NONE; }
+inline bool FileNode::isSeq() const { return type() == SEQ; }
+inline bool FileNode::isMap() const { return type() == MAP; }
+inline bool FileNode::isInt() const { return type() == INT; }
+inline bool FileNode::isReal() const { return type() == REAL; }
+inline bool FileNode::isString() const { return type() == STR; }
+inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
+inline const CvFileNode* FileNode::operator* () const { return node; }
+inline FileNode::operator int() const { int value; read(*this, value, 0); return value; }
+inline FileNode::operator float() const { float value; read(*this, value, 0.f); return value; }
+inline FileNode::operator double() const { double value; read(*this, value, 0.); return value; }
+inline FileNode::operator String() const { String value; read(*this, value, value); return value; }
+inline double FileNode::real() const { return double(*this); }
+inline String FileNode::string() const { return String(*this); }
+inline Mat FileNode::mat() const { Mat value; read(*this, value, value); return value; }
+inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); }
+inline FileNodeIterator FileNode::end() const { return FileNodeIterator(fs, node, size()); }
+inline void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const { begin().readRaw( fmt, vec, len ); }
+inline FileNode FileNodeIterator::operator *() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
+inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
+inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, *this); }
+
+//! @endcond
+
+
+CV_EXPORTS void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt);
+
+CV_EXPORTS void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len);
+
+CV_EXPORTS void cvEndWriteRawData_Base64(::CvFileStorage * fs);
+
+CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat);
+
+CV_EXPORTS void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat);
+
} // cv
#endif // OPENCV_CORE_PERSISTENCE_HPP
diff --git a/include/opencv2/core/saturate.hpp b/include/opencv2/core/saturate.hpp
index 8127e3d..36d3121 100755
--- a/include/opencv2/core/saturate.hpp
+++ b/include/opencv2/core/saturate.hpp
@@ -156,22 +156,6 @@ template<> inline uint64 saturate_cast<uint64>(int64 v) { return (uint64)st
template<> inline int64 saturate_cast<int64>(uint64 v) { return (int64)std::min(v, (uint64)LLONG_MAX); }
-/** @overload */
-template<typename _Tp> static inline _Tp saturate_cast(float16_t v) { return saturate_cast<_Tp>((float)v); }
-
-// in theory, we could use a LUT for 8u/8s->16f conversion,
-// but with hardware support for FP32->FP16 conversion the current approach is preferable
-template<> inline float16_t saturate_cast<float16_t>(uchar v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(schar v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(ushort v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(short v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(unsigned v){ return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(int v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(uint64 v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(int64 v) { return float16_t((float)v); }
-template<> inline float16_t saturate_cast<float16_t>(float v) { return float16_t(v); }
-template<> inline float16_t saturate_cast<float16_t>(double v) { return float16_t((float)v); }
-
//! @}
} // cv
diff --git a/include/opencv2/core/simd_intrinsics.hpp b/include/opencv2/core/simd_intrinsics.hpp
index c50923f..7151d36 100755
--- a/include/opencv2/core/simd_intrinsics.hpp
+++ b/include/opencv2/core/simd_intrinsics.hpp
@@ -7,7 +7,7 @@
/**
Helper header to support SIMD intrinsics (universal intrinsics) in user code.
-Intrinsics documentation: https://docs.opencv.org/master/df/d91/group__core__hal__intrin.html
+Intrinsics documentation: https://docs.opencv.org/3.4/df/d91/group__core__hal__intrin.html
Checks of target CPU instruction set based on compiler definitions don't work well enough.
diff --git a/include/opencv2/core/traits.hpp b/include/opencv2/core/traits.hpp
index 52ab083..6cb10f4 100755
--- a/include/opencv2/core/traits.hpp
+++ b/include/opencv2/core/traits.hpp
@@ -261,20 +261,6 @@ public:
};
};
-template<> class DataType<float16_t>
-{
-public:
- typedef float16_t value_type;
- typedef float work_type;
- typedef value_type channel_type;
- typedef value_type vec_type;
- enum { generic_type = 0,
- depth = CV_16F,
- channels = 1,
- fmt = (int)'h',
- type = CV_MAKETYPE(depth, channels)
- };
-};
/** @brief A helper class for cv::DataType
@@ -344,12 +330,6 @@ template<> class TypeDepth<CV_64F>
typedef double value_type;
};
-template<> class TypeDepth<CV_16F>
-{
- enum { depth = CV_16F };
- typedef float16_t value_type;
-};
-
#endif
//! @}
diff --git a/include/opencv2/core/types.hpp b/include/opencv2/core/types.hpp
index b1fa676..4d04bef 100755
--- a/include/opencv2/core/types.hpp
+++ b/include/opencv2/core/types.hpp
@@ -163,12 +163,10 @@ public:
Point_();
Point_(_Tp _x, _Tp _y);
Point_(const Point_& pt);
- Point_(Point_&& pt) CV_NOEXCEPT;
Point_(const Size_<_Tp>& sz);
Point_(const Vec<_Tp, 2>& v);
Point_& operator = (const Point_& pt);
- Point_& operator = (Point_&& pt) CV_NOEXCEPT;
//! conversion to another data type
template<typename _Tp2> operator Point_<_Tp2>() const;
@@ -245,16 +243,18 @@ public:
Point3_();
Point3_(_Tp _x, _Tp _y, _Tp _z);
Point3_(const Point3_& pt);
- Point3_(Point3_&& pt) CV_NOEXCEPT;
explicit Point3_(const Point_<_Tp>& pt);
Point3_(const Vec<_Tp, 3>& v);
Point3_& operator = (const Point3_& pt);
- Point3_& operator = (Point3_&& pt) CV_NOEXCEPT;
//! conversion to another data type
template<typename _Tp2> operator Point3_<_Tp2>() const;
//! conversion to cv::Vec<>
+#if OPENCV_ABI_COMPATIBILITY > 300
+ template<typename _Tp2> operator Vec<_Tp2, 3>() const;
+#else
operator Vec<_Tp, 3>() const;
+#endif
//! dot product
_Tp dot(const Point3_& pt) const;
@@ -321,15 +321,11 @@ public:
Size_();
Size_(_Tp _width, _Tp _height);
Size_(const Size_& sz);
- Size_(Size_&& sz) CV_NOEXCEPT;
Size_(const Point_<_Tp>& pt);
Size_& operator = (const Size_& sz);
- Size_& operator = (Size_&& sz) CV_NOEXCEPT;
//! the area (width*height)
_Tp area() const;
- //! aspect ratio (width/height)
- double aspectRatio() const;
//! true if empty
bool empty() const;
@@ -426,12 +422,10 @@ public:
Rect_();
Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
Rect_(const Rect_& r);
- Rect_(Rect_&& r) CV_NOEXCEPT;
Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
Rect_& operator = ( const Rect_& r );
- Rect_& operator = ( Rect_&& r ) CV_NOEXCEPT;
//! the top-left corner
Point_<_Tp> tl() const;
//! the bottom-right corner
@@ -641,12 +635,6 @@ public:
Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
Scalar_(_Tp v0);
- Scalar_(const Scalar_& s);
- Scalar_(Scalar_&& s) CV_NOEXCEPT;
-
- Scalar_& operator=(const Scalar_& s);
- Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT;
-
template<typename _Tp2, int cn>
Scalar_(const Vec<_Tp2, cn>& v);
@@ -1168,10 +1156,6 @@ template<typename _Tp> inline
Point_<_Tp>::Point_(const Point_& pt)
: x(pt.x), y(pt.y) {}
-template<typename _Tp> inline
-Point_<_Tp>::Point_(Point_&& pt) CV_NOEXCEPT
- : x(std::move(pt.x)), y(std::move(pt.y)) {}
-
template<typename _Tp> inline
Point_<_Tp>::Point_(const Size_<_Tp>& sz)
: x(sz.width), y(sz.height) {}
@@ -1187,13 +1171,6 @@ Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt)
return *this;
}
-template<typename _Tp> inline
-Point_<_Tp>& Point_<_Tp>::operator = (Point_&& pt) CV_NOEXCEPT
-{
- x = std::move(pt.x); y = std::move(pt.y);
- return *this;
-}
-
template<typename _Tp> template<typename _Tp2> inline
Point_<_Tp>::operator Point_<_Tp2>() const
{
@@ -1215,7 +1192,7 @@ _Tp Point_<_Tp>::dot(const Point_& pt) const
template<typename _Tp> inline
double Point_<_Tp>::ddot(const Point_& pt) const
{
- return (double)x*pt.x + (double)y*pt.y;
+ return (double)x*(double)(pt.x) + (double)y*(double)(pt.y);
}
template<typename _Tp> inline
@@ -1435,10 +1412,6 @@ template<typename _Tp> inline
Point3_<_Tp>::Point3_(const Point3_& pt)
: x(pt.x), y(pt.y), z(pt.z) {}
-template<typename _Tp> inline
-Point3_<_Tp>::Point3_(Point3_&& pt) CV_NOEXCEPT
- : x(std::move(pt.x)), y(std::move(pt.y)), z(std::move(pt.z)) {}
-
template<typename _Tp> inline
Point3_<_Tp>::Point3_(const Point_<_Tp>& pt)
: x(pt.x), y(pt.y), z(_Tp()) {}
@@ -1453,11 +1426,19 @@ Point3_<_Tp>::operator Point3_<_Tp2>() const
return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z));
}
+#if OPENCV_ABI_COMPATIBILITY > 300
+template<typename _Tp> template<typename _Tp2> inline
+Point3_<_Tp>::operator Vec<_Tp2, 3>() const
+{
+ return Vec<_Tp2, 3>(x, y, z);
+}
+#else
template<typename _Tp> inline
Point3_<_Tp>::operator Vec<_Tp, 3>() const
{
return Vec<_Tp, 3>(x, y, z);
}
+#endif
template<typename _Tp> inline
Point3_<_Tp>& Point3_<_Tp>::operator = (const Point3_& pt)
@@ -1466,13 +1447,6 @@ Point3_<_Tp>& Point3_<_Tp>::operator = (const Point3_& pt)
return *this;
}
-template<typename _Tp> inline
-Point3_<_Tp>& Point3_<_Tp>::operator = (Point3_&& pt) CV_NOEXCEPT
-{
- x = std::move(pt.x); y = std::move(pt.y); z = std::move(pt.z);
- return *this;
-}
-
template<typename _Tp> inline
_Tp Point3_<_Tp>::dot(const Point3_& pt) const
{
@@ -1689,10 +1663,6 @@ template<typename _Tp> inline
Size_<_Tp>::Size_(const Size_& sz)
: width(sz.width), height(sz.height) {}
-template<typename _Tp> inline
-Size_<_Tp>::Size_(Size_&& sz) CV_NOEXCEPT
- : width(std::move(sz.width)), height(std::move(sz.height)) {}
-
template<typename _Tp> inline
Size_<_Tp>::Size_(const Point_<_Tp>& pt)
: width(pt.x), height(pt.y) {}
@@ -1710,13 +1680,6 @@ Size_<_Tp>& Size_<_Tp>::operator = (const Size_<_Tp>& sz)
return *this;
}
-template<typename _Tp> inline
-Size_<_Tp>& Size_<_Tp>::operator = (Size_<_Tp>&& sz) CV_NOEXCEPT
-{
- width = std::move(sz.width); height = std::move(sz.height);
- return *this;
-}
-
template<typename _Tp> inline
_Tp Size_<_Tp>::area() const
{
@@ -1726,12 +1689,6 @@ _Tp Size_<_Tp>::area() const
return result;
}
-template<typename _Tp> inline
-double Size_<_Tp>::aspectRatio() const
-{
- return width / static_cast<double>(height);
-}
-
template<typename _Tp> inline
bool Size_<_Tp>::empty() const
{
@@ -1831,10 +1788,6 @@ template<typename _Tp> inline
Rect_<_Tp>::Rect_(const Rect_<_Tp>& r)
: x(r.x), y(r.y), width(r.width), height(r.height) {}
-template<typename _Tp> inline
-Rect_<_Tp>::Rect_(Rect_<_Tp>&& r) CV_NOEXCEPT
- : x(std::move(r.x)), y(std::move(r.y)), width(std::move(r.width)), height(std::move(r.height)) {}
-
template<typename _Tp> inline
Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz)
: x(org.x), y(org.y), width(sz.width), height(sz.height) {}
@@ -1858,16 +1811,6 @@ Rect_<_Tp>& Rect_<_Tp>::operator = ( const Rect_<_Tp>& r )
return *this;
}
-template<typename _Tp> inline
-Rect_<_Tp>& Rect_<_Tp>::operator = ( Rect_<_Tp>&& r ) CV_NOEXCEPT
-{
- x = std::move(r.x);
- y = std::move(r.y);
- width = std::move(r.width);
- height = std::move(r.height);
- return *this;
-}
-
template<typename _Tp> inline
Point_<_Tp> Rect_<_Tp>::tl() const
{
@@ -2064,6 +2007,8 @@ inline
RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle)
: center(_center), size(_size), angle(_angle) {}
+
+
///////////////////////////////// Range /////////////////////////////////
inline
@@ -2163,36 +2108,6 @@ Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3)
this->val[3] = v3;
}
-template<typename _Tp> inline
-Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) {
-}
-
-template<typename _Tp> inline
-Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT {
- this->val[0] = std::move(s.val[0]);
- this->val[1] = std::move(s.val[1]);
- this->val[2] = std::move(s.val[2]);
- this->val[3] = std::move(s.val[3]);
-}
-
-template<typename _Tp> inline
-Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) {
- this->val[0] = s.val[0];
- this->val[1] = s.val[1];
- this->val[2] = s.val[2];
- this->val[3] = s.val[3];
- return *this;
-}
-
-template<typename _Tp> inline
-Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT {
- this->val[0] = std::move(s.val[0]);
- this->val[1] = std::move(s.val[1]);
- this->val[2] = std::move(s.val[2]);
- this->val[3] = std::move(s.val[3]);
- return *this;
-}
-
template<typename _Tp> template<typename _Tp2, int cn> inline
Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v)
{
diff --git a/include/opencv2/core/types_c.h b/include/opencv2/core/types_c.h
index 97aeab3..eddbe7d 100755
--- a/include/opencv2/core/types_c.h
+++ b/include/opencv2/core/types_c.h
@@ -1707,7 +1707,7 @@ typedef CvContour CvPoint2DSeq;
#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */
#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */
#define CV_SEQ_ELTYPE_GENERIC 0
-#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/)
+#define CV_SEQ_ELTYPE_PTR CV_USRTYPE1
#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */
#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */
#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */
@@ -1959,8 +1959,6 @@ CvSeqReader;
* Data structures for persistence (a.k.a serialization) functionality *
\****************************************************************************************/
-#if 0
-
/** "black box" file storage */
typedef struct CvFileStorage CvFileStorage;
@@ -2113,7 +2111,28 @@ typedef struct CvTypeInfo
CvCloneFunc clone; /**< creates a copy of the object */
}
CvTypeInfo;
-#endif
+
+
+/**** System data types ******/
+
+typedef struct CvPluginFuncInfo
+{
+ void** func_addr;
+ void* default_func_addr;
+ const char* func_names;
+ int search_modules;
+ int loaded_from;
+}
+CvPluginFuncInfo;
+
+typedef struct CvModuleInfo
+{
+ struct CvModuleInfo* next;
+ const char* name;
+ const char* version;
+ CvPluginFuncInfo* func_tab;
+}
+CvModuleInfo;
/** @} */
diff --git a/include/opencv2/core/utility.hpp b/include/opencv2/core/utility.hpp
index 311d6f5..b97458d 100755
--- a/include/opencv2/core/utility.hpp
+++ b/include/opencv2/core/utility.hpp
@@ -56,10 +56,8 @@
#include "opencv2/core.hpp"
#include <ostream>
+#ifdef CV_CXX11
#include <functional>
-
-#if !defined(_M_CEE)
-#include <mutex> // std::mutex, std::lock_guard
#endif
namespace cv
@@ -284,107 +282,98 @@ CV_EXPORTS_W double getTickFrequency();
The class computes passing time by counting the number of ticks per second. That is, the following code computes the
execution time in seconds:
-@code
-TickMeter tm;
-tm.start();
-// do something ...
-tm.stop();
-std::cout << tm.getTimeSec();
-@endcode
+@snippet snippets/core_various.cpp TickMeter_total
It is also possible to compute the average time over multiple runs:
-@code
-TickMeter tm;
-for (int i = 0; i < 100; i++)
-{
- tm.start();
- // do something ...
- tm.stop();
-}
-double average_time = tm.getTimeSec() / tm.getCounter();
-std::cout << "Average time in second per iteration is: " << average_time << std::endl;
-@endcode
+@snippet snippets/core_various.cpp TickMeter_average
+
@sa getTickCount, getTickFrequency
*/
-
class CV_EXPORTS_W TickMeter
{
public:
//! the default constructor
CV_WRAP TickMeter()
{
- reset();
+ reset();
}
- /**
- starts counting ticks.
- */
+ //! starts counting ticks.
CV_WRAP void start()
{
- startTime = cv::getTickCount();
+ startTime = cv::getTickCount();
}
- /**
- stops counting ticks.
- */
+ //! stops counting ticks.
CV_WRAP void stop()
{
- int64 time = cv::getTickCount();
- if (startTime == 0)
- return;
- ++counter;
- sumTime += (time - startTime);
- startTime = 0;
+ int64 time = cv::getTickCount();
+ if (startTime == 0)
+ return;
+ ++counter;
+ sumTime += (time - startTime);
+ startTime = 0;
}
- /**
- returns counted ticks.
- */
+ //! returns counted ticks.
CV_WRAP int64 getTimeTicks() const
{
- return sumTime;
+ return sumTime;
}
- /**
- returns passed time in microseconds.
- */
+ //! returns passed time in microseconds.
CV_WRAP double getTimeMicro() const
{
- return getTimeMilli()*1e3;
+ return getTimeMilli()*1e3;
}
- /**
- returns passed time in milliseconds.
- */
+ //! returns passed time in milliseconds.
CV_WRAP double getTimeMilli() const
{
- return getTimeSec()*1e3;
+ return getTimeSec()*1e3;
}
- /**
- returns passed time in seconds.
- */
+ //! returns passed time in seconds.
CV_WRAP double getTimeSec() const
{
- return (double)getTimeTicks() / getTickFrequency();
+ return (double)getTimeTicks() / getTickFrequency();
}
- /**
- returns internal counter value.
- */
+ //! returns internal counter value.
CV_WRAP int64 getCounter() const
{
- return counter;
+ return counter;
}
- /**
- resets internal values.
- */
+ //! returns average FPS (frames per second) value.
+ CV_WRAP double getFPS() const
+ {
+ const double sec = getTimeSec();
+ if (sec < DBL_EPSILON)
+ return 0.;
+ return counter / sec;
+ }
+
+ //! returns average time in seconds
+ CV_WRAP double getAvgTimeSec() const
+ {
+ if (counter <= 0)
+ return 0.;
+ return getTimeSec() / counter;
+ }
+
+ //! returns average time in milliseconds
+ CV_WRAP double getAvgTimeMilli() const
+ {
+ return getAvgTimeSec() * 1e3;
+ }
+
+ //! resets internal values.
CV_WRAP void reset()
{
- startTime = 0;
- sumTime = 0;
- counter = 0;
+ startTime = 0;
+ sumTime = 0;
+ counter = 0;
}
private:
@@ -449,7 +438,7 @@ Returned value is a string containing space separated list of CPU features with
Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?`
*/
-CV_EXPORTS std::string getCPUFeaturesLine();
+CV_EXPORTS_W std::string getCPUFeaturesLine();
/** @brief Returns the number of logical CPUs available for the process.
*/
@@ -591,6 +580,7 @@ public:
*/
CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
+#ifdef CV_CXX11
class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody
{
private:
@@ -610,6 +600,7 @@ inline void parallel_for_(const Range& range, std::function<void(const Range&)>
{
parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes);
}
+#endif
/////////////////////////////// forEach method of cv::Mat ////////////////////////////
template<typename _Tp, typename Functor> inline
@@ -622,6 +613,7 @@ void Mat::forEach_impl(const Functor& operation) {
// or (_Tp&, void*) <- in case you don't need current idx.
}
+ CV_Assert(!empty());
CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX);
const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]);
@@ -710,10 +702,34 @@ void Mat::forEach_impl(const Functor& operation) {
/////////////////////////// Synchronization Primitives ///////////////////////////////
-#if !defined(_M_CEE)
-typedef std::recursive_mutex Mutex;
-typedef std::lock_guard<cv::Mutex> AutoLock;
-#endif
+class CV_EXPORTS Mutex
+{
+public:
+ Mutex();
+ ~Mutex();
+ Mutex(const Mutex& m);
+ Mutex& operator = (const Mutex& m);
+
+ void lock();
+ bool trylock();
+ void unlock();
+
+ struct Impl;
+protected:
+ Impl* impl;
+};
+
+class CV_EXPORTS AutoLock
+{
+public:
+ AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
+ ~AutoLock() { mutex->unlock(); }
+protected:
+ Mutex* mutex;
+private:
+ AutoLock(const AutoLock&);
+ AutoLock& operator = (const AutoLock&);
+};
/** @brief Designed for command line parsing
@@ -933,8 +949,8 @@ public:
void printErrors() const;
protected:
- void getByName(const String& name, bool space_delete, Param type, void* dst) const;
- void getByIndex(int index, bool space_delete, Param type, void* dst) const;
+ void getByName(const String& name, bool space_delete, int type, void* dst) const;
+ void getByIndex(int index, bool space_delete, int type, void* dst) const;
struct Impl;
Impl* impl;
@@ -1043,6 +1059,15 @@ template<typename _Tp, size_t fixed_size> inline size_t
AutoBuffer<_Tp, fixed_size>::size() const
{ return sz; }
+template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const
+{
+ return get<String>(index, space_delete);
+}
+template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const
+{
+ return get<String>(name, space_delete);
+}
+
//! @endcond
@@ -1205,4 +1230,8 @@ CV_EXPORTS int getThreadID();
#define CV_IMPL_ADD(impl)
#endif
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/core/core_c.h"
+#endif
+
#endif //OPENCV_CORE_UTILITY_H
diff --git a/include/opencv2/core/utils/allocator_stats.impl.hpp b/include/opencv2/core/utils/allocator_stats.impl.hpp
index b77493d..eb5ecde 100755
--- a/include/opencv2/core/utils/allocator_stats.impl.hpp
+++ b/include/opencv2/core/utils/allocator_stats.impl.hpp
@@ -7,10 +7,33 @@
#include "./allocator_stats.hpp"
+//#define OPENCV_DISABLE_ALLOCATOR_STATS
+
#ifdef CV_CXX11
+
#include <atomic>
+
+#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE
+#if defined(__GNUC__) && (\
+ (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \
+ (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) \
+ )
+#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int
+#endif
+#endif
+
+#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE
+#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE long long
+#endif
+
+#else // CV_CXX11
+
+#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE
+#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int // CV_XADD supports int only
#endif
+#endif // CV_CXX11
+
namespace cv { namespace utils {
#ifdef CV__ALLOCATOR_STATS_LOG
@@ -19,24 +42,32 @@ namespace {
class AllocatorStatistics : public AllocatorStatisticsInterface
{
-protected:
-#ifdef CV_CXX11
- std::atomic<long long> curr, total, total_allocs, peak;
-#else
- volatile long long curr, total, total_allocs, peak; // overflow is possible, CV_XADD operates with 'int' only
-#endif
+#ifdef OPENCV_DISABLE_ALLOCATOR_STATS
public:
- AllocatorStatistics()
-#ifndef CV_CXX11
- : curr(0), total(0), total_allocs(0), peak(0)
-#endif
- {}
+ AllocatorStatistics() {}
~AllocatorStatistics() CV_OVERRIDE {}
- // AllocatorStatisticsInterface
+ uint64_t getCurrentUsage() const CV_OVERRIDE { return 0; }
+ uint64_t getTotalUsage() const CV_OVERRIDE { return 0; }
+ uint64_t getNumberOfAllocations() const CV_OVERRIDE { return 0; }
+ uint64_t getPeakUsage() const CV_OVERRIDE { return 0; }
+
+ /** set peak usage = current usage */
+ void resetPeakUsage() CV_OVERRIDE {};
+
+ void onAllocate(size_t /*sz*/) {}
+ void onFree(size_t /*sz*/) {}
+
+#elif defined(CV_CXX11)
+
+protected:
+ typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t;
+ std::atomic<counter_t> curr, total, total_allocs, peak;
+public:
+ AllocatorStatistics() {}
+ ~AllocatorStatistics() CV_OVERRIDE {}
-#ifdef CV_CXX11
uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr.load(); }
uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total.load(); }
uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs.load(); }
@@ -52,7 +83,7 @@ public:
CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load()));
#endif
- long long new_curr = curr.fetch_add((long long)sz) + (long long)sz;
+ counter_t new_curr = curr.fetch_add((counter_t)sz) + (counter_t)sz;
// peak = std::max((uint64_t)peak, new_curr);
auto prev_peak = peak.load();
@@ -63,7 +94,7 @@ public:
}
// end of peak = max(...)
- total += (long long)sz;
+ total += (counter_t)sz;
total_allocs++;
}
void onFree(size_t sz)
@@ -71,10 +102,20 @@ public:
#ifdef CV__ALLOCATOR_STATS_LOG
CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load()));
#endif
- curr -= (long long)sz;
+ curr -= (counter_t)sz;
}
-#else
+#else // non C++11
+
+protected:
+ typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t;
+ volatile counter_t curr, total, total_allocs, peak; // overflow is possible, CV_XADD operates with 'int' only
+public:
+ AllocatorStatistics()
+ : curr(0), total(0), total_allocs(0), peak(0)
+ {}
+ ~AllocatorStatistics() CV_OVERRIDE {}
+
uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr; }
uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total; }
uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs; }
@@ -89,21 +130,21 @@ public:
CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr));
#endif
- uint64_t new_curr = (uint64_t)CV_XADD(&curr, (uint64_t)sz) + sz;
+ counter_t new_curr = (counter_t)CV_XADD(&curr, (counter_t)sz) + (counter_t)sz;
- peak = std::max((uint64_t)peak, new_curr); // non-thread safe
+ peak = std::max((counter_t)peak, new_curr); // non-thread safe
//CV_XADD(&total, (uint64_t)sz); // overflow with int, non-reliable...
total += sz;
- CV_XADD(&total_allocs, (uint64_t)1);
+ CV_XADD(&total_allocs, (counter_t)1);
}
void onFree(size_t sz)
{
#ifdef CV__ALLOCATOR_STATS_LOG
CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr));
#endif
- CV_XADD(&curr, (uint64_t)-sz);
+ CV_XADD(&curr, (counter_t)-sz);
}
#endif
};
diff --git a/include/opencv2/core/utils/filesystem.hpp b/include/opencv2/core/utils/filesystem.hpp
index a98d220..00b0dd1 100755
--- a/include/opencv2/core/utils/filesystem.hpp
+++ b/include/opencv2/core/utils/filesystem.hpp
@@ -26,10 +26,6 @@ CV_EXPORTS cv::String canonical(const cv::String& path);
/** Join path components */
CV_EXPORTS cv::String join(const cv::String& base, const cv::String& path);
-/** Get parent directory */
-CV_EXPORTS cv::String getParent(const cv::String &path);
-CV_EXPORTS std::wstring getParent(const std::wstring& path);
-
/**
* Generate a list of all files that match the globbing pattern.
*
diff --git a/include/opencv2/core/utils/logger.defines.hpp b/include/opencv2/core/utils/logger.defines.hpp
index 7d73f02..b2dfc41 100755
--- a/include/opencv2/core/utils/logger.defines.hpp
+++ b/include/opencv2/core/utils/logger.defines.hpp
@@ -17,26 +17,6 @@
#define CV_LOG_LEVEL_DEBUG 5 //!< Debug message. Disabled in the "Release" build.
#define CV_LOG_LEVEL_VERBOSE 6 //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build.
-namespace cv {
-namespace utils {
-namespace logging {
-
-//! Supported logging levels and their semantic
-enum LogLevel {
- LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call
- LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error)
- LOG_LEVEL_ERROR = 2, //!< Error message
- LOG_LEVEL_WARNING = 3, //!< Warning message
- LOG_LEVEL_INFO = 4, //!< Info message
- LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build.
- LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build.
-#ifndef CV_DOXYGEN
- ENUM_LOG_LEVEL_FORCE_INT = INT_MAX
-#endif
-};
-
-}}} // namespace
-
//! @}
#endif // OPENCV_LOGGER_DEFINES_HPP
diff --git a/include/opencv2/core/utils/logger.hpp b/include/opencv2/core/utils/logger.hpp
index bf73d9a..501d140 100755
--- a/include/opencv2/core/utils/logger.hpp
+++ b/include/opencv2/core/utils/logger.hpp
@@ -10,7 +10,6 @@
#include <limits.h> // INT_MAX
#include "logger.defines.hpp"
-#include "logtag.hpp"
namespace cv {
namespace utils {
@@ -19,6 +18,20 @@ namespace logging {
//! @addtogroup core_logging
//! @{
+//! Supported logging levels and their semantic
+enum LogLevel {
+ LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call
+ LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error)
+ LOG_LEVEL_ERROR = 2, //!< Error message
+ LOG_LEVEL_WARNING = 3, //!< Warning message
+ LOG_LEVEL_INFO = 4, //!< Info message
+ LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build.
+ LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build.
+#ifndef CV_DOXYGEN
+ ENUM_LOG_LEVEL_FORCE_INT = INT_MAX
+#endif
+};
+
/** Set global logging level
@return previous logging level
*/
@@ -26,39 +39,15 @@ CV_EXPORTS LogLevel setLogLevel(LogLevel logLevel);
/** Get global logging level */
CV_EXPORTS LogLevel getLogLevel();
-CV_EXPORTS void registerLogTag(cv::utils::logging::LogTag* plogtag);
-
-CV_EXPORTS void setLogTagLevel(const char* tag, cv::utils::logging::LogLevel level);
-
-CV_EXPORTS cv::utils::logging::LogLevel getLogTagLevel(const char* tag);
-
namespace internal {
-
-/** Get global log tag */
-CV_EXPORTS cv::utils::logging::LogTag* getGlobalLogTag();
-
/** Write log message */
CV_EXPORTS void writeLogMessage(LogLevel logLevel, const char* message);
-
-/** Write log message */
-CV_EXPORTS void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message);
-
} // namespace
-struct LogTagAuto
- : public LogTag
-{
- inline LogTagAuto(const char* _name, LogLevel _level)
- : LogTag(_name, _level)
- {
- registerLogTag(this);
- }
-};
-
/**
* \def CV_LOG_STRIP_LEVEL
*
- * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|SILENT] to compile out anything at that and before that logging level
+ * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|DISABLED] to compile out anything at that and before that logging level
*/
#ifndef CV_LOG_STRIP_LEVEL
# if defined NDEBUG
@@ -68,84 +57,101 @@ struct LogTagAuto
# endif
#endif
-#define CV_LOGTAG_PTR_CAST(expr) static_cast<const cv::utils::logging::LogTag*>(expr)
-
-// CV_LOGTAG_EXPAND_NAME is intended to be re-defined (undef and then define again)
-// to allows logging users to use a shorter name argument when calling
-// CV_LOG_WITH_TAG or its related macros such as CV_LOG_INFO.
-//
-// This macro is intended to modify the tag argument as a string (token), via
-// preprocessor token pasting or metaprogramming techniques. A typical usage
-// is to apply a prefix, such as
-// ...... #define CV_LOGTAG_EXPAND_NAME(tag) cv_logtag_##tag
-//
-// It is permitted to re-define to a hard-coded expression, ignoring the tag.
-// This would work identically like the CV_LOGTAG_FALLBACK macro.
-//
-// Important: When the logging macro is called with tag being NULL, a user-defined
-// CV_LOGTAG_EXPAND_NAME may expand it into cv_logtag_0, cv_logtag_NULL, or
-// cv_logtag_nullptr. Use with care. Also be mindful of C++ symbol redefinitions.
-//
-// If there is significant amount of logging code with tag being NULL, it is
-// recommended to use (re-define) CV_LOGTAG_FALLBACK to inject locally a default
-// tag at the beginning of a compilation unit, to minimize lines of code changes.
-//
-#define CV_LOGTAG_EXPAND_NAME(tag) tag
-
-// CV_LOGTAG_FALLBACK is intended to be re-defined (undef and then define again)
-// by any other compilation units to provide a log tag when the logging statement
-// does not specify one. The macro needs to expand into a C++ expression that can
-// be static_cast into (cv::utils::logging::LogTag*). Null (nullptr) is permitted.
-#define CV_LOGTAG_FALLBACK nullptr
-
-// CV_LOGTAG_GLOBAL is the tag used when a log tag is not specified in the logging
-// statement nor the compilation unit. The macro needs to expand into a C++
-// expression that can be static_cast into (cv::utils::logging::LogTag*). Must be
-// non-null. Do not re-define.
-#define CV_LOGTAG_GLOBAL cv::utils::logging::internal::getGlobalLogTag()
-
-#define CV_LOG_WITH_TAG(tag, msgLevel, ...) \
+#define CV_LOG_WITH_TAG(tag, msgLevel, extra_check0, extra_check1, msg_prefix, ...) \
for(;;) { \
- const auto cv_temp_msglevel = (cv::utils::logging::LogLevel)(msgLevel); \
- if (cv_temp_msglevel >= (CV_LOG_STRIP_LEVEL)) break; \
- auto cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_EXPAND_NAME(tag)); \
- if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_FALLBACK); \
- if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_GLOBAL); \
- if (cv_temp_logtagptr && (cv_temp_msglevel > cv_temp_logtagptr->level)) break; \
- std::stringstream cv_temp_logstream; \
- cv_temp_logstream << __VA_ARGS__; \
- cv::utils::logging::internal::writeLogMessageEx( \
- cv_temp_msglevel, \
- (cv_temp_logtagptr ? cv_temp_logtagptr->name : nullptr), \
- __FILE__, \
- __LINE__, \
- CV_Func, \
- cv_temp_logstream.str().c_str()); \
+ extra_check0; \
+ if (cv::utils::logging::getLogLevel() < msgLevel) break; \
+ extra_check1; \
+ std::stringstream ss; ss msg_prefix << __VA_ARGS__; \
+ cv::utils::logging::internal::writeLogMessage(msgLevel, ss.str().c_str()); \
break; \
}
-#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, __VA_ARGS__)
-#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, __VA_ARGS__)
-#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, __VA_ARGS__)
-#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, __VA_ARGS__)
-#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, __VA_ARGS__)
-#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), __VA_ARGS__)
+#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , , , __VA_ARGS__)
+#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , , , __VA_ARGS__)
+#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , , , __VA_ARGS__)
+#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , , , __VA_ARGS__)
+#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , , , __VA_ARGS__)
+#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_VERBOSE, , , << "[VERB" << v << ":" << cv::utils::getThreadID() << "] ", __VA_ARGS__)
#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO
-# undef CV_LOG_INFO
-# define CV_LOG_INFO(tag, ...)
+#undef CV_LOG_INFO
+#define CV_LOG_INFO(tag, ...)
#endif
#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG
-# undef CV_LOG_DEBUG
-# define CV_LOG_DEBUG(tag, ...)
+#undef CV_LOG_DEBUG
+#define CV_LOG_DEBUG(tag, ...)
#endif
#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE
-# undef CV_LOG_VERBOSE
-# define CV_LOG_VERBOSE(tag, v, ...)
+#undef CV_LOG_VERBOSE
+#define CV_LOG_VERBOSE(tag, v, ...)
#endif
+//! @cond IGNORED
+#define CV__LOG_ONCE_CHECK_PRE \
+ static bool _cv_log_once_ ## __LINE__ = false; \
+ if (_cv_log_once_ ## __LINE__) break;
+
+#define CV__LOG_ONCE_CHECK_POST \
+ _cv_log_once_ ## __LINE__ = true;
+
+#define CV__LOG_IF_CHECK(logging_cond) \
+ if (!(logging_cond)) break;
+
+//! @endcond
+
+
+// CV_LOG_ONCE_XXX macros
+
+#define CV_LOG_ONCE_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, , __VA_ARGS__)
+#define CV_LOG_ONCE_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, , __VA_ARGS__)
+#define CV_LOG_ONCE_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, , __VA_ARGS__)
+#define CV_LOG_ONCE_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, , __VA_ARGS__)
+#define CV_LOG_ONCE_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_VERBOSE, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, << "[VERB" << v << ":" << cv::utils::getThreadID() << "] ", __VA_ARGS__)
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO
+#undef CV_LOG_ONCE_INFO
+#define CV_LOG_ONCE_INFO(tag, ...)
+#endif
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG
+#undef CV_LOG_ONCE_DEBUG
+#define CV_LOG_ONCE_DEBUG(tag, ...)
+#endif
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE
+#undef CV_LOG_ONCE_VERBOSE
+#define CV_LOG_ONCE_VERBOSE(tag, v, ...)
+#endif
+
+
+// CV_LOG_IF_XXX macros
+
+#define CV_LOG_IF_FATAL(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , CV__LOG_IF_CHECK(logging_cond), , __VA_ARGS__)
+#define CV_LOG_IF_ERROR(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , CV__LOG_IF_CHECK(logging_cond), , __VA_ARGS__)
+#define CV_LOG_IF_WARNING(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , CV__LOG_IF_CHECK(logging_cond), , __VA_ARGS__)
+#define CV_LOG_IF_INFO(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , CV__LOG_IF_CHECK(logging_cond), , __VA_ARGS__)
+#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , CV__LOG_IF_CHECK(logging_cond), , __VA_ARGS__)
+#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_VERBOSE, , CV__LOG_IF_CHECK(logging_cond), << "[VERB" << v << ":" << cv::utils::getThreadID() << "] ", __VA_ARGS__)
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO
+#undef CV_LOG_IF_INFO
+#define CV_LOG_IF_INFO(tag, logging_cond, ...)
+#endif
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG
+#undef CV_LOG_IF_DEBUG
+#define CV_LOG_IF_DEBUG(tag, logging_cond, ...)
+#endif
+
+#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE
+#undef CV_LOG_IF_VERBOSE
+#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...)
+#endif
+
+
//! @}
}}} // namespace
diff --git a/include/opencv2/core/utils/logtag.hpp b/include/opencv2/core/utils/logtag.hpp
deleted file mode 100755
index 4089720..0000000
--- a/include/opencv2/core/utils/logtag.hpp
+++ /dev/null
@@ -1,28 +0,0 @@
-// This file is part of OpenCV project.
-// It is subject to the license terms in the LICENSE file found in the top-level directory
-// of this distribution and at http://opencv.org/license.html.
-
-#ifndef OPENCV_CORE_LOGTAG_HPP
-#define OPENCV_CORE_LOGTAG_HPP
-
-#include "opencv2/core/cvstd.hpp"
-#include "logger.defines.hpp"
-
-namespace cv {
-namespace utils {
-namespace logging {
-
-struct LogTag
-{
- const char* name;
- LogLevel level;
-
- inline LogTag(const char* _name, LogLevel _level)
- : name(_name)
- , level(_level)
- {}
-};
-
-}}}
-
-#endif
diff --git a/include/opencv2/core/utils/tls.hpp b/include/opencv2/core/utils/tls.hpp
index 697a7b0..b5f1138 100755
--- a/include/opencv2/core/utils/tls.hpp
+++ b/include/opencv2/core/utils/tls.hpp
@@ -38,7 +38,11 @@ protected:
virtual void* createDataInstance() const = 0;
virtual void deleteDataInstance(void* pData) const = 0;
+#if OPENCV_ABI_COMPATIBILITY > 300
private:
+#else
+public:
+#endif
int key_;
friend class cv::details::TlsStorage; // core/src/system.cpp
@@ -48,8 +52,8 @@ public:
private:
// Disable copy/assign (noncopyable pattern)
- TLSDataContainer(TLSDataContainer &) = delete;
- TLSDataContainer& operator =(const TLSDataContainer &) = delete;
+ TLSDataContainer(TLSDataContainer &);
+ TLSDataContainer& operator =(const TLSDataContainer &);
};
diff --git a/include/opencv2/core/version.hpp b/include/opencv2/core/version.hpp
index 29855b1..7b5bb2d 100755
--- a/include/opencv2/core/version.hpp
+++ b/include/opencv2/core/version.hpp
@@ -5,9 +5,9 @@
#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP
-#define CV_VERSION_MAJOR 4
-#define CV_VERSION_MINOR 2
-#define CV_VERSION_REVISION 0
+#define CV_VERSION_MAJOR 3
+#define CV_VERSION_MINOR 4
+#define CV_VERSION_REVISION 13
#define CV_VERSION_STATUS ""
#define CVAUX_STR_EXP(__A) #__A
diff --git a/include/opencv2/core/vsx_utils.hpp b/include/opencv2/core/vsx_utils.hpp
index 91669bf..d796251 100755
--- a/include/opencv2/core/vsx_utils.hpp
+++ b/include/opencv2/core/vsx_utils.hpp
@@ -110,9 +110,9 @@ VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); }
#if defined(__GNUG__) && !defined(__clang__)
// inline asm helper
-#define VSX_IMPL_1RG(rt, rto, rg, rgo, opc, fnm) \
-VSX_FINLINE(rt) fnm(const rg& a) \
-{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "="#rto (rs) : #rgo (a)); return rs; }
+#define VSX_IMPL_1RG(rt, rg, opc, fnm) \
+VSX_FINLINE(rt) fnm(const rg& a) \
+{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; }
#define VSX_IMPL_1VRG(rt, rg, opc, fnm) \
VSX_FINLINE(rt) fnm(const rg& a) \
@@ -233,6 +233,10 @@ VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \
#if __GNUG__ < 5
// vec_xxpermdi in gcc4 missing little-endian supports just like clang
# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1)))
+// same as vec_xxpermdi
+# undef vec_vbpermq
+ VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq)
+ VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq)
#else
# define vec_permi vec_xxpermdi
#endif // __GNUG__ < 5
@@ -257,44 +261,38 @@ VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp)
VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp)
// converts word and doubleword to double-precision
-#ifdef vec_ctd
-# undef vec_ctd
-#endif
-VSX_IMPL_1RG(vec_double2, wd, vec_int4, wa, xvcvsxwdp, vec_ctdo)
-VSX_IMPL_1RG(vec_double2, wd, vec_uint4, wa, xvcvuxwdp, vec_ctdo)
-VSX_IMPL_1RG(vec_double2, wd, vec_dword2, wi, xvcvsxddp, vec_ctd)
-VSX_IMPL_1RG(vec_double2, wd, vec_udword2, wi, xvcvuxddp, vec_ctd)
+#undef vec_ctd
+VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo)
+VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo)
+VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd)
+VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd)
// converts word and doubleword to single-precision
#undef vec_ctf
-VSX_IMPL_1RG(vec_float4, wf, vec_int4, wa, xvcvsxwsp, vec_ctf)
-VSX_IMPL_1RG(vec_float4, wf, vec_uint4, wa, xvcvuxwsp, vec_ctf)
-VSX_IMPL_1RG(vec_float4, wf, vec_dword2, wi, xvcvsxdsp, vec_ctfo)
-VSX_IMPL_1RG(vec_float4, wf, vec_udword2, wi, xvcvuxdsp, vec_ctfo)
+VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf)
+VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf)
+VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo)
+VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo)
// converts single and double precision to signed word
#undef vec_cts
-VSX_IMPL_1RG(vec_int4, wa, vec_double2, wd, xvcvdpsxws, vec_ctso)
-VSX_IMPL_1RG(vec_int4, wa, vec_float4, wf, xvcvspsxws, vec_cts)
+VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso)
+VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts)
// converts single and double precision to unsigned word
#undef vec_ctu
-VSX_IMPL_1RG(vec_uint4, wa, vec_double2, wd, xvcvdpuxws, vec_ctuo)
-VSX_IMPL_1RG(vec_uint4, wa, vec_float4, wf, xvcvspuxws, vec_ctu)
+VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo)
+VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu)
// converts single and double precision to signed doubleword
-#ifdef vec_ctsl
-# undef vec_ctsl
-#endif
-VSX_IMPL_1RG(vec_dword2, wi, vec_double2, wd, xvcvdpsxds, vec_ctsl)
-VSX_IMPL_1RG(vec_dword2, wi, vec_float4, wf, xvcvspsxds, vec_ctslo)
+#undef vec_ctsl
+VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl)
+VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo)
// converts single and double precision to unsigned doubleword
-#ifdef vec_ctul
-# undef vec_ctul
-#endif
-VSX_IMPL_1RG(vec_udword2, wi, vec_double2, wd, xvcvdpuxds, vec_ctul)
-VSX_IMPL_1RG(vec_udword2, wi, vec_float4, wf, xvcvspuxds, vec_ctulo)
+#undef vec_ctul
+VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul)
+VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo)
// just in case if GCC doesn't define it
#ifndef vec_xl
@@ -317,7 +315,7 @@ VSX_IMPL_1RG(vec_udword2, wi, vec_float4, wf, xvcvspuxds, vec_ctulo)
* Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837
*
* So we're not able to use inline asm and only use built-in functions that CLANG supports
- * and use __builtin_convertvector if clang missng any of vector conversions built-in functions
+ * and use __builtin_convertvector if clang missing any of vector conversions built-in functions
*
* todo: clang asm template bug is fixed, need to reconsider the current workarounds.
*/
@@ -491,7 +489,7 @@ VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo)
// Only for Eigen!
/*
* changing behavior of conversion intrinsics for gcc has effect on Eigen
- * so we redfine old behavior again only on gcc, clang
+ * so we redefine old behavior again only on gcc, clang
*/
#if !defined(__clang__) || __clang_major__ > 4
// ignoring second arg since Eigen only truncates toward zero
@@ -505,7 +503,7 @@ VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo)
VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts)
VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf)
// define vec_cts for converting double precision to signed doubleword
- // which isn't combitable with xlc but its okay since Eigen only use it for gcc
+ // which isn't compatible with xlc but its okay since Eigen only uses it for gcc
VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl)
#endif // Eigen
diff --git a/include/opencv2/core_detect.hpp b/include/opencv2/core_detect.hpp
deleted file mode 100755
index 46a5017..0000000
--- a/include/opencv2/core_detect.hpp
+++ /dev/null
@@ -1,149 +0,0 @@
-// This file is part of OpenCV project.
-// It is subject to the license terms in the LICENSE file found in the top-level directory
-// of this distribution and at http://opencv.org/license.html.
-#ifndef _OPENCV_DNN_OBJDETECT_CORE_DETECT_HPP_
-#define _OPENCV_DNN_OBJDETECT_CORE_DETECT_HPP_
-
-#include <vector>
-#include <memory>
-
-#include <opencv2/highgui.hpp>
-#include <opencv2/imgproc.hpp>
-
-/** @defgroup dnn_objdetect DNN used for object detection
-*/
-
-namespace cv
-{
-namespace dnn_objdetect
-{
-
- //! @addtogroup dnn_objdetect
- //! @{
-
- /** @brief Structure to hold the details pertaining to a single bounding box
- */
- typedef struct
- {
- int xmin, xmax;
- int ymin, ymax;
- size_t class_idx;
- std::string label_name;
- double class_prob;
- } object;
-
-
- /** @brief A class to post process model predictions
- */
- class CV_EXPORTS InferBbox
- {
- public:
- /** @brief Default constructer
- @param _delta_bbox Blob containing relative coordinates of bounding boxes
- @param _class_scores Blob containing the probability values of each class
- @param _conf_scores Blob containing the confidence scores
- */
- InferBbox(Mat _delta_bbox, Mat _class_scores, Mat _conf_scores);
-
- /** @brief Filters the bounding boxes.
- */
- void filter(double thresh = 0.8);
-
- /** @brief Vector which holds the final detections of the model
- */
- std::vector<object> detections;
-
- protected:
- /** @brief Transform relative coordinates from ConvDet to bounding box coordinates
- @param bboxes Vector to hold the predicted bounding boxes
- */
- void transform_bboxes(std::vector<std::vector<double> > *bboxes);
-
- /** @brief Computes final probability values of each bounding box
- @param final_probs Vector to hold the probability values
- */
- void final_probability_dist(std::vector<std::vector<double> > *final_probs);
-
- /** @brief Transform bounding boxes from [x, y, h, w] to [xmin, ymin, xmax, ymax]
- @param pre Vector conatining initial co-ordinates
- @param post Vector containing the transformed co-ordinates
- */
- void transform_bboxes_inv(std::vector<std::vector<double> > *pre,
- std::vector<std::vector<double> > *post);
-
- /** @brief Ensures that the bounding box values are within image boundaries
- @param min_max_boxes Vector containing bounding boxes of the form [xmin, ymin, xmax, ymax]
- */
- void assert_predictions(std::vector<std::vector<double> > *min_max_boxes);
-
- /** @brief Filter top `n` predictions
- @param probs Final probability values of bounding boxes
- @param boxes Predicted bounding box co-ordinates
- @param top_n_boxes Contains bounding box co-ordinates of top `n` boxes
- @param top_n_idxs Containes class indices of top `n` bounding boxes
- @param top_n_probs Contains probability values of top `n` bounding boxes
- */
- void filter_top_n(std::vector<std::vector<double> > *probs,
- std::vector<std::vector<double> > *boxes,
- std::vector<std::vector<double> > &top_n_boxes,
- std::vector<size_t> &top_n_idxs,
- std::vector<double> &top_n_probs);
-
- /** @brief Wrapper to apply Non-Maximal Supression
- @param top_n_boxes Contains bounding box co-ordinates of top `n` boxes
- @param top_n_idxs Containes class indices of top `n` bounding boxes
- @param top_n_probs Contains probability values of top `n` bounding boxes
- */
- void nms_wrapper(std::vector<std::vector<double> > &top_n_boxes,
- std::vector<size_t> &top_n_idxs,
- std::vector<double> &top_n_probs);
-
- /** @brief Applies Non-Maximal Supression
- @param boxes Bounding box co-ordinates belonging to one class
- @param probs Probability values of boxes belonging to one class
- */
- std::vector<bool> non_maximal_suppression(std::vector<std::vector<double> >
- *boxes, std::vector<double> *probs);
-
- /** @brief Computes intersection over union of bounding boxes
- @param boxes Vector of bounding box co-ordinates
- @param base_box Base box wrt which IOU is calculated
- @param iou Vector to store IOU values
- */
- void intersection_over_union(std::vector<std::vector<double> > *boxes,
- std::vector<double> *base_box, std::vector<double> *iou);
-
- static inline bool comparator (std::pair<double, size_t> l1,
- std::pair<double, size_t> l2)
- {
- return l1.first > l2.first;
- }
-
- private:
- Mat delta_bbox;
- Mat class_scores;
- Mat conf_scores;
-
- unsigned int image_width;
- unsigned int image_height;
-
- unsigned int W, H;
- std::vector<std::vector<double> > anchors_values;
- std::vector<std::pair<double, double> > anchor_center;
- std::vector<std::pair<double, double> > anchor_shapes;
-
- std::vector<std::string> label_map;
-
- unsigned int num_classes;
- unsigned int anchors_per_grid;
- size_t anchors;
- double intersection_thresh;
- double nms_intersection_thresh;
- size_t n_top_detections;
- double epsilon;
- };
-
- //! @}
-} // namespace dnn_objdetect
-} // namespace cv
-#endif
diff --git a/include/opencv2/features2d.hpp b/include/opencv2/features2d.hpp
index 7b9f3a6..293b5be 100755
--- a/include/opencv2/features2d.hpp
+++ b/include/opencv2/features2d.hpp
@@ -244,6 +244,97 @@ typedef Feature2D DescriptorExtractor;
//! @addtogroup features2d_main
//! @{
+
+/** @brief Class for implementing the wrapper which makes detectors and extractors to be affine invariant,
+described as ASIFT in @cite YM11 .
+*/
+class CV_EXPORTS_W AffineFeature : public Feature2D
+{
+public:
+ /**
+ @param backend The detector/extractor you want to use as backend.
+ @param maxTilt The highest power index of tilt factor. 5 is used in the paper as tilt sampling range n.
+ @param minTilt The lowest power index of tilt factor. 0 is used in the paper.
+ @param tiltStep Tilt sampling step \f$\delta_t\f$ in Algorithm 1 in the paper.
+ @param rotateStepBase Rotation sampling step factor b in Algorithm 1 in the paper.
+ */
+ CV_WRAP static Ptr<AffineFeature> create(const Ptr<Feature2D>& backend,
+ int maxTilt = 5, int minTilt = 0, float tiltStep = 1.4142135623730951f, float rotateStepBase = 72);
+
+ CV_WRAP virtual void setViewParams(const std::vector<float>& tilts, const std::vector<float>& rolls) = 0;
+ CV_WRAP virtual void getViewParams(std::vector<float>& tilts, std::vector<float>& rolls) const = 0;
+ CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
+};
+
+typedef AffineFeature AffineFeatureDetector;
+typedef AffineFeature AffineDescriptorExtractor;
+
+
+/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform
+(SIFT) algorithm by D. Lowe @cite Lowe04 .
+*/
+class CV_EXPORTS_W SIFT : public Feature2D
+{
+public:
+ /**
+ @param nfeatures The number of best features to retain. The features are ranked by their scores
+ (measured in SIFT algorithm as the local contrast)
+
+ @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The
+ number of octaves is computed automatically from the image resolution.
+
+ @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform
+ (low-contrast) regions. The larger the threshold, the less features are produced by the detector.
+
+ @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When
+ nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set
+ this argument to 0.09.
+
+ @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning
+ is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are
+ filtered out (more features are retained).
+
+ @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image
+ is captured with a weak camera with soft lenses, you might want to reduce the number.
+ */
+ CV_WRAP static Ptr<SIFT> create(int nfeatures = 0, int nOctaveLayers = 3,
+ double contrastThreshold = 0.04, double edgeThreshold = 10,
+ double sigma = 1.6);
+
+ /** @brief Create SIFT with specified descriptorType.
+ @param nfeatures The number of best features to retain. The features are ranked by their scores
+ (measured in SIFT algorithm as the local contrast)
+
+ @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The
+ number of octaves is computed automatically from the image resolution.
+
+ @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform
+ (low-contrast) regions. The larger the threshold, the less features are produced by the detector.
+
+ @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When
+ nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set
+ this argument to 0.09.
+
+ @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning
+ is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are
+ filtered out (more features are retained).
+
+ @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image
+ is captured with a weak camera with soft lenses, you might want to reduce the number.
+
+ @param descriptorType The type of descriptors. Only CV_32F and CV_8U are supported.
+ */
+ CV_WRAP static Ptr<SIFT> create(int nfeatures, int nOctaveLayers,
+ double contrastThreshold, double edgeThreshold,
+ double sigma, int descriptorType);
+
+ CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
+};
+
+typedef SIFT SiftFeatureDetector;
+typedef SIFT SiftDescriptorExtractor;
+
+
/** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 .
*/
class CV_EXPORTS_W BRISK : public Feature2D
@@ -289,18 +380,6 @@ public:
const std::vector<int> &numberList, float dMax=5.85f, float dMin=8.2f,
const std::vector<int>& indexChange=std::vector<int>());
CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
-
- /** @brief Set detection threshold.
- @param threshold AGAST detection threshold score.
- */
- CV_WRAP virtual void setThreshold(int threshold) { CV_UNUSED(threshold); return; }
- CV_WRAP virtual int getThreshold() const { return -1; }
-
- /** @brief Set detection octaves.
- @param octaves detection octaves. Use 0 to do single scale.
- */
- CV_WRAP virtual void setOctaves(int octaves) { CV_UNUSED(octaves); return; }
- CV_WRAP virtual int getOctaves() const { return -1; }
};
/** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor
@@ -313,8 +392,7 @@ k-tuples) are rotated according to the measured orientation).
class CV_EXPORTS_W ORB : public Feature2D
{
public:
- enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 };
- static const int kBytes = 32;
+ enum { kBytes = 32, HARRIS_SCORE=0, FAST_SCORE=1 };
/** @brief The ORB constructor
@@ -348,7 +426,7 @@ public:
@param fastThreshold the fast threshold
*/
CV_WRAP static Ptr<ORB> create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31,
- int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20);
+ int firstLevel=0, int WTA_K=2, int scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20);
CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0;
CV_WRAP virtual int getMaxFeatures() const = 0;
@@ -368,8 +446,8 @@ public:
CV_WRAP virtual void setWTA_K(int wta_k) = 0;
CV_WRAP virtual int getWTA_K() const = 0;
- CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0;
- CV_WRAP virtual ORB::ScoreType getScoreType() const = 0;
+ CV_WRAP virtual void setScoreType(int scoreType) = 0;
+ CV_WRAP virtual int getScoreType() const = 0;
CV_WRAP virtual void setPatchSize(int patchSize) = 0;
CV_WRAP virtual int getPatchSize() const = 0;
@@ -398,7 +476,7 @@ code which is distributed under GPL.
class CV_EXPORTS_W MSER : public Feature2D
{
public:
- /** @brief Full consturctor for %MSER detector
+ /** @brief Full constructor for %MSER detector
@param _delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$
@param _min_area prune the area which smaller than minArea
@@ -439,41 +517,6 @@ public:
CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
};
-//! @} features2d_main
-
-//! @addtogroup features2d_main
-//! @{
-
-/** @brief Wrapping class for feature detection using the FAST method. :
- */
-class CV_EXPORTS_W FastFeatureDetector : public Feature2D
-{
-public:
- enum DetectorType
- {
- TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2
- };
- enum
- {
- THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002
- };
-
-
- CV_WRAP static Ptr<FastFeatureDetector> create( int threshold=10,
- bool nonmaxSuppression=true,
- FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 );
-
- CV_WRAP virtual void setThreshold(int threshold) = 0;
- CV_WRAP virtual int getThreshold() const = 0;
-
- CV_WRAP virtual void setNonmaxSuppression(bool f) = 0;
- CV_WRAP virtual bool getNonmaxSuppression() const = 0;
-
- CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0;
- CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0;
- CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
-};
-
/** @overload */
CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
int threshold, bool nonmaxSuppression=true );
@@ -492,36 +535,32 @@ FastFeatureDetector::TYPE_5_8
Detects corners using the FAST algorithm by @cite Rosten06 .
-@note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8,
-cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner
-detection, use cv.FAST.detect() method.
+@note In Python API, types are given as cv2.FAST_FEATURE_DETECTOR_TYPE_5_8,
+cv2.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv2.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner
+detection, use cv2.FAST.detect() method.
*/
CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
- int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type );
+ int threshold, bool nonmaxSuppression, int type );
//! @} features2d_main
//! @addtogroup features2d_main
//! @{
-/** @brief Wrapping class for feature detection using the AGAST method. :
+/** @brief Wrapping class for feature detection using the FAST method. :
*/
-class CV_EXPORTS_W AgastFeatureDetector : public Feature2D
+class CV_EXPORTS_W FastFeatureDetector : public Feature2D
{
public:
- enum DetectorType
- {
- AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3,
- };
-
enum
{
- THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001,
+ TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2,
+ THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002,
};
- CV_WRAP static Ptr<AgastFeatureDetector> create( int threshold=10,
- bool nonmaxSuppression=true,
- AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16);
+ CV_WRAP static Ptr<FastFeatureDetector> create( int threshold=10,
+ bool nonmaxSuppression=true,
+ int type=FastFeatureDetector::TYPE_9_16 );
CV_WRAP virtual void setThreshold(int threshold) = 0;
CV_WRAP virtual int getThreshold() const = 0;
@@ -529,8 +568,8 @@ public:
CV_WRAP virtual void setNonmaxSuppression(bool f) = 0;
CV_WRAP virtual bool getNonmaxSuppression() const = 0;
- CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0;
- CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0;
+ CV_WRAP virtual void setType(int type) = 0;
+ CV_WRAP virtual int getType() const = 0;
CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
};
@@ -557,7 +596,37 @@ Detects corners using the AGAST algorithm by @cite mair2010_agast .
*/
CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints,
- int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type );
+ int threshold, bool nonmaxSuppression, int type );
+//! @} features2d_main
+
+//! @addtogroup features2d_main
+//! @{
+
+/** @brief Wrapping class for feature detection using the AGAST method. :
+ */
+class CV_EXPORTS_W AgastFeatureDetector : public Feature2D
+{
+public:
+ enum
+ {
+ AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3,
+ THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001,
+ };
+
+ CV_WRAP static Ptr<AgastFeatureDetector> create( int threshold=10,
+ bool nonmaxSuppression=true,
+ int type=AgastFeatureDetector::OAST_9_16 );
+
+ CV_WRAP virtual void setThreshold(int threshold) = 0;
+ CV_WRAP virtual int getThreshold() const = 0;
+
+ CV_WRAP virtual void setNonmaxSuppression(bool f) = 0;
+ CV_WRAP virtual bool getNonmaxSuppression() const = 0;
+
+ CV_WRAP virtual void setType(int type) = 0;
+ CV_WRAP virtual int getType() const = 0;
+ CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
+};
/** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. :
*/
@@ -669,7 +738,7 @@ F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on
class CV_EXPORTS_W KAZE : public Feature2D
{
public:
- enum DiffusivityType
+ enum
{
DIFF_PM_G1 = 0,
DIFF_PM_G2 = 1,
@@ -690,7 +759,7 @@ public:
CV_WRAP static Ptr<KAZE> create(bool extended=false, bool upright=false,
float threshold = 0.001f,
int nOctaves = 4, int nOctaveLayers = 4,
- KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2);
+ int diffusivity = KAZE::DIFF_PM_G2);
CV_WRAP virtual void setExtended(bool extended) = 0;
CV_WRAP virtual bool getExtended() const = 0;
@@ -707,8 +776,8 @@ public:
CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0;
CV_WRAP virtual int getNOctaveLayers() const = 0;
- CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0;
- CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0;
+ CV_WRAP virtual void setDiffusivity(int diff) = 0;
+ CV_WRAP virtual int getDiffusivity() const = 0;
CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
};
@@ -732,7 +801,7 @@ class CV_EXPORTS_W AKAZE : public Feature2D
{
public:
// AKAZE descriptor type
- enum DescriptorType
+ enum
{
DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation
DESCRIPTOR_KAZE = 3,
@@ -752,13 +821,13 @@ public:
@param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or
DIFF_CHARBONNIER
*/
- CV_WRAP static Ptr<AKAZE> create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB,
+ CV_WRAP static Ptr<AKAZE> create(int descriptor_type=AKAZE::DESCRIPTOR_MLDB,
int descriptor_size = 0, int descriptor_channels = 3,
float threshold = 0.001f, int nOctaves = 4,
- int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2);
+ int nOctaveLayers = 4, int diffusivity = KAZE::DIFF_PM_G2);
- CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0;
- CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0;
+ CV_WRAP virtual void setDescriptorType(int dtype) = 0;
+ CV_WRAP virtual int getDescriptorType() const = 0;
CV_WRAP virtual void setDescriptorSize(int dsize) = 0;
CV_WRAP virtual int getDescriptorSize() const = 0;
@@ -775,8 +844,8 @@ public:
CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0;
CV_WRAP virtual int getNOctaveLayers() const = 0;
- CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0;
- CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0;
+ CV_WRAP virtual void setDiffusivity(int diff) = 0;
+ CV_WRAP virtual int getDiffusivity() const = 0;
CV_WRAP virtual String getDefaultName() const CV_OVERRIDE;
};
@@ -803,7 +872,7 @@ template<> struct Accumulator<short> { typedef float Type; };
template<class T>
struct CV_EXPORTS SL2
{
- static const NormTypes normType = NORM_L2SQR;
+ enum { normType = NORM_L2SQR };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
@@ -819,7 +888,7 @@ struct CV_EXPORTS SL2
template<class T>
struct L2
{
- static const NormTypes normType = NORM_L2;
+ enum { normType = NORM_L2 };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
@@ -835,7 +904,7 @@ struct L2
template<class T>
struct L1
{
- static const NormTypes normType = NORM_L1;
+ enum { normType = NORM_L1 };
typedef T ValueType;
typedef typename Accumulator<T>::Type ResultType;
@@ -860,7 +929,7 @@ an image set.
class CV_EXPORTS_W DescriptorMatcher : public Algorithm
{
public:
- enum MatcherType
+ enum
{
FLANNBASED = 1,
BRUTEFORCE = 2,
@@ -869,7 +938,6 @@ public:
BRUTEFORCE_HAMMINGLUT = 5,
BRUTEFORCE_SL2 = 6
};
-
virtual ~DescriptorMatcher();
/** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor
@@ -1047,7 +1115,7 @@ public:
*/
CV_WRAP static Ptr<DescriptorMatcher> create( const String& descriptorMatcherType );
- CV_WRAP static Ptr<DescriptorMatcher> create( const DescriptorMatcher::MatcherType& matcherType );
+ CV_WRAP static Ptr<DescriptorMatcher> create( int matcherType );
// see corresponding cv::Algorithm method
@@ -1202,20 +1270,20 @@ protected:
//! @addtogroup features2d_draw
//! @{
-enum struct DrawMatchesFlags
+struct CV_EXPORTS DrawMatchesFlags
{
- DEFAULT = 0, //!< Output image matrix will be created (Mat::create),
- //!< i.e. existing memory of output image may be reused.
- //!< Two source image, matches and single keypoints will be drawn.
- //!< For each keypoint only the center point will be drawn (without
- //!< the circle around keypoint with keypoint size and orientation).
- DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create).
- //!< Matches will be drawn on existing content of output image.
- NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn.
- DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and
- //!< orientation will be drawn.
+ enum{ DEFAULT = 0, //!< Output image matrix will be created (Mat::create),
+ //!< i.e. existing memory of output image may be reused.
+ //!< Two source image, matches and single keypoints will be drawn.
+ //!< For each keypoint only the center point will be drawn (without
+ //!< the circle around keypoint with keypoint size and orientation).
+ DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create).
+ //!< Matches will be drawn on existing content of output image.
+ NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn.
+ DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and
+ //!< orientation will be drawn.
+ };
};
-CV_ENUM_FLAGS(DrawMatchesFlags)
/** @brief Draws keypoints.
@@ -1228,12 +1296,12 @@ output image. See possible flags bit values below.
DrawMatchesFlags. See details above in drawMatches .
@note
-For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT,
-cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG,
-cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS
+For Python API, flags are modified as cv2.DRAW_MATCHES_FLAGS_DEFAULT,
+cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv2.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG,
+cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS
*/
CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector<KeyPoint>& keypoints, InputOutputArray outImage,
- const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
+ const Scalar& color=Scalar::all(-1), int flags=DrawMatchesFlags::DEFAULT );
/** @brief Draws the found matches of keypoints from two images.
@@ -1261,14 +1329,14 @@ CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector<KeyPoint>& key
InputArray img2, const std::vector<KeyPoint>& keypoints2,
const std::vector<DMatch>& matches1to2, InputOutputArray outImg,
const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
- const std::vector<char>& matchesMask=std::vector<char>(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
+ const std::vector<char>& matchesMask=std::vector<char>(), int flags=DrawMatchesFlags::DEFAULT );
/** @overload */
CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector<KeyPoint>& keypoints1,
InputArray img2, const std::vector<KeyPoint>& keypoints2,
const std::vector<std::vector<DMatch> >& matches1to2, InputOutputArray outImg,
const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1),
- const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT );
+ const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), int flags=DrawMatchesFlags::DEFAULT );
//! @} features2d_draw
diff --git a/include/opencv2/flann.hpp b/include/opencv2/flann.hpp
index 887759e..5c52bfe 100755
--- a/include/opencv2/flann.hpp
+++ b/include/opencv2/flann.hpp
@@ -95,6 +95,8 @@ using ::cvflann::MaxDistance;
using ::cvflann::HammingLUT;
using ::cvflann::Hamming;
using ::cvflann::Hamming2;
+using ::cvflann::DNAmmingLUT;
+using ::cvflann::DNAmming2;
using ::cvflann::HistIntersectionDistance;
using ::cvflann::HellingerDistance;
using ::cvflann::ChiSquareDistance;
@@ -131,6 +133,14 @@ performed using library calls, if available. Lookup table implementation is used
cv::flann::Hamming2 - %Hamming distance functor. Population count is
implemented in 12 arithmetic operations (one of which is multiplication).
+cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison.
+As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits,
+it counts the bits pairs differences between two sequences using a lookup table implementation.
+
+cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison.
+Bases differences count are vectorised thanks to arithmetic operations using standard
+registers (AVX2 and AVX-512 should come in a near future).
+
cv::flann::HistIntersectionDistance - The histogram
intersection distance functor.
@@ -191,8 +201,28 @@ public:
KDTreeIndexParams( int trees = 4 );
};
@endcode
+ - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed
+ will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers
+ are picked among the points without further refinement of their position.
+ This algorithm fits both floating, integer and binary vectors. :
+ @code
+ struct HierarchicalClusteringIndexParams : public IndexParams
+ {
+ HierarchicalClusteringIndexParams(
+ int branching = 32,
+ flann_centers_init_t centers_init = CENTERS_RANDOM,
+ int trees = 4,
+ int leaf_size = 100);
+
+ };
+ @endcode
- **KMeansIndexParams** When passing an object of this type the index constructed will be a
- hierarchical k-means tree. :
+ hierarchical k-means tree (one tree by default), dividing each set of points into n clusters
+ whose barycenters are refined iteratively.
+ Note that this algorithm has been extended to the support of binary vectors as an alternative
+ to LSH when knn search speed is the criterium. It will also outperform LSH when processing
+ directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values
+ for most of the dimensions. It is recommended to set more than one tree with binary data. :
@code
struct KMeansIndexParams : public IndexParams
{
@@ -201,6 +231,13 @@ public:
int iterations = 11,
flann_centers_init_t centers_init = CENTERS_RANDOM,
float cb_index = 0.2 );
+
+ KMeansIndexParams(
+ int branching,
+ int iterations,
+ flann_centers_init_t centers_init,
+ float cb_index,
+ int trees );
};
@endcode
- **CompositeIndexParams** When using a parameters object of this type the index created
@@ -219,7 +256,8 @@ public:
- **LshIndexParams** When using a parameters object of this type the index created uses
multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search
by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd
- International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007) :
+ International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007).
+ This algorithm is designed for binary vectors. :
@code
struct LshIndexParams : public IndexParams
{
@@ -536,7 +574,7 @@ private:
@param features The points to be clustered. The matrix must have elements of type
Distance::ElementType.
@param centers The centers of the clusters obtained. The matrix must have type
-Distance::ResultType. The number of rows in this matrix represents the number of clusters desired,
+Distance::CentersType. The number of rows in this matrix represents the number of clusters desired,
however, because of the way the cut in the hierarchical tree is chosen, the number of clusters
computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of
clusters desired, where branching is the tree's branching factor (see description of the
@@ -553,15 +591,15 @@ int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::K
Distance d = Distance())
{
typedef typename Distance::ElementType ElementType;
- typedef typename Distance::ResultType DistanceType;
+ typedef typename Distance::CentersType CentersType;
CV_Assert(features.type() == CvType<ElementType>::type());
CV_Assert(features.isContinuous());
::cvflann::Matrix<ElementType> m_features((ElementType*)features.ptr<ElementType>(0), features.rows, features.cols);
- CV_Assert(centers.type() == CvType<DistanceType>::type());
+ CV_Assert(centers.type() == CvType<CentersType>::type());
CV_Assert(centers.isContinuous());
- ::cvflann::Matrix<DistanceType> m_centers((DistanceType*)centers.ptr<DistanceType>(0), centers.rows, centers.cols);
+ ::cvflann::Matrix<CentersType> m_centers((CentersType*)centers.ptr<CentersType>(0), centers.rows, centers.cols);
return ::cvflann::hierarchicalClustering<Distance>(m_features, m_centers, params, d);
}
diff --git a/include/opencv2/flann/all_indices.h b/include/opencv2/flann/all_indices.h
index ba5a2f2..03877ab 100755
--- a/include/opencv2/flann/all_indices.h
+++ b/include/opencv2/flann/all_indices.h
@@ -82,7 +82,7 @@ struct index_creator
nnIndex = new LshIndex<Distance>(dataset, params, distance);
break;
default:
- throw FLANNException("Unknown index type");
+ FLANN_THROW(cv::Error::StsBadArg, "Unknown index type");
}
return nnIndex;
@@ -111,7 +111,7 @@ struct index_creator<False,VectorSpace,Distance>
nnIndex = new LshIndex<Distance>(dataset, params, distance);
break;
default:
- throw FLANNException("Unknown index type");
+ FLANN_THROW(cv::Error::StsBadArg, "Unknown index type");
}
return nnIndex;
@@ -130,6 +130,9 @@ struct index_creator<False,False,Distance>
case FLANN_INDEX_LINEAR:
nnIndex = new LinearIndex<Distance>(dataset, params, distance);
break;
+ case FLANN_INDEX_KMEANS:
+ nnIndex = new KMeansIndex<Distance>(dataset, params, distance);
+ break;
case FLANN_INDEX_HIERARCHICAL:
nnIndex = new HierarchicalClusteringIndex<Distance>(dataset, params, distance);
break;
@@ -137,7 +140,7 @@ struct index_creator<False,False,Distance>
nnIndex = new LshIndex<Distance>(dataset, params, distance);
break;
default:
- throw FLANNException("Unknown index type");
+ FLANN_THROW(cv::Error::StsBadArg, "Unknown index type");
}
return nnIndex;
diff --git a/include/opencv2/flann/autotuned_index.h b/include/opencv2/flann/autotuned_index.h
index eb4554f..d90f739 100755
--- a/include/opencv2/flann/autotuned_index.h
+++ b/include/opencv2/flann/autotuned_index.h
@@ -34,7 +34,6 @@
#include <sstream>
-#include "general.h"
#include "nn_index.h"
#include "ground_truth.h"
#include "index_testing.h"
@@ -497,7 +496,7 @@ private:
const int nn = 1;
const size_t SAMPLE_COUNT = 1000;
- assert(bestIndex_ != NULL); // must have a valid index
+ CV_Assert(bestIndex_ != NULL && "Requires a valid index"); // must have a valid index
float speedup = 0;
diff --git a/include/opencv2/flann/composite_index.h b/include/opencv2/flann/composite_index.h
index bcf0827..f1af41a 100755
--- a/include/opencv2/flann/composite_index.h
+++ b/include/opencv2/flann/composite_index.h
@@ -33,7 +33,6 @@
//! @cond IGNORED
-#include "general.h"
#include "nn_index.h"
#include "kdtree_index.h"
#include "kmeans_index.h"
diff --git a/include/opencv2/flann/defines.h b/include/opencv2/flann/defines.h
index 884c600..8ab8329 100755
--- a/include/opencv2/flann/defines.h
+++ b/include/opencv2/flann/defines.h
@@ -128,6 +128,7 @@ enum flann_distance_t
FLANN_DIST_KULLBACK_LEIBLER = 8,
FLANN_DIST_KL = 8,
FLANN_DIST_HAMMING = 9,
+ FLANN_DIST_DNAMMING = 10,
// deprecated constants, should use the FLANN_DIST_* ones instead
EUCLIDEAN = 1,
diff --git a/include/opencv2/flann/dist.h b/include/opencv2/flann/dist.h
index 07a1cc2..608f8a5 100755
--- a/include/opencv2/flann/dist.h
+++ b/include/opencv2/flann/dist.h
@@ -1,4 +1,4 @@
-/***********************************************************************
+ο»Ώ/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
@@ -68,6 +68,63 @@ inline float abs<float>(float x) { return fabsf(x); }
template<>
inline double abs<double>(double x) { return fabs(x); }
+
+template<typename TargetType>
+inline TargetType round(float x) { return static_cast<TargetType>(x); }
+
+template<>
+inline unsigned int round<unsigned int>(float x) { return static_cast<unsigned int>(x + 0.5f); }
+
+template<>
+inline unsigned short round<unsigned short>(float x) { return static_cast<unsigned short>(x + 0.5f); }
+
+template<>
+inline unsigned char round<unsigned char>(float x) { return static_cast<unsigned char>(x + 0.5f); }
+
+template<>
+inline long long round<long long>(float x) { return static_cast<long long>(x + 0.5f); }
+
+template<>
+inline long round<long>(float x) { return static_cast<long>(x + 0.5f); }
+
+template<>
+inline int round<int>(float x) { return static_cast<int>(x + 0.5f) - (x<0); }
+
+template<>
+inline short round<short>(float x) { return static_cast<short>(x + 0.5f) - (x<0); }
+
+template<>
+inline char round<char>(float x) { return static_cast<char>(x + 0.5f) - (x<0); }
+
+
+template<typename TargetType>
+inline TargetType round(double x) { return static_cast<TargetType>(x); }
+
+template<>
+inline unsigned int round<unsigned int>(double x) { return static_cast<unsigned int>(x + 0.5); }
+
+template<>
+inline unsigned short round<unsigned short>(double x) { return static_cast<unsigned short>(x + 0.5); }
+
+template<>
+inline unsigned char round<unsigned char>(double x) { return static_cast<unsigned char>(x + 0.5); }
+
+template<>
+inline long long round<long long>(double x) { return static_cast<long long>(x + 0.5); }
+
+template<>
+inline long round<long>(double x) { return static_cast<long>(x + 0.5); }
+
+template<>
+inline int round<int>(double x) { return static_cast<int>(x + 0.5) - (x<0); }
+
+template<>
+inline short round<short>(double x) { return static_cast<short>(x + 0.5) - (x<0); }
+
+template<>
+inline char round<char>(double x) { return static_cast<char>(x + 0.5) - (x<0); }
+
+
template<typename T>
struct Accumulator { typedef T Type; };
template<>
@@ -88,13 +145,57 @@ struct Accumulator<int> { typedef float Type; };
class True
{
+public:
+ static const bool val = true;
};
class False
{
+public:
+ static const bool val = false;
};
+/*
+ * This is a "zero iterator". It basically behaves like a zero filled
+ * array to all algorithms that use arrays as iterators (STL style).
+ * It's useful when there's a need to compute the distance between feature
+ * and origin it and allows for better compiler optimisation than using a
+ * zero-filled array.
+ */
+template <typename T>
+struct ZeroIterator
+{
+
+ T operator*()
+ {
+ return 0;
+ }
+
+ T operator[](int)
+ {
+ return 0;
+ }
+
+ const ZeroIterator<T>& operator ++()
+ {
+ return *this;
+ }
+
+ ZeroIterator<T> operator ++(int)
+ {
+ return *this;
+ }
+
+ ZeroIterator<T>& operator+=(int)
+ {
+ return *this;
+ }
+
+};
+
+
+
/**
* Squared Euclidean distance functor.
*
@@ -109,6 +210,7 @@ struct L2_Simple
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
template <typename Iterator1, typename Iterator2>
ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
@@ -142,6 +244,7 @@ struct L2
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the squared Euclidean distance between two vectors.
@@ -207,6 +310,7 @@ struct L1
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the Manhattan (L_1) distance between two vectors.
@@ -264,6 +368,7 @@ struct MinkowskiDistance
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
int order;
@@ -328,6 +433,7 @@ struct MaxDistance
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the max distance (L_infinity) between two vectors.
@@ -385,11 +491,36 @@ struct HammingLUT
typedef unsigned char ElementType;
typedef int ResultType;
+ typedef ElementType CentersType;
/** this will count the bits in a ^ b
*/
- ResultType operator()(const unsigned char* a, const unsigned char* b, size_t size) const
+ template<typename Iterator2>
+ ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const
+ {
+ static const uchar popCountTable[] =
+ {
+ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
+ 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
+ 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
+ 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
+ 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
+ };
+ ResultType result = 0;
+ const unsigned char* b2 = reinterpret_cast<const unsigned char*> (b);
+ for (size_t i = 0; i < size; i++) {
+ result += popCountTable[a[i] ^ b2[i]];
+ }
+ return result;
+ }
+
+
+ ResultType operator()(const unsigned char* a, const ZeroIterator<unsigned char> b, size_t size) const
{
+ (void)b;
static const uchar popCountTable[] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
@@ -403,7 +534,7 @@ struct HammingLUT
};
ResultType result = 0;
for (size_t i = 0; i < size; i++) {
- result += popCountTable[a[i] ^ b[i]];
+ result += popCountTable[a[i]];
}
return result;
}
@@ -422,17 +553,20 @@ struct Hamming
typedef T ElementType;
typedef int ResultType;
+ typedef ElementType CentersType;
template<typename Iterator1, typename Iterator2>
- ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
+ ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
{
ResultType result = 0;
#if defined(__ARM_NEON__) && !defined(__CUDACC__)
{
+ const unsigned char* a2 = reinterpret_cast<const unsigned char*> (a);
+ const unsigned char* b2 = reinterpret_cast<const unsigned char*> (b);
uint32x4_t bits = vmovq_n_u32(0);
for (size_t i = 0; i < size; i += 16) {
- uint8x16_t A_vec = vld1q_u8 (a + i);
- uint8x16_t B_vec = vld1q_u8 (b + i);
+ uint8x16_t A_vec = vld1q_u8 (a2 + i);
+ uint8x16_t B_vec = vld1q_u8 (b2 + i);
uint8x16_t AxorB = veorq_u8 (A_vec, B_vec);
uint8x16_t bitsSet = vcntq_u8 (AxorB);
uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet);
@@ -470,6 +604,52 @@ struct Hamming
#endif
return result;
}
+
+
+ template<typename Iterator1>
+ ResultType operator()(const Iterator1 a, ZeroIterator<unsigned char> b, size_t size, ResultType /*worst_dist*/ = -1) const
+ {
+ (void)b;
+ ResultType result = 0;
+#if defined(__ARM_NEON__) && !defined(__CUDACC__)
+ {
+ const unsigned char* a2 = reinterpret_cast<const unsigned char*> (a);
+ uint32x4_t bits = vmovq_n_u32(0);
+ for (size_t i = 0; i < size; i += 16) {
+ uint8x16_t A_vec = vld1q_u8 (a2 + i);
+ uint8x16_t bitsSet = vcntq_u8 (A_vec);
+ uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet);
+ uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8);
+ bits = vaddq_u32(bits, bitSet4);
+ }
+ uint64x2_t bitSet2 = vpaddlq_u32 (bits);
+ result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0);
+ result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2);
+ }
+#elif defined(__GNUC__)
+ {
+ //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll)
+ typedef unsigned long long pop_t;
+ const size_t modulo = size % sizeof(pop_t);
+ const pop_t* a2 = reinterpret_cast<const pop_t*> (a);
+ const pop_t* a2_end = a2 + (size / sizeof(pop_t));
+
+ for (; a2 != a2_end; ++a2) result += __builtin_popcountll(*a2);
+
+ if (modulo) {
+ //in the case where size is not dividable by sizeof(size_t)
+ //need to mask off the bits at the end
+ pop_t a_final = 0;
+ memcpy(&a_final, a2, modulo);
+ result += __builtin_popcountll(a_final);
+ }
+ }
+#else // NO NEON and NOT GNUC
+ HammingLUT lut;
+ result = lut(reinterpret_cast<const unsigned char*> (a), b, size);
+#endif
+ return result;
+ }
};
template<typename T>
@@ -480,6 +660,7 @@ struct Hamming2
typedef T ElementType;
typedef int ResultType;
+ typedef ElementType CentersType;
/** This is popcount_3() from:
* http://en.wikipedia.org/wiki/Hamming_weight */
@@ -500,13 +681,15 @@ struct Hamming2
#endif
template <typename Iterator1, typename Iterator2>
- ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
+ ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
{
+ CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)");
+
#ifdef FLANN_PLATFORM_64_BIT
const uint64_t* pa = reinterpret_cast<const uint64_t*>(a);
const uint64_t* pb = reinterpret_cast<const uint64_t*>(b);
ResultType result = 0;
- size /= (sizeof(uint64_t)/sizeof(unsigned char));
+ size /= long_word_size_;
for(size_t i = 0; i < size; ++i ) {
result += popcnt64(*pa ^ *pb);
++pa;
@@ -516,7 +699,7 @@ struct Hamming2
const uint32_t* pa = reinterpret_cast<const uint32_t*>(a);
const uint32_t* pb = reinterpret_cast<const uint32_t*>(b);
ResultType result = 0;
- size /= (sizeof(uint32_t)/sizeof(unsigned char));
+ size /= long_word_size_;
for(size_t i = 0; i < size; ++i ) {
result += popcnt32(*pa ^ *pb);
++pa;
@@ -525,12 +708,197 @@ struct Hamming2
#endif
return result;
}
+
+
+ template <typename Iterator1>
+ ResultType operator()(const Iterator1 a, ZeroIterator<unsigned char> b, size_t size, ResultType /*worst_dist*/ = -1) const
+ {
+ CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)");
+
+ (void)b;
+#ifdef FLANN_PLATFORM_64_BIT
+ const uint64_t* pa = reinterpret_cast<const uint64_t*>(a);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt64(*pa);
+ ++pa;
+ }
+#else
+ const uint32_t* pa = reinterpret_cast<const uint32_t*>(a);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt32(*pa);
+ ++pa;
+ }
+#endif
+ return result;
+ }
+
+private:
+#ifdef FLANN_PLATFORM_64_BIT
+ static const size_t long_word_size_ = sizeof(uint64_t)/sizeof(unsigned char);
+#else
+ static const size_t long_word_size_ = sizeof(uint32_t)/sizeof(unsigned char);
+#endif
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+struct DNAmmingLUT
+{
+ typedef False is_kdtree_distance;
+ typedef False is_vector_space_distance;
+
+ typedef unsigned char ElementType;
+ typedef int ResultType;
+ typedef ElementType CentersType;
+
+ /** this will count the bits in a ^ b
+ */
+ template<typename Iterator2>
+ ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const
+ {
+ static const uchar popCountTable[] =
+ {
+ 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4
+ };
+ ResultType result = 0;
+ const unsigned char* b2 = reinterpret_cast<const unsigned char*> (b);
+ for (size_t i = 0; i < size; i++) {
+ result += popCountTable[a[i] ^ b2[i]];
+ }
+ return result;
+ }
+
+
+ ResultType operator()(const unsigned char* a, const ZeroIterator<unsigned char> b, size_t size) const
+ {
+ (void)b;
+ static const uchar popCountTable[] =
+ {
+ 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
+ 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4
+ };
+ ResultType result = 0;
+ for (size_t i = 0; i < size; i++) {
+ result += popCountTable[a[i]];
+ }
+ return result;
+ }
+};
+
+
+template<typename T>
+struct DNAmming2
+{
+ typedef False is_kdtree_distance;
+ typedef False is_vector_space_distance;
+
+ typedef T ElementType;
+ typedef int ResultType;
+ typedef ElementType CentersType;
+
+ /** This is popcount_3() from:
+ * http://en.wikipedia.org/wiki/Hamming_weight */
+ unsigned int popcnt32(uint32_t n) const
+ {
+ n = ((n >> 1) | n) & 0x55555555;
+ n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
+ return (((n + (n >> 4))& 0x0F0F0F0F)* 0x01010101) >> 24;
+ }
+
+#ifdef FLANN_PLATFORM_64_BIT
+ unsigned int popcnt64(uint64_t n) const
+ {
+ n = ((n >> 1) | n) & 0x5555555555555555;
+ n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333);
+ return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56;
+ }
+#endif
+
+ template <typename Iterator1, typename Iterator2>
+ ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const
+ {
+ CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)");
+
+#ifdef FLANN_PLATFORM_64_BIT
+ const uint64_t* pa = reinterpret_cast<const uint64_t*>(a);
+ const uint64_t* pb = reinterpret_cast<const uint64_t*>(b);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt64(*pa ^ *pb);
+ ++pa;
+ ++pb;
+ }
+#else
+ const uint32_t* pa = reinterpret_cast<const uint32_t*>(a);
+ const uint32_t* pb = reinterpret_cast<const uint32_t*>(b);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt32(*pa ^ *pb);
+ ++pa;
+ ++pb;
+ }
+#endif
+ return result;
+ }
+
+
+ template <typename Iterator1>
+ ResultType operator()(const Iterator1 a, ZeroIterator<unsigned char> b, size_t size, ResultType /*worst_dist*/ = -1) const
+ {
+ CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)");
+
+ (void)b;
+#ifdef FLANN_PLATFORM_64_BIT
+ const uint64_t* pa = reinterpret_cast<const uint64_t*>(a);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt64(*pa);
+ ++pa;
+ }
+#else
+ const uint32_t* pa = reinterpret_cast<const uint32_t*>(a);
+ ResultType result = 0;
+ size /= long_word_size_;
+ for(size_t i = 0; i < size; ++i ) {
+ result += popcnt32(*pa);
+ ++pa;
+ }
+#endif
+ return result;
+ }
+
+private:
+#ifdef FLANN_PLATFORM_64_BIT
+ static const size_t long_word_size_= sizeof(uint64_t)/sizeof(unsigned char);
+#else
+ static const size_t long_word_size_= sizeof(uint32_t)/sizeof(unsigned char);
+#endif
+};
+
+
+
template<class T>
struct HistIntersectionDistance
{
@@ -539,6 +907,7 @@ struct HistIntersectionDistance
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the histogram intersection distance
@@ -594,6 +963,7 @@ struct HellingerDistance
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the Hellinger distance
@@ -643,6 +1013,7 @@ struct ChiSquareDistance
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the chi-square distance
@@ -697,6 +1068,7 @@ struct KL_Divergence
typedef T ElementType;
typedef typename Accumulator<T>::Type ResultType;
+ typedef ResultType CentersType;
/**
* Compute the Kullback-Leibler divergence
@@ -708,7 +1080,7 @@ struct KL_Divergence
Iterator1 last = a + size;
while (a < last) {
- if (* b != 0) {
+ if ( *a != 0 && *b != 0 ) {
ResultType ratio = (ResultType)(*a / *b);
if (ratio>0) {
result += *a * log(ratio);
@@ -731,7 +1103,7 @@ struct KL_Divergence
inline ResultType accum_dist(const U& a, const V& b, int) const
{
ResultType result = ResultType();
- if( *b != 0 ) {
+ if( a != 0 && b != 0 ) {
ResultType ratio = (ResultType)(a / b);
if (ratio>0) {
result = a * log(ratio);
@@ -742,46 +1114,6 @@ struct KL_Divergence
};
-
-/*
- * This is a "zero iterator". It basically behaves like a zero filled
- * array to all algorithms that use arrays as iterators (STL style).
- * It's useful when there's a need to compute the distance between feature
- * and origin it and allows for better compiler optimisation than using a
- * zero-filled array.
- */
-template <typename T>
-struct ZeroIterator
-{
-
- T operator*()
- {
- return 0;
- }
-
- T operator[](int)
- {
- return 0;
- }
-
- const ZeroIterator<T>& operator ++()
- {
- return *this;
- }
-
- ZeroIterator<T> operator ++(int)
- {
- return *this;
- }
-
- ZeroIterator<T>& operator+=(int)
- {
- return *this;
- }
-
-};
-
-
/*
* Depending on processed distances, some of them are already squared (e.g. L2)
* and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure
@@ -842,6 +1174,58 @@ typename Distance::ResultType ensureSquareDistance( typename Distance::ResultTyp
}
+/*
+ * ...a template to tell the user if the distance he is working with is actually squared
+ */
+
+template <typename Distance, typename ElementType>
+struct isSquareDist
+{
+ bool operator()() { return false; }
+};
+
+
+template <typename ElementType>
+struct isSquareDist<L2_Simple<ElementType>, ElementType>
+{
+ bool operator()() { return true; }
+};
+
+template <typename ElementType>
+struct isSquareDist<L2<ElementType>, ElementType>
+{
+ bool operator()() { return true; }
+};
+
+
+template <typename ElementType>
+struct isSquareDist<MinkowskiDistance<ElementType>, ElementType>
+{
+ bool operator()() { return true; }
+};
+
+template <typename ElementType>
+struct isSquareDist<HellingerDistance<ElementType>, ElementType>
+{
+ bool operator()() { return true; }
+};
+
+template <typename ElementType>
+struct isSquareDist<ChiSquareDistance<ElementType>, ElementType>
+{
+ bool operator()() { return true; }
+};
+
+
+template <typename Distance>
+bool isSquareDistance()
+{
+ typedef typename Distance::ElementType ElementType;
+
+ isSquareDist<Distance, ElementType> dummy;
+ return dummy();
+}
+
/*
* ...and a template to ensure the user that he will process the normal distance,
* and not squared distance, without losing processing time calling sqrt(ensureSquareDistance)
diff --git a/include/opencv2/flann/flann_base.hpp b/include/opencv2/flann/flann_base.hpp
index 83606d2..258ec38 100755
--- a/include/opencv2/flann/flann_base.hpp
+++ b/include/opencv2/flann/flann_base.hpp
@@ -34,7 +34,6 @@
//! @cond IGNORED
#include <vector>
-#include <cassert>
#include <cstdio>
#include "general.h"
@@ -83,11 +82,11 @@ NNIndex<Distance>* load_saved_index(const Matrix<typename Distance::ElementType>
IndexHeader header = load_header(fin);
if (header.data_type != Datatype<ElementType>::type()) {
fclose(fin);
- throw FLANNException("Datatype of saved index is different than of the one to be created.");
+ FLANN_THROW(cv::Error::StsError, "Datatype of saved index is different than of the one to be created.");
}
if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) {
fclose(fin);
- throw FLANNException("The index saved belongs to a different dataset");
+ FLANN_THROW(cv::Error::StsError, "The index saved belongs to a different dataset");
}
IndexParams params;
@@ -141,7 +140,7 @@ public:
{
FILE* fout = fopen(filename.c_str(), "wb");
if (fout == NULL) {
- throw FLANNException("Cannot open file");
+ FLANN_THROW(cv::Error::StsError, "Cannot open file");
}
save_header(fout, *nnIndex_);
saveIndex(fout);
@@ -283,7 +282,7 @@ private:
* of the form (branching-1)*K+1 smaller than clusters.rows).
*/
template <typename Distance>
-int hierarchicalClustering(const Matrix<typename Distance::ElementType>& points, Matrix<typename Distance::ResultType>& centers,
+int hierarchicalClustering(const Matrix<typename Distance::ElementType>& points, Matrix<typename Distance::CentersType>& centers,
const KMeansIndexParams& params, Distance d = Distance())
{
KMeansIndex<Distance> kmeans(points, params, d);
diff --git a/include/opencv2/flann/general.h b/include/opencv2/flann/general.h
index ac848d6..29fa8be 100755
--- a/include/opencv2/flann/general.h
+++ b/include/opencv2/flann/general.h
@@ -31,6 +31,8 @@
#ifndef OPENCV_FLANN_GENERAL_H_
#define OPENCV_FLANN_GENERAL_H_
+#if CV_VERSION_MAJOR <= 4
+
//! @cond IGNORED
#include "opencv2/core.hpp"
@@ -48,6 +50,14 @@ public:
}
+#define FLANN_THROW(TYPE, STR) throw FLANNException(STR)
+
+#else
+
+#define FLANN_THROW(TYPE, STR) CV_Error(TYPE, STR)
+
+#endif
+
//! @endcond
#endif /* OPENCV_FLANN_GENERAL_H_ */
diff --git a/include/opencv2/flann/hierarchical_clustering_index.h b/include/opencv2/flann/hierarchical_clustering_index.h
index 20304ed..7085d69 100755
--- a/include/opencv2/flann/hierarchical_clustering_index.h
+++ b/include/opencv2/flann/hierarchical_clustering_index.h
@@ -35,7 +35,6 @@
#include <algorithm>
#include <map>
-#include <cassert>
#include <limits>
#include <cmath>
@@ -153,7 +152,7 @@ private:
int n = indices_length;
int rnd = rand_int(n);
- assert(rnd >=0 && rnd < n);
+ CV_DbgAssert(rnd >=0 && rnd < n);
centers[0] = dsindices[rnd];
@@ -208,7 +207,7 @@ private:
// Choose one random center and set the closestDistSq values
int index = rand_int(n);
- assert(index >=0 && index < n);
+ CV_DbgAssert(index >=0 && index < n);
centers[0] = dsindices[index];
// Computing distance^2 will have the advantage of even higher probability further to pick new centers
@@ -295,7 +294,7 @@ private:
// Choose one random center and set the closestDistSq values
int index = rand_int(n);
- assert(index >=0 && index < n);
+ CV_DbgAssert(index >=0 && index < n);
centers[0] = dsindices[index];
for (int i = 0; i < n; i++) {
@@ -383,10 +382,9 @@ public:
chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser;
}
else {
- throw FLANNException("Unknown algorithm for choosing initial centers.");
+ FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers.");
}
- trees_ = get_param(params,"trees",4);
root = new NodePtr[trees_];
indices = new int*[trees_];
@@ -406,34 +404,16 @@ public:
*/
virtual ~HierarchicalClusteringIndex()
{
- free_elements();
-
if (root!=NULL) {
delete[] root;
}
if (indices!=NULL) {
+ free_indices();
delete[] indices;
}
}
-
- /**
- * Release the inner elements of indices[]
- */
- void free_elements()
- {
- if (indices!=NULL) {
- for(int i=0; i<trees_; ++i) {
- if (indices[i]!=NULL) {
- delete[] indices[i];
- indices[i] = NULL;
- }
- }
- }
- }
-
-
/**
* Returns size of index.
*/
@@ -466,10 +446,10 @@ public:
void buildIndex() CV_OVERRIDE
{
if (branching_<2) {
- throw FLANNException("Branching factor must be at least 2");
+ FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
}
- free_elements();
+ free_indices();
for (int i=0; i<trees_; ++i) {
indices[i] = new int[size_];
@@ -505,13 +485,12 @@ public:
void loadIndex(FILE* stream) CV_OVERRIDE
{
- free_elements();
-
if (root!=NULL) {
delete[] root;
}
if (indices!=NULL) {
+ free_indices();
delete[] indices;
}
@@ -549,7 +528,7 @@ public:
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
{
- int maxChecks = get_param(searchParams,"checks",32);
+ const int maxChecks = get_param(searchParams,"checks",32);
// Priority queue storing intermediate branches in the best-bin-first search
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
@@ -558,6 +537,8 @@ public:
int checks = 0;
for (int i=0; i<trees_; ++i) {
findNN(root[i], result, vec, checks, maxChecks, heap, checked);
+ if ((checks >= maxChecks) && result.full())
+ break;
}
BranchSt branch;
@@ -565,10 +546,10 @@ public:
NodePtr node = branch.node;
findNN(node, result, vec, checks, maxChecks, heap, checked);
}
- assert(result.full());
delete heap;
+ CV_Assert(result.full());
}
IndexParams getParameters() const CV_OVERRIDE
@@ -649,6 +630,20 @@ private:
}
+ /**
+ * Release the inner elements of indices[]
+ */
+ void free_indices()
+ {
+ if (indices!=NULL) {
+ for(int i=0; i<trees_; ++i) {
+ if (indices[i]!=NULL) {
+ delete[] indices[i];
+ indices[i] = NULL;
+ }
+ }
+ }
+ }
void computeLabels(int* dsindices, int indices_length, int* centers, int centers_length, int* labels, DistanceType& cost)
@@ -749,8 +744,8 @@ private:
Heap<BranchSt>* heap, std::vector<bool>& checked)
{
if (node->childs==NULL) {
- if (checks>=maxChecks) {
- if (result.full()) return;
+ if ((checks>=maxChecks) && result.full()) {
+ return;
}
for (int i=0; i<node->size; ++i) {
int index = node->indices[i];
diff --git a/include/opencv2/flann/index_testing.h b/include/opencv2/flann/index_testing.h
index 47b6f0b..207adef 100755
--- a/include/opencv2/flann/index_testing.h
+++ b/include/opencv2/flann/index_testing.h
@@ -34,7 +34,6 @@
//! @cond IGNORED
#include <cstring>
-#include <cassert>
#include <cmath>
#include "matrix.h"
@@ -94,7 +93,7 @@ float search_with_ground_truth(NNIndex<Distance>& index, const Matrix<typename D
if (matches.cols<size_t(nn)) {
Logger::info("matches.cols=%d, nn=%d\n",matches.cols,nn);
- throw FLANNException("Ground truth is not computed for as many neighbors as requested");
+ FLANN_THROW(cv::Error::StsError, "Ground truth is not computed for as many neighbors as requested");
}
KNNResultSet<DistanceType> resultSet(nn+skipMatches);
diff --git a/include/opencv2/flann/kdtree_index.h b/include/opencv2/flann/kdtree_index.h
index 4723505..ea3550a 100755
--- a/include/opencv2/flann/kdtree_index.h
+++ b/include/opencv2/flann/kdtree_index.h
@@ -35,10 +35,8 @@
#include <algorithm>
#include <map>
-#include <cassert>
#include <cstring>
-#include "general.h"
#include "nn_index.h"
#include "dynamic_bitset.h"
#include "matrix.h"
@@ -433,7 +431,7 @@ private:
if (trees_>0) {
searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError);
}
- assert(result.full());
+ CV_Assert(result.full());
}
/**
@@ -462,7 +460,7 @@ private:
delete heap;
- assert(result.full());
+ CV_Assert(result.full());
}
diff --git a/include/opencv2/flann/kdtree_single_index.h b/include/opencv2/flann/kdtree_single_index.h
index fa38f9f..ed95c3d 100755
--- a/include/opencv2/flann/kdtree_single_index.h
+++ b/include/opencv2/flann/kdtree_single_index.h
@@ -35,10 +35,8 @@
#include <algorithm>
#include <map>
-#include <cassert>
#include <cstring>
-#include "general.h"
#include "nn_index.h"
#include "matrix.h"
#include "result_set.h"
@@ -214,11 +212,11 @@ public:
*/
void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
{
- assert(queries.cols == veclen());
- assert(indices.rows >= queries.rows);
- assert(dists.rows >= queries.rows);
- assert(int(indices.cols) >= knn);
- assert(int(dists.cols) >= knn);
+ CV_Assert(queries.cols == veclen());
+ CV_Assert(indices.rows >= queries.rows);
+ CV_Assert(dists.rows >= queries.rows);
+ CV_Assert(int(indices.cols) >= knn);
+ CV_Assert(int(dists.cols) >= knn);
KNNSimpleResultSet<DistanceType> resultSet(knn);
for (size_t i = 0; i < queries.rows; i++) {
@@ -461,7 +459,7 @@ private:
DistanceType span = bbox[i].high-bbox[i].low;
if (span>(DistanceType)((1-EPS)*max_span)) {
ElementType min_elem, max_elem;
- computeMinMax(ind, count, cutfeat, min_elem, max_elem);
+ computeMinMax(ind, count, (int)i, min_elem, max_elem);
DistanceType spread = (DistanceType)(max_elem-min_elem);
if (spread>max_spread) {
cutfeat = (int)i;
@@ -548,11 +546,19 @@ private:
/* If this is a leaf node, then do check and return. */
if ((node->child1 == NULL)&&(node->child2 == NULL)) {
DistanceType worst_dist = result_set.worstDist();
- for (int i=node->left; i<node->right; ++i) {
- int index = reorder_ ? i : vind_[i];
- DistanceType dist = distance_(vec, data_[index], dim_, worst_dist);
- if (dist<worst_dist) {
- result_set.addPoint(dist,vind_[i]);
+ if (reorder_) {
+ for (int i=node->left; i<node->right; ++i) {
+ DistanceType dist = distance_(vec, data_[i], dim_, worst_dist);
+ if (dist<worst_dist) {
+ result_set.addPoint(dist,vind_[i]);
+ }
+ }
+ } else {
+ for (int i=node->left; i<node->right; ++i) {
+ DistanceType dist = distance_(vec, data_[vind_[i]], dim_, worst_dist);
+ if (dist<worst_dist) {
+ result_set.addPoint(dist,vind_[i]);
+ }
}
}
return;
diff --git a/include/opencv2/flann/kmeans_index.h b/include/opencv2/flann/kmeans_index.h
index 7574e7f..10b272d 100755
--- a/include/opencv2/flann/kmeans_index.h
+++ b/include/opencv2/flann/kmeans_index.h
@@ -35,7 +35,6 @@
#include <algorithm>
#include <map>
-#include <cassert>
#include <limits>
#include <cmath>
@@ -50,14 +49,19 @@
#include "saving.h"
#include "logger.h"
+#define BITS_PER_CHAR 8
+#define BITS_PER_BASE 2 // for DNA/RNA sequences
+#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE)
+#define HISTOS_PER_BASE (1<<BITS_PER_BASE)
+
namespace cvflann
{
struct KMeansIndexParams : public IndexParams
{
- KMeansIndexParams(int branching = 32, int iterations = 11,
- flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 )
+ void indexParams(int branching, int iterations,
+ flann_centers_init_t centers_init, float cb_index, int trees)
{
(*this)["algorithm"] = FLANN_INDEX_KMEANS;
// branching factor
@@ -68,6 +72,20 @@ struct KMeansIndexParams : public IndexParams
(*this)["centers_init"] = centers_init;
// cluster boundary index. Used when searching the kmeans tree
(*this)["cb_index"] = cb_index;
+ // number of kmeans trees to search in
+ (*this)["trees"] = trees;
+ }
+
+ KMeansIndexParams(int branching = 32, int iterations = 11,
+ flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 )
+ {
+ indexParams(branching, iterations, centers_init, cb_index, 1);
+ }
+
+ KMeansIndexParams(int branching, int iterations,
+ flann_centers_init_t centers_init, float cb_index, int trees)
+ {
+ indexParams(branching, iterations, centers_init, cb_index, trees);
}
};
@@ -84,6 +102,10 @@ class KMeansIndex : public NNIndex<Distance>
public:
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
+ typedef typename Distance::CentersType CentersType;
+
+ typedef typename Distance::is_kdtree_distance is_kdtree_distance;
+ typedef typename Distance::is_vector_space_distance is_vector_space_distance;
@@ -152,7 +174,7 @@ public:
int n = indices_length;
int rnd = rand_int(n);
- assert(rnd >=0 && rnd < n);
+ CV_DbgAssert(rnd >=0 && rnd < n);
centers[0] = indices[rnd];
@@ -207,7 +229,7 @@ public:
// Choose one random center and set the closestDistSq values
int index = rand_int(n);
- assert(index >=0 && index < n);
+ CV_DbgAssert(index >=0 && index < n);
centers[0] = indices[index];
for (int i = 0; i < n; i++) {
@@ -273,12 +295,14 @@ public:
return FLANN_INDEX_KMEANS;
}
+ template<class CentersContainerType>
class KMeansDistanceComputer : public cv::ParallelLoopBody
{
public:
KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
- const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
- std::vector<int> &_new_centroids, std::vector<DistanceType> &_sq_dists)
+ const int _branching, const int* _indices, const CentersContainerType& _dcenters,
+ const size_t _veclen, std::vector<int> &_new_centroids,
+ std::vector<DistanceType> &_sq_dists)
: distance(_distance)
, dataset(_dataset)
, branching(_branching)
@@ -316,7 +340,7 @@ public:
const Matrix<ElementType>& dataset;
const int branching;
const int* indices;
- const Matrix<double>& dcenters;
+ const CentersContainerType& dcenters;
const size_t veclen;
std::vector<int> &new_centroids;
std::vector<DistanceType> &sq_dists;
@@ -340,6 +364,7 @@ public:
veclen_ = dataset_.cols;
branching_ = get_param(params,"branching",32);
+ trees_ = get_param(params,"trees",1);
iterations_ = get_param(params,"iterations",11);
if (iterations_<0) {
iterations_ = (std::numeric_limits<int>::max)();
@@ -356,10 +381,17 @@ public:
chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
}
else {
- throw FLANNException("Unknown algorithm for choosing initial centers.");
+ FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers.");
}
cb_index_ = 0.4f;
+ root_ = new KMeansNodePtr[trees_];
+ indices_ = new int*[trees_];
+
+ for (int i=0; i<trees_; ++i) {
+ root_[i] = NULL;
+ indices_[i] = NULL;
+ }
}
@@ -375,9 +407,11 @@ public:
virtual ~KMeansIndex()
{
if (root_ != NULL) {
- free_centers(root_);
+ free_centers();
+ delete[] root_;
}
if (indices_!=NULL) {
+ free_indices();
delete[] indices_;
}
}
@@ -419,19 +453,24 @@ public:
void buildIndex() CV_OVERRIDE
{
if (branching_<2) {
- throw FLANNException("Branching factor must be at least 2");
+ FLANN_THROW(cv::Error::StsError, "Branching factor must be at least 2");
}
- indices_ = new int[size_];
- for (size_t i=0; i<size_; ++i) {
- indices_[i] = int(i);
- }
+ free_indices();
+
+ for (int i=0; i<trees_; ++i) {
+ indices_[i] = new int[size_];
+ for (size_t j=0; j<size_; ++j) {
+ indices_[i][j] = int(j);
+ }
+ root_[i] = pool_.allocate<KMeansNode>();
+ std::memset(root_[i], 0, sizeof(KMeansNode));
- root_ = pool_.allocate<KMeansNode>();
- std::memset(root_, 0, sizeof(KMeansNode));
+ Distance* dummy = NULL;
+ computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy);
- computeNodeStatistics(root_, indices_, (int)size_);
- computeClustering(root_, indices_, (int)size_, branching_,0);
+ computeClustering(root_[i], indices_[i], (int)size_, branching_,0);
+ }
}
@@ -441,35 +480,43 @@ public:
save_value(stream, iterations_);
save_value(stream, memoryCounter_);
save_value(stream, cb_index_);
- save_value(stream, *indices_, (int)size_);
-
- save_tree(stream, root_);
+ save_value(stream, trees_);
+ for (int i=0; i<trees_; ++i) {
+ save_value(stream, *indices_[i], (int)size_);
+ save_tree(stream, root_[i], i);
+ }
}
void loadIndex(FILE* stream) CV_OVERRIDE
{
+ if (indices_!=NULL) {
+ free_indices();
+ delete[] indices_;
+ }
+ if (root_!=NULL) {
+ free_centers();
+ }
+
load_value(stream, branching_);
load_value(stream, iterations_);
load_value(stream, memoryCounter_);
load_value(stream, cb_index_);
- if (indices_!=NULL) {
- delete[] indices_;
- }
- indices_ = new int[size_];
- load_value(stream, *indices_, size_);
+ load_value(stream, trees_);
- if (root_!=NULL) {
- free_centers(root_);
+ indices_ = new int*[trees_];
+ for (int i=0; i<trees_; ++i) {
+ indices_[i] = new int[size_];
+ load_value(stream, *indices_[i], size_);
+ load_tree(stream, root_[i], i);
}
- load_tree(stream, root_);
index_params_["algorithm"] = getType();
index_params_["branching"] = branching_;
+ index_params_["trees"] = trees_;
index_params_["iterations"] = iterations_;
index_params_["centers_init"] = centers_init_;
index_params_["cb_index"] = cb_index_;
-
}
@@ -485,28 +532,31 @@ public:
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
{
- int maxChecks = get_param(searchParams,"checks",32);
+ const int maxChecks = get_param(searchParams,"checks",32);
if (maxChecks==FLANN_CHECKS_UNLIMITED) {
- findExactNN(root_, result, vec);
+ findExactNN(root_[0], result, vec);
}
else {
// Priority queue storing intermediate branches in the best-bin-first search
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
int checks = 0;
- findNN(root_, result, vec, checks, maxChecks, heap);
+ for (int i=0; i<trees_; ++i) {
+ findNN(root_[i], result, vec, checks, maxChecks, heap);
+ if ((checks >= maxChecks) && result.full())
+ break;
+ }
BranchSt branch;
while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
KMeansNodePtr node = branch.node;
findNN(node, result, vec, checks, maxChecks, heap);
}
- assert(result.full());
-
delete heap;
- }
+ CV_Assert(result.full());
+ }
}
/**
@@ -516,22 +566,22 @@ public:
* numClusters = number of clusters to have in the clustering computed
* Returns: number of cluster centers
*/
- int getClusterCenters(Matrix<DistanceType>& centers)
+ int getClusterCenters(Matrix<CentersType>& centers)
{
int numClusters = centers.rows;
if (numClusters<1) {
- throw FLANNException("Number of clusters must be at least 1");
+ FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1");
}
DistanceType variance;
KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
- int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance);
+ int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance);
Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
for (int i=0; i<clusterCount; ++i) {
- DistanceType* center = clusters[i]->pivot;
+ CentersType* center = clusters[i]->pivot;
for (size_t j=0; j<veclen_; ++j) {
centers[i][j] = center[j];
}
@@ -556,7 +606,7 @@ private:
/**
* The cluster center.
*/
- DistanceType* pivot;
+ CentersType* pivot;
/**
* The cluster radius.
*/
@@ -596,37 +646,37 @@ private:
- void save_tree(FILE* stream, KMeansNodePtr node)
+ void save_tree(FILE* stream, KMeansNodePtr node, int num)
{
save_value(stream, *node);
save_value(stream, *(node->pivot), (int)veclen_);
if (node->childs==NULL) {
- int indices_offset = (int)(node->indices - indices_);
+ int indices_offset = (int)(node->indices - indices_[num]);
save_value(stream, indices_offset);
}
else {
for(int i=0; i<branching_; ++i) {
- save_tree(stream, node->childs[i]);
+ save_tree(stream, node->childs[i], num);
}
}
}
- void load_tree(FILE* stream, KMeansNodePtr& node)
+ void load_tree(FILE* stream, KMeansNodePtr& node, int num)
{
node = pool_.allocate<KMeansNode>();
load_value(stream, *node);
- node->pivot = new DistanceType[veclen_];
+ node->pivot = new CentersType[veclen_];
load_value(stream, *(node->pivot), (int)veclen_);
if (node->childs==NULL) {
int indices_offset;
load_value(stream, indices_offset);
- node->indices = indices_ + indices_offset;
+ node->indices = indices_[num] + indices_offset;
}
else {
node->childs = pool_.allocate<KMeansNodePtr>(branching_);
for(int i=0; i<branching_; ++i) {
- load_tree(stream, node->childs[i]);
+ load_tree(stream, node->childs[i], num);
}
}
}
@@ -645,39 +695,65 @@ private:
}
}
+ void free_centers()
+ {
+ if (root_ != NULL) {
+ for(int i=0; i<trees_; ++i) {
+ if (root_[i] != NULL) {
+ free_centers(root_[i]);
+ }
+ }
+ }
+ }
+
+ /**
+ * Release the inner elements of indices[]
+ */
+ void free_indices()
+ {
+ if (indices_!=NULL) {
+ for(int i=0; i<trees_; ++i) {
+ if (indices_[i]!=NULL) {
+ delete[] indices_[i];
+ indices_[i] = NULL;
+ }
+ }
+ }
+ }
+
/**
* Computes the statistics of a node (mean, radius, variance).
*
* Params:
* node = the node to use
- * indices = the indices of the points belonging to the node
+ * indices = array of indices of the points belonging to the node
+ * indices_length = number of indices in the array
*/
- void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length)
+ void computeNodeStatistics(KMeansNodePtr node, int* indices, unsigned int indices_length)
{
-
- DistanceType radius = 0;
DistanceType variance = 0;
- DistanceType* mean = new DistanceType[veclen_];
- memoryCounter_ += int(veclen_*sizeof(DistanceType));
+ CentersType* mean = new CentersType[veclen_];
+ memoryCounter_ += int(veclen_*sizeof(CentersType));
- memset(mean,0,veclen_*sizeof(DistanceType));
+ memset(mean,0,veclen_*sizeof(CentersType));
- for (size_t i=0; i<size_; ++i) {
+ for (unsigned int i=0; i<indices_length; ++i) {
ElementType* vec = dataset_[indices[i]];
for (size_t j=0; j<veclen_; ++j) {
mean[j] += vec[j];
}
variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
}
+ float length = static_cast<float>(indices_length);
for (size_t j=0; j<veclen_; ++j) {
- mean[j] /= size_;
+ mean[j] = cvflann::round<CentersType>( mean[j] / static_cast<double>(indices_length) );
}
- variance /= size_;
+ variance /= static_cast<DistanceType>( length );
variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
- DistanceType tmp = 0;
- for (int i=0; i<indices_length; ++i) {
- tmp = distance_(mean, dataset_[indices[i]], veclen_);
+ DistanceType radius = 0;
+ for (unsigned int i=0; i<indices_length; ++i) {
+ DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
if (tmp>radius) {
radius = tmp;
}
@@ -689,79 +765,192 @@ private:
}
- /**
- * The method responsible with actually doing the recursive hierarchical
- * clustering
- *
- * Params:
- * node = the node to cluster
- * indices = indices of the points belonging to the current node
- * branching = the branching factor to use in the clustering
- *
- * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
- */
- void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
+ void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length)
{
- node->size = indices_length;
- node->level = level;
+ const unsigned int accumulator_veclen = static_cast<unsigned int>(
+ veclen_*sizeof(CentersType)*BITS_PER_CHAR);
+
+ unsigned long long variance = 0ull;
+ CentersType* mean = new CentersType[veclen_];
+ memoryCounter_ += int(veclen_*sizeof(CentersType));
+ unsigned int* mean_accumulator = new unsigned int[accumulator_veclen];
+
+ memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen);
+
+ for (unsigned int i=0; i<indices_length; ++i) {
+ variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
+ distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
+ unsigned char* vec = (unsigned char*)dataset_[indices[i]];
+ for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
+ mean_accumulator[k] += (vec[l]) & 0x01;
+ mean_accumulator[k+1] += (vec[l]>>1) & 0x01;
+ mean_accumulator[k+2] += (vec[l]>>2) & 0x01;
+ mean_accumulator[k+3] += (vec[l]>>3) & 0x01;
+ mean_accumulator[k+4] += (vec[l]>>4) & 0x01;
+ mean_accumulator[k+5] += (vec[l]>>5) & 0x01;
+ mean_accumulator[k+6] += (vec[l]>>6) & 0x01;
+ mean_accumulator[k+7] += (vec[l]>>7) & 0x01;
+ }
+ }
+ double cnt = static_cast<double>(indices_length);
+ unsigned char* char_mean = (unsigned char*)mean;
+ for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
+ char_mean[l] = static_cast<unsigned char>(
+ (((int)(0.5 + (double)(mean_accumulator[k]) / cnt)))
+ | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1)
+ | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2)
+ | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3)
+ | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4)
+ | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5)
+ | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6)
+ | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7));
+ }
+ variance = static_cast<unsigned long long>(
+ 0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
+ variance -= static_cast<unsigned long long>(
+ ensureSquareDistance<Distance>(
+ distance_(mean, ZeroIterator<ElementType>(), veclen_)));
- if (indices_length < branching) {
- node->indices = indices;
- std::sort(node->indices,node->indices+indices_length);
- node->childs = NULL;
- return;
+ DistanceType radius = 0;
+ for (unsigned int i=0; i<indices_length; ++i) {
+ DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
+ if (tmp>radius) {
+ radius = tmp;
+ }
}
- cv::AutoBuffer<int> centers_idx_buf(branching);
- int* centers_idx = centers_idx_buf.data();
- int centers_length;
- (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
+ node->variance = static_cast<DistanceType>(variance);
+ node->radius = radius;
+ node->pivot = mean;
- if (centers_length<branching) {
- node->indices = indices;
- std::sort(node->indices,node->indices+indices_length);
- node->childs = NULL;
- return;
- }
+ delete[] mean_accumulator;
+ }
- cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
- Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
- for (int i=0; i<centers_length; ++i) {
- ElementType* vec = dataset_[centers_idx[i]];
- for (size_t k=0; k<veclen_; ++k) {
- dcenters[i][k] = double(vec[k]);
+ void computeDnaNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length)
+ {
+ const unsigned int histos_veclen = static_cast<unsigned int>(
+ veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
+
+ unsigned long long variance = 0ull;
+ unsigned int* histograms = new unsigned int[histos_veclen];
+ memset(histograms, 0, sizeof(unsigned int)*histos_veclen);
+
+ for (unsigned int i=0; i<indices_length; ++i) {
+ variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(
+ distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_)));
+
+ unsigned char* vec = (unsigned char*)dataset_[indices[i]];
+ for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
+ histograms[k + ((vec[l]) & 0x03)]++;
+ histograms[k + 4 + ((vec[l]>>2) & 0x03)]++;
+ histograms[k + 8 + ((vec[l]>>4) & 0x03)]++;
+ histograms[k +12 + ((vec[l]>>6) & 0x03)]++;
}
}
- std::vector<DistanceType> radiuses(branching);
- cv::AutoBuffer<int> count_buf(branching);
- int* count = count_buf.data();
- for (int i=0; i<branching; ++i) {
- radiuses[i] = 0;
- count[i] = 0;
+ CentersType* mean = new CentersType[veclen_];
+ memoryCounter_ += int(veclen_*sizeof(CentersType));
+ unsigned char* char_mean = (unsigned char*)mean;
+ unsigned int* h = histograms;
+ for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
+ char_mean[l] = (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
+ : h[k] > h[k+3] ? 0x00 : 0x11
+ : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
+ : h[k+1] > h[k+3] ? 0x01 : 0x11)
+ | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
+ : h[k+4] > h[k+7] ? 0x00 : 0x1100
+ : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
+ : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
+ | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
+ : h[k+8] >h[k+11] ? 0x00 : 0x110000
+ : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
+ : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
+ | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
+ : h[k+12] >h[k+15] ? 0x00 : 0x11000000
+ : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
+ : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
}
+ variance = static_cast<unsigned long long>(
+ 0.5 + static_cast<double>(variance) / static_cast<double>(indices_length));
+ variance -= static_cast<unsigned long long>(
+ ensureSquareDistance<Distance>(
+ distance_(mean, ZeroIterator<ElementType>(), veclen_)));
- // assign points to clusters
- cv::AutoBuffer<int> belongs_to_buf(indices_length);
- int* belongs_to = belongs_to_buf.data();
- for (int i=0; i<indices_length; ++i) {
-
- DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
- belongs_to[i] = 0;
- for (int j=1; j<branching; ++j) {
- DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
- if (sq_dist>new_sq_dist) {
- belongs_to[i] = j;
- sq_dist = new_sq_dist;
- }
- }
- if (sq_dist>radiuses[belongs_to[i]]) {
- radiuses[belongs_to[i]] = sq_dist;
+ DistanceType radius = 0;
+ for (unsigned int i=0; i<indices_length; ++i) {
+ DistanceType tmp = distance_(mean, dataset_[indices[i]], veclen_);
+ if (tmp>radius) {
+ radius = tmp;
}
- count[belongs_to[i]]++;
}
+ node->variance = static_cast<DistanceType>(variance);
+ node->radius = radius;
+ node->pivot = mean;
+
+ delete[] histograms;
+ }
+
+
+ template<typename DistType>
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const DistType* identifier)
+ {
+ (void)identifier;
+ computeNodeStatistics(node, indices, indices_length);
+ }
+
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const cvflann::HammingLUT* identifier)
+ {
+ (void)identifier;
+ computeBitfieldNodeStatistics(node, indices, indices_length);
+ }
+
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const cvflann::Hamming<unsigned char>* identifier)
+ {
+ (void)identifier;
+ computeBitfieldNodeStatistics(node, indices, indices_length);
+ }
+
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const cvflann::Hamming2<unsigned char>* identifier)
+ {
+ (void)identifier;
+ computeBitfieldNodeStatistics(node, indices, indices_length);
+ }
+
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const cvflann::DNAmmingLUT* identifier)
+ {
+ (void)identifier;
+ computeDnaNodeStatistics(node, indices, indices_length);
+ }
+
+ void computeNodeStatistics(KMeansNodePtr node, int* indices,
+ unsigned int indices_length,
+ const cvflann::DNAmming2<unsigned char>* identifier)
+ {
+ (void)identifier;
+ computeDnaNodeStatistics(node, indices, indices_length);
+ }
+
+
+ void refineClustering(int* indices, int indices_length, int branching, CentersType** centers,
+ std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
+ {
+ cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
+ Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
+
bool converged = false;
int iteration = 0;
while (!converged && iteration<iterations_) {
@@ -791,7 +980,8 @@ private:
std::vector<DistanceType> sq_dists(indices_length);
// reassign points to clusters
- KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
+ KMeansDistanceComputer<Matrix<double> > invoker(
+ distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
parallel_for_(cv::Range(0, (int)indices_length), invoker);
for (int i=0; i < (int)indices_length; ++i) {
@@ -831,20 +1021,232 @@ private:
converged = false;
}
}
+ }
+
+ for (int i=0; i<branching; ++i) {
+ centers[i] = new CentersType[veclen_];
+ memoryCounter_ += (int)(veclen_*sizeof(CentersType));
+ for (size_t k=0; k<veclen_; ++k) {
+ centers[i][k] = (CentersType)dcenters[i][k];
+ }
+ }
+ }
+
+ void refineBitfieldClustering(int* indices, int indices_length, int branching, CentersType** centers,
+ std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
+ {
+ for (int i=0; i<branching; ++i) {
+ centers[i] = new CentersType[veclen_];
+ memoryCounter_ += (int)(veclen_*sizeof(CentersType));
}
- DistanceType** centers = new DistanceType*[branching];
+ const unsigned int accumulator_veclen = static_cast<unsigned int>(
+ veclen_*sizeof(ElementType)*BITS_PER_CHAR);
+ cv::AutoBuffer<unsigned int> dcenters_buf(branching*accumulator_veclen);
+ Matrix<unsigned int> dcenters(dcenters_buf.data(), branching, accumulator_veclen);
+
+ bool converged = false;
+ int iteration = 0;
+ while (!converged && iteration<iterations_) {
+ converged = true;
+ iteration++;
+
+ // compute the new cluster centers
+ for (int i=0; i<branching; ++i) {
+ memset(dcenters[i],0,sizeof(unsigned int)*accumulator_veclen);
+ radiuses[i] = 0;
+ }
+ for (int i=0; i<indices_length; ++i) {
+ unsigned char* vec = (unsigned char*)dataset_[indices[i]];
+ unsigned int* dcenter = dcenters[belongs_to[i]];
+ for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
+ dcenter[k] += (vec[l]) & 0x01;
+ dcenter[k+1] += (vec[l]>>1) & 0x01;
+ dcenter[k+2] += (vec[l]>>2) & 0x01;
+ dcenter[k+3] += (vec[l]>>3) & 0x01;
+ dcenter[k+4] += (vec[l]>>4) & 0x01;
+ dcenter[k+5] += (vec[l]>>5) & 0x01;
+ dcenter[k+6] += (vec[l]>>6) & 0x01;
+ dcenter[k+7] += (vec[l]>>7) & 0x01;
+ }
+ }
+ for (int i=0; i<branching; ++i) {
+ double cnt = static_cast<double>(count[i]);
+ unsigned int* dcenter = dcenters[i];
+ unsigned char* charCenter = (unsigned char*)centers[i];
+ for (size_t k=0, l=0; k<accumulator_veclen; k+=BITS_PER_CHAR, ++l) {
+ charCenter[l] = static_cast<unsigned char>(
+ (((int)(0.5 + (double)(dcenter[k]) / cnt)))
+ | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1)
+ | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2)
+ | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3)
+ | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4)
+ | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5)
+ | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6)
+ | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7));
+ }
+ }
+
+ std::vector<int> new_centroids(indices_length);
+ std::vector<DistanceType> dists(indices_length);
+
+ // reassign points to clusters
+ KMeansDistanceComputer<ElementType**> invoker(
+ distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
+ parallel_for_(cv::Range(0, (int)indices_length), invoker);
+
+ for (int i=0; i < indices_length; ++i) {
+ DistanceType dist(dists[i]);
+ int new_centroid(new_centroids[i]);
+ if (dist > radiuses[new_centroid]) {
+ radiuses[new_centroid] = dist;
+ }
+ if (new_centroid != belongs_to[i]) {
+ count[belongs_to[i]]--;
+ count[new_centroid]++;
+ belongs_to[i] = new_centroid;
+ converged = false;
+ }
+ }
+
+ for (int i=0; i<branching; ++i) {
+ // if one cluster converges to an empty cluster,
+ // move an element into that cluster
+ if (count[i]==0) {
+ int j = (i+1)%branching;
+ while (count[j]<=1) {
+ j = (j+1)%branching;
+ }
+
+ for (int k=0; k<indices_length; ++k) {
+ if (belongs_to[k]==j) {
+ // for cluster j, we move the furthest element from the center to the empty cluster i
+ if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
+ belongs_to[k] = i;
+ count[j]--;
+ count[i]++;
+ break;
+ }
+ }
+ }
+ converged = false;
+ }
+ }
+ }
+ }
+
+ void refineDnaClustering(int* indices, int indices_length, int branching, CentersType** centers,
+ std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
+ {
for (int i=0; i<branching; ++i) {
- centers[i] = new DistanceType[veclen_];
- memoryCounter_ += (int)(veclen_*sizeof(DistanceType));
- for (size_t k=0; k<veclen_; ++k) {
- centers[i][k] = (DistanceType)dcenters[i][k];
+ centers[i] = new CentersType[veclen_];
+ memoryCounter_ += (int)(veclen_*sizeof(CentersType));
+ }
+
+ const unsigned int histos_veclen = static_cast<unsigned int>(
+ veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR));
+ cv::AutoBuffer<unsigned int> histos_buf(branching*histos_veclen);
+ Matrix<unsigned int> histos(histos_buf.data(), branching, histos_veclen);
+
+ bool converged = false;
+ int iteration = 0;
+ while (!converged && iteration<iterations_) {
+ converged = true;
+ iteration++;
+
+ // compute the new cluster centers
+ for (int i=0; i<branching; ++i) {
+ memset(histos[i],0,sizeof(unsigned int)*histos_veclen);
+ radiuses[i] = 0;
+ }
+ for (int i=0; i<indices_length; ++i) {
+ unsigned char* vec = (unsigned char*)dataset_[indices[i]];
+ unsigned int* h = histos[belongs_to[i]];
+ for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
+ h[k + ((vec[l]) & 0x03)]++;
+ h[k + 4 + ((vec[l]>>2) & 0x03)]++;
+ h[k + 8 + ((vec[l]>>4) & 0x03)]++;
+ h[k +12 + ((vec[l]>>6) & 0x03)]++;
+ }
+ }
+ for (int i=0; i<branching; ++i) {
+ unsigned int* h = histos[i];
+ unsigned char* charCenter = (unsigned char*)centers[i];
+ for (size_t k=0, l=0; k<histos_veclen; k+=HISTOS_PER_BASE*BASE_PER_CHAR, ++l) {
+ charCenter[l]= (h[k] > h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10
+ : h[k] > h[k+3] ? 0x00 : 0x11
+ : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10
+ : h[k+1] > h[k+3] ? 0x01 : 0x11)
+ | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000
+ : h[k+4] > h[k+7] ? 0x00 : 0x1100
+ : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000
+ : h[k+5] > h[k+7] ? 0x0100 : 0x1100)
+ | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000
+ : h[k+8] >h[k+11] ? 0x00 : 0x110000
+ : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000
+ : h[k+9] >h[k+11] ? 0x010000 : 0x110000)
+ | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000
+ : h[k+12] >h[k+15] ? 0x00 : 0x11000000
+ : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000
+ : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000);
+ }
+ }
+
+ std::vector<int> new_centroids(indices_length);
+ std::vector<DistanceType> dists(indices_length);
+
+ // reassign points to clusters
+ KMeansDistanceComputer<ElementType**> invoker(
+ distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists);
+ parallel_for_(cv::Range(0, (int)indices_length), invoker);
+
+ for (int i=0; i < indices_length; ++i) {
+ DistanceType dist(dists[i]);
+ int new_centroid(new_centroids[i]);
+ if (dist > radiuses[new_centroid]) {
+ radiuses[new_centroid] = dist;
+ }
+ if (new_centroid != belongs_to[i]) {
+ count[belongs_to[i]]--;
+ count[new_centroid]++;
+ belongs_to[i] = new_centroid;
+ converged = false;
+ }
+ }
+
+ for (int i=0; i<branching; ++i) {
+ // if one cluster converges to an empty cluster,
+ // move an element into that cluster
+ if (count[i]==0) {
+ int j = (i+1)%branching;
+ while (count[j]<=1) {
+ j = (j+1)%branching;
+ }
+
+ for (int k=0; k<indices_length; ++k) {
+ if (belongs_to[k]==j) {
+ // for cluster j, we move the furthest element from the center to the empty cluster i
+ if ( distance_(dataset_[indices[k]], centers[j], veclen_) == radiuses[j] ) {
+ belongs_to[k] = i;
+ count[j]--;
+ count[i]++;
+ break;
+ }
+ }
+ }
+ converged = false;
+ }
}
}
+ }
+ void computeSubClustering(KMeansNodePtr node, int* indices, int indices_length,
+ int branching, int level, CentersType** centers,
+ std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
+ {
// compute kmeans clustering for each of the resulting clusters
node->childs = pool_.allocate<KMeansNodePtr>(branching);
int start = 0;
@@ -858,7 +1260,7 @@ private:
if (belongs_to[i]==c) {
DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
variance += d;
- mean_radius += sqrt(d);
+ mean_radius += static_cast<DistanceType>( sqrt(d) );
std::swap(indices[i],indices[end]);
std::swap(belongs_to[i],belongs_to[end]);
end++;
@@ -877,11 +1279,252 @@ private:
computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
start=end;
}
+ }
- delete[] centers;
+
+ void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length,
+ int branching, int level, CentersType** centers,
+ std::vector<DistanceType>& radiuses, int* belongs_to, int* count)
+ {
+ // compute kmeans clustering for each of the resulting clusters
+ node->childs = pool_.allocate<KMeansNodePtr>(branching);
+ int start = 0;
+ int end = start;
+ for (int c=0; c<branching; ++c) {
+ int s = count[c];
+
+ unsigned long long variance = 0ull;
+ DistanceType mean_radius =0;
+ for (int i=0; i<indices_length; ++i) {
+ if (belongs_to[i]==c) {
+ DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
+ variance += static_cast<unsigned long long>( ensureSquareDistance<Distance>(d) );
+ mean_radius += ensureSimpleDistance<Distance>(d);
+ std::swap(indices[i],indices[end]);
+ std::swap(belongs_to[i],belongs_to[end]);
+ end++;
+ }
+ }
+ mean_radius = static_cast<DistanceType>(
+ 0.5f + static_cast<float>(mean_radius) / static_cast<float>(s));
+ variance = static_cast<unsigned long long>(
+ 0.5 + static_cast<double>(variance) / static_cast<double>(s));
+ variance -= static_cast<unsigned long long>(
+ ensureSquareDistance<Distance>(
+ distance_(centers[c], ZeroIterator<ElementType>(), veclen_)));
+
+ node->childs[c] = pool_.allocate<KMeansNode>();
+ std::memset(node->childs[c], 0, sizeof(KMeansNode));
+ node->childs[c]->radius = radiuses[c];
+ node->childs[c]->pivot = centers[c];
+ node->childs[c]->variance = static_cast<DistanceType>(variance);
+ node->childs[c]->mean_radius = mean_radius;
+ computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
+ start=end;
+ }
+ }
+
+
+ template<typename DistType>
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const DistType* identifier)
+ {
+ (void)identifier;
+ refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
+ }
+
+
+ /**
+ * The methods responsible with doing the recursive hierarchical clustering on
+ * binary vectors.
+ * As some might have heard that KMeans on binary data doesn't make sense,
+ * it's worth a little explanation why it actually fairly works. As
+ * with the Hierarchical Clustering algortihm, we seed several centers for the
+ * current node by picking some of its points. Then in a first pass each point
+ * of the node is then related to its closest center. Now let's have a look at
+ * the 5 central dimensions of the 9 following points:
+ *
+ * xxxxxx11100xxxxx (1)
+ * xxxxxx11010xxxxx (2)
+ * xxxxxx11001xxxxx (3)
+ * xxxxxx10110xxxxx (4)
+ * xxxxxx10101xxxxx (5)
+ * xxxxxx10011xxxxx (6)
+ * xxxxxx01110xxxxx (7)
+ * xxxxxx01101xxxxx (8)
+ * xxxxxx01011xxxxx (9)
+ * sum _____
+ * of 1: 66555
+ *
+ * Even if the barycenter notion doesn't apply, we can set a center
+ * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing
+ * on for these points.
+ *
+ * Note that convergence isn't ensured anymore. In practice, using Gonzales
+ * as seeding algorithm should be fine for getting convergence ("iterations"
+ * value can be set to -1). But with KMeans++ seeding you should definitely
+ * set a maximum number of iterations (but make it higher than the "iterations"
+ * default value of 11).
+ *
+ * Params:
+ * node = the node to cluster
+ * indices = indices of the points belonging to the current node
+ * indices_length = number of points in the current node
+ * branching = the branching factor to use in the clustering
+ * level = 0 for the root node, it increases with the subdivision levels
+ * centers = clusters centers to compute
+ * radiuses = radiuses of clusters
+ * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to
+ * count = array storing the number of indices for a given center id
+ * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates)
+ */
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const cvflann::HammingLUT* identifier)
+ {
+ (void)identifier;
+ refineBitfieldClustering(
+ indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
+ }
+
+
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const cvflann::Hamming<unsigned char>* identifier)
+ {
+ (void)identifier;
+ refineBitfieldClustering(
+ indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
}
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const cvflann::Hamming2<unsigned char>* identifier)
+ {
+ (void)identifier;
+ refineBitfieldClustering(
+ indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
+ }
+
+
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier)
+ {
+ (void)identifier;
+ refineDnaClustering(
+ indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
+ }
+
+
+ void refineAndSplitClustering(
+ KMeansNodePtr node, int* indices, int indices_length, int branching,
+ int level, CentersType** centers, std::vector<DistanceType>& radiuses,
+ int* belongs_to, int* count, const cvflann::DNAmming2<unsigned char>* identifier)
+ {
+ (void)identifier;
+ refineDnaClustering(
+ indices, indices_length, branching, centers, radiuses, belongs_to, count);
+
+ computeAnyBitfieldSubClustering(node, indices, indices_length, branching,
+ level, centers, radiuses, belongs_to, count);
+ }
+
+
+ /**
+ * The method responsible with actually doing the recursive hierarchical
+ * clustering
+ *
+ * Params:
+ * node = the node to cluster
+ * indices = indices of the points belonging to the current node
+ * branching = the branching factor to use in the clustering
+ *
+ * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
+ */
+ void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
+ {
+ node->size = indices_length;
+ node->level = level;
+
+ if (indices_length < branching) {
+ node->indices = indices;
+ std::sort(node->indices,node->indices+indices_length);
+ node->childs = NULL;
+ return;
+ }
+
+ cv::AutoBuffer<int> centers_idx_buf(branching);
+ int* centers_idx = centers_idx_buf.data();
+ int centers_length;
+ (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
+
+ if (centers_length<branching) {
+ node->indices = indices;
+ std::sort(node->indices,node->indices+indices_length);
+ node->childs = NULL;
+ return;
+ }
+
+
+ std::vector<DistanceType> radiuses(branching);
+ cv::AutoBuffer<int> count_buf(branching);
+ int* count = count_buf.data();
+ for (int i=0; i<branching; ++i) {
+ radiuses[i] = 0;
+ count[i] = 0;
+ }
+
+ // assign points to clusters
+ cv::AutoBuffer<int> belongs_to_buf(indices_length);
+ int* belongs_to = belongs_to_buf.data();
+ for (int i=0; i<indices_length; ++i) {
+ DistanceType sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[0]], veclen_);
+ belongs_to[i] = 0;
+ for (int j=1; j<branching; ++j) {
+ DistanceType new_sq_dist = distance_(dataset_[indices[i]], dataset_[centers_idx[j]], veclen_);
+ if (sq_dist>new_sq_dist) {
+ belongs_to[i] = j;
+ sq_dist = new_sq_dist;
+ }
+ }
+ if (sq_dist>radiuses[belongs_to[i]]) {
+ radiuses[belongs_to[i]] = sq_dist;
+ }
+ count[belongs_to[i]]++;
+ }
+
+ CentersType** centers = new CentersType*[branching];
+
+ Distance* dummy = NULL;
+ refineAndSplitClustering(node, indices, indices_length, branching, level,
+ centers, radiuses, belongs_to, count, dummy);
+
+ delete[] centers;
+ }
+
/**
* Performs one descent in the hierarchical k-means tree. The branches not
@@ -905,18 +1548,22 @@ private:
DistanceType rsq = node->radius;
DistanceType wsq = result.worstDist();
- DistanceType val = bsq-rsq-wsq;
- DistanceType val2 = val*val-4*rsq*wsq;
-
- //if (val>0) {
- if ((val>0)&&(val2>0)) {
- return;
+ if (isSquareDistance<Distance>())
+ {
+ DistanceType val = bsq-rsq-wsq;
+ if ((val>0) && (val*val > 4*rsq*wsq))
+ return;
+ }
+ else
+ {
+ if (bsq-rsq > wsq)
+ return;
}
}
if (node->childs==NULL) {
- if (checks>=maxChecks) {
- if (result.full()) return;
+ if ((checks>=maxChecks) && result.full()) {
+ return;
}
checks += node->size;
for (int i=0; i<node->size; ++i) {
@@ -956,7 +1603,8 @@ private:
// float* best_center = node->childs[best_index]->pivot;
for (int i=0; i<branching_; ++i) {
if (i != best_index) {
- domain_distances[i] -= cb_index_*node->childs[i]->variance;
+ domain_distances[i] -= cvflann::round<DistanceType>(
+ cb_index_*node->childs[i]->variance );
// float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
// if (domain_distances[i]<dist_to_border) {
@@ -981,12 +1629,16 @@ private:
DistanceType rsq = node->radius;
DistanceType wsq = result.worstDist();
- DistanceType val = bsq-rsq-wsq;
- DistanceType val2 = val*val-4*rsq*wsq;
-
- // if (val>0) {
- if ((val>0)&&(val2>0)) {
- return;
+ if (isSquareDistance<Distance>())
+ {
+ DistanceType val = bsq-rsq-wsq;
+ if ((val>0) && (val*val > 4*rsq*wsq))
+ return;
+ }
+ else
+ {
+ if (bsq-rsq > wsq)
+ return;
}
}
@@ -1024,7 +1676,8 @@ private:
DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
int j=0;
- while (domain_distances[j]<dist && j<i) j++;
+ while (domain_distances[j]<dist && j<i)
+ j++;
for (int k=i; k>j; --k) {
domain_distances[k] = domain_distances[k-1];
sort_indices[k] = sort_indices[k-1];
@@ -1111,6 +1764,9 @@ private:
/** The branching factor used in the hierarchical k-means clustering */
int branching_;
+ /** Number of kmeans trees (default is one) */
+ int trees_;
+
/** Maximum number of iterations to use when performing k-means clustering */
int iterations_;
@@ -1146,12 +1802,12 @@ private:
/**
* The root node in the tree.
*/
- KMeansNodePtr root_;
+ KMeansNodePtr* root_;
/**
* Array of indices to vectors in the dataset.
*/
- int* indices_;
+ int** indices_;
/**
* The distance
diff --git a/include/opencv2/flann/linear_index.h b/include/opencv2/flann/linear_index.h
index 8a0f10f..6428c0d 100755
--- a/include/opencv2/flann/linear_index.h
+++ b/include/opencv2/flann/linear_index.h
@@ -33,7 +33,6 @@
//! @cond IGNORED
-#include "general.h"
#include "nn_index.h"
namespace cvflann
diff --git a/include/opencv2/flann/lsh_index.h b/include/opencv2/flann/lsh_index.h
index ee620da..9ff86b8 100755
--- a/include/opencv2/flann/lsh_index.h
+++ b/include/opencv2/flann/lsh_index.h
@@ -38,12 +38,10 @@
//! @cond IGNORED
#include <algorithm>
-#include <cassert>
#include <cstring>
#include <map>
#include <vector>
-#include "general.h"
#include "nn_index.h"
#include "matrix.h"
#include "result_set.h"
@@ -53,6 +51,11 @@
#include "random.h"
#include "saving.h"
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable: 4702) //disable unreachable code
+#endif
+
namespace cvflann
{
@@ -60,20 +63,20 @@ struct LshIndexParams : public IndexParams
{
LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2)
{
- (* this)["algorithm"] = FLANN_INDEX_LSH;
+ (*this)["algorithm"] = FLANN_INDEX_LSH;
// The number of hash tables to use
- (*this)["table_number"] = table_number;
+ (*this)["table_number"] = static_cast<int>(table_number);
// The length of the key in the hash tables
- (*this)["key_size"] = key_size;
+ (*this)["key_size"] = static_cast<int>(key_size);
// Number of levels to use in multi-probe (0 for standard LSH)
- (*this)["multi_probe_level"] = multi_probe_level;
+ (*this)["multi_probe_level"] = static_cast<int>(multi_probe_level);
}
};
/**
- * Randomized kd-tree index
+ * Locality-sensitive hashing index
*
- * Contains the k-d trees and other information for indexing a set of points
+ * Contains the tables and other information for indexing a set of points
* for nearest-neighbor matching.
*/
template<typename Distance>
@@ -94,9 +97,9 @@ public:
{
// cv::flann::IndexParams sets integer params as 'int', so it is used with get_param
// in place of 'unsigned int'
- table_number_ = (unsigned int)get_param<int>(index_params_,"table_number",12);
- key_size_ = (unsigned int)get_param<int>(index_params_,"key_size",20);
- multi_probe_level_ = (unsigned int)get_param<int>(index_params_,"multi_probe_level",2);
+ table_number_ = get_param(index_params_,"table_number",12);
+ key_size_ = get_param(index_params_,"key_size",20);
+ multi_probe_level_ = get_param(index_params_,"multi_probe_level",2);
feature_size_ = (unsigned)dataset_.cols;
fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_);
@@ -112,7 +115,7 @@ public:
void buildIndex() CV_OVERRIDE
{
tables_.resize(table_number_);
- for (unsigned int i = 0; i < table_number_; ++i) {
+ for (int i = 0; i < table_number_; ++i) {
lsh::LshTable<ElementType>& table = tables_[i];
table = lsh::LshTable<ElementType>(feature_size_, key_size_);
@@ -191,11 +194,11 @@ public:
*/
virtual void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params) CV_OVERRIDE
{
- assert(queries.cols == veclen());
- assert(indices.rows >= queries.rows);
- assert(dists.rows >= queries.rows);
- assert(int(indices.cols) >= knn);
- assert(int(dists.cols) >= knn);
+ CV_Assert(queries.cols == veclen());
+ CV_Assert(indices.rows >= queries.rows);
+ CV_Assert(dists.rows >= queries.rows);
+ CV_Assert(int(indices.cols) >= knn);
+ CV_Assert(int(dists.cols) >= knn);
KNNUniqueResultSet<DistanceType> resultSet(knn);
@@ -378,11 +381,11 @@ private:
IndexParams index_params_;
/** table number */
- unsigned int table_number_;
+ int table_number_;
/** key size */
- unsigned int key_size_;
+ int key_size_;
/** How far should we look for neighbors in multi-probe LSH */
- unsigned int multi_probe_level_;
+ int multi_probe_level_;
/** The XOR masks to apply to a key to get the neighboring buckets */
std::vector<lsh::BucketKey> xor_masks_;
@@ -391,6 +394,10 @@ private:
};
}
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
//! @endcond
#endif //OPENCV_FLANN_LSH_INDEX_H_
diff --git a/include/opencv2/flann/lsh_table.h b/include/opencv2/flann/lsh_table.h
index db8b5af..a189562 100755
--- a/include/opencv2/flann/lsh_table.h
+++ b/include/opencv2/flann/lsh_table.h
@@ -58,6 +58,12 @@
#include "dynamic_bitset.h"
#include "matrix.h"
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable: 4702) //disable unreachable code
+#endif
+
+
namespace cvflann
{
@@ -162,8 +168,7 @@ public:
{
feature_size_ = feature_size;
CV_UNUSED(key_size);
- std::cerr << "LSH is not implemented for that type" << std::endl;
- assert(0);
+ CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" );
}
/** Add a feature to the table
@@ -243,9 +248,8 @@ public:
*/
size_t getKey(const ElementType* /*feature*/) const
{
- std::cerr << "LSH is not implemented for that type" << std::endl;
- assert(0);
- return 1;
+ CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" );
+ return 0;
}
/** Get statistics about the table
@@ -510,6 +514,10 @@ inline LshStats LshTable<unsigned char>::getStats() const
}
}
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! @endcond
diff --git a/include/opencv2/flann/matrix.h b/include/opencv2/flann/matrix.h
index 34893b7..fb871bd 100755
--- a/include/opencv2/flann/matrix.h
+++ b/include/opencv2/flann/matrix.h
@@ -35,8 +35,6 @@
#include <stdio.h>
-#include "general.h"
-
namespace cvflann
{
diff --git a/include/opencv2/flann/miniflann.hpp b/include/opencv2/flann/miniflann.hpp
index 2532907..1deeeb9 100755
--- a/include/opencv2/flann/miniflann.hpp
+++ b/include/opencv2/flann/miniflann.hpp
@@ -54,20 +54,6 @@ namespace cv
namespace flann
{
-enum FlannIndexType {
- FLANN_INDEX_TYPE_8U = CV_8U,
- FLANN_INDEX_TYPE_8S = CV_8S,
- FLANN_INDEX_TYPE_16U = CV_16U,
- FLANN_INDEX_TYPE_16S = CV_16S,
- FLANN_INDEX_TYPE_32S = CV_32S,
- FLANN_INDEX_TYPE_32F = CV_32F,
- FLANN_INDEX_TYPE_64F = CV_64F,
- FLANN_INDEX_TYPE_STRING,
- FLANN_INDEX_TYPE_BOOL,
- FLANN_INDEX_TYPE_ALGORITHM,
- LAST_VALUE_FLANN_INDEX_TYPE = FLANN_INDEX_TYPE_ALGORITHM
-};
-
struct CV_EXPORTS IndexParams
{
IndexParams();
@@ -84,9 +70,8 @@ struct CV_EXPORTS IndexParams
void setBool(const String& key, bool value);
void setAlgorithm(int value);
- // FIXIT: replace by void write(FileStorage& fs) const + read()
void getAll(std::vector<String>& names,
- std::vector<FlannIndexType>& types,
+ std::vector<int>& types,
std::vector<String>& strValues,
std::vector<double>& numValues) const;
@@ -146,26 +131,30 @@ struct CV_EXPORTS SearchParams : public IndexParams
SearchParams( int checks = 32, float eps = 0, bool sorted = true );
};
-class CV_EXPORTS_W Index
+class CV_EXPORTS Index
{
public:
- CV_WRAP Index();
- CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2);
+ Index();
+
+ /// @note 'features' must have extended lifetime (as cv::Mat) than this #Index instance (to avoid dangling pointers)
+ Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2);
virtual ~Index();
- CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2);
- CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices,
+ /// @note 'features' must have extended lifetime (as cv::Mat) than this #Index instance (to avoid dangling pointers)
+ virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2);
+
+ virtual void knnSearch(InputArray query, OutputArray indices,
OutputArray dists, int knn, const SearchParams& params=SearchParams());
- CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices,
+ virtual int radiusSearch(InputArray query, OutputArray indices,
OutputArray dists, double radius, int maxResults,
const SearchParams& params=SearchParams());
- CV_WRAP virtual void save(const String& filename) const;
- CV_WRAP virtual bool load(InputArray features, const String& filename);
- CV_WRAP virtual void release();
- CV_WRAP cvflann::flann_distance_t getDistance() const;
- CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const;
+ virtual void save(const String& filename) const;
+ virtual bool load(InputArray features, const String& filename);
+ virtual void release();
+ cvflann::flann_distance_t getDistance() const;
+ cvflann::flann_algorithm_t getAlgorithm() const;
protected:
cvflann::flann_distance_t distType;
diff --git a/include/opencv2/flann/nn_index.h b/include/opencv2/flann/nn_index.h
index 00fe6ec..f6e17d1 100755
--- a/include/opencv2/flann/nn_index.h
+++ b/include/opencv2/flann/nn_index.h
@@ -31,7 +31,6 @@
#ifndef OPENCV_FLANN_NNINDEX_H
#define OPENCV_FLANN_NNINDEX_H
-#include "general.h"
#include "matrix.h"
#include "result_set.h"
#include "params.h"
@@ -69,11 +68,11 @@ public:
*/
virtual void knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, int knn, const SearchParams& params)
{
- assert(queries.cols == veclen());
- assert(indices.rows >= queries.rows);
- assert(dists.rows >= queries.rows);
- assert(int(indices.cols) >= knn);
- assert(int(dists.cols) >= knn);
+ CV_Assert(queries.cols == veclen());
+ CV_Assert(indices.rows >= queries.rows);
+ CV_Assert(dists.rows >= queries.rows);
+ CV_Assert(int(indices.cols) >= knn);
+ CV_Assert(int(dists.cols) >= knn);
#if 0
KNNResultSet<DistanceType> resultSet(knn);
diff --git a/include/opencv2/flann/params.h b/include/opencv2/flann/params.h
index b8f7331..a7920d0 100755
--- a/include/opencv2/flann/params.h
+++ b/include/opencv2/flann/params.h
@@ -77,7 +77,7 @@ T get_param(const IndexParams& params, cv::String name)
return it->second.cast<T>();
}
else {
- throw FLANNException(cv::String("Missing parameter '")+name+cv::String("' in the parameters given"));
+ FLANN_THROW(cv::Error::StsBadArg, cv::String("Missing parameter '")+name+cv::String("' in the parameters given"));
}
}
diff --git a/include/opencv2/flann/random.h b/include/opencv2/flann/random.h
index 3bb48b6..2c1809c 100755
--- a/include/opencv2/flann/random.h
+++ b/include/opencv2/flann/random.h
@@ -37,8 +37,6 @@
#include <cstdlib>
#include <vector>
-#include "general.h"
-
namespace cvflann
{
diff --git a/include/opencv2/flann/result_set.h b/include/opencv2/flann/result_set.h
index 735028f..47ad231 100755
--- a/include/opencv2/flann/result_set.h
+++ b/include/opencv2/flann/result_set.h
@@ -160,7 +160,8 @@ class KNNResultSet : public ResultSet<DistanceType>
DistanceType worst_distance_;
public:
- KNNResultSet(int capacity_) : capacity(capacity_), count(0)
+ KNNResultSet(int capacity_)
+ : indices(NULL), dists(NULL), capacity(capacity_), count(0), worst_distance_(0)
{
}
@@ -186,6 +187,8 @@ public:
void addPoint(DistanceType dist, int index) CV_OVERRIDE
{
+ CV_DbgAssert(indices);
+ CV_DbgAssert(dists);
if (dist >= worst_distance_) return;
int i;
for (i = count; i > 0; --i) {
@@ -196,12 +199,10 @@ public:
#endif
{
// Check for duplicate indices
- int j = i - 1;
- while ((j >= 0) && (dists[j] == dist)) {
+ for (int j = i; dists[j] == dist && j--;) {
if (indices[j] == index) {
return;
}
- --j;
}
break;
}
diff --git a/include/opencv2/flann/saving.h b/include/opencv2/flann/saving.h
index 53359b4..8b3aeb7 100755
--- a/include/opencv2/flann/saving.h
+++ b/include/opencv2/flann/saving.h
@@ -112,11 +112,11 @@ inline IndexHeader load_header(FILE* stream)
size_t read_size = fread(&header,sizeof(header),1,stream);
if (read_size!=(size_t)1) {
- throw FLANNException("Invalid index file, cannot read");
+ FLANN_THROW(cv::Error::StsError, "Invalid index file, cannot read");
}
if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) {
- throw FLANNException("Invalid index file, wrong signature");
+ FLANN_THROW(cv::Error::StsError, "Invalid index file, wrong signature");
}
return header;
@@ -150,7 +150,7 @@ void load_value(FILE* stream, T& value, size_t count = 1)
{
size_t read_cnt = fread(&value, sizeof(value), count, stream);
if (read_cnt != count) {
- throw FLANNException("Cannot read from file");
+ FLANN_THROW(cv::Error::StsParseError, "Cannot read from file");
}
}
@@ -159,12 +159,12 @@ void load_value(FILE* stream, cvflann::Matrix<T>& value)
{
size_t read_cnt = fread(&value, sizeof(value), 1, stream);
if (read_cnt != 1) {
- throw FLANNException("Cannot read from file");
+ FLANN_THROW(cv::Error::StsParseError, "Cannot read from file");
}
value.data = new T[value.rows*value.cols];
read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream);
if (read_cnt != (size_t)(value.rows*value.cols)) {
- throw FLANNException("Cannot read from file");
+ FLANN_THROW(cv::Error::StsParseError, "Cannot read from file");
}
}
@@ -175,12 +175,12 @@ void load_value(FILE* stream, std::vector<T>& value)
size_t size;
size_t read_cnt = fread(&size, sizeof(size_t), 1, stream);
if (read_cnt!=1) {
- throw FLANNException("Cannot read from file");
+ FLANN_THROW(cv::Error::StsError, "Cannot read from file");
}
value.resize(size);
read_cnt = fread(&value[0], sizeof(T), size, stream);
if (read_cnt != size) {
- throw FLANNException("Cannot read from file");
+ FLANN_THROW(cv::Error::StsError, "Cannot read from file");
}
}
diff --git a/include/opencv2/flann/simplex_downhill.h b/include/opencv2/flann/simplex_downhill.h
index 9fd84f4..0297014 100755
--- a/include/opencv2/flann/simplex_downhill.h
+++ b/include/opencv2/flann/simplex_downhill.h
@@ -72,7 +72,7 @@ float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL )
{
const int MAX_ITERATIONS = 10;
- assert(n>0);
+ CV_DbgAssert(n>0);
T* p_o = new T[n];
T* p_r = new T[n];
@@ -131,7 +131,7 @@ float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL )
}
if (val_r<vals[0]) {
- // value is smaller than smalest in simplex
+ // value is smaller than smallest in simplex
// expand some more to see if it drops further
for (int i=0; i<n; ++i) {
diff --git a/include/opencv2/flann/timer.h b/include/opencv2/flann/timer.h
index 73795aa..7dc50a4 100755
--- a/include/opencv2/flann/timer.h
+++ b/include/opencv2/flann/timer.h
@@ -60,6 +60,7 @@ public:
* Constructor.
*/
StartStopTimer()
+ : startTime(0)
{
reset();
}
diff --git a/include/opencv2/highgui.hpp b/include/opencv2/highgui.hpp
index f109640..6a8c598 100755
--- a/include/opencv2/highgui.hpp
+++ b/include/opencv2/highgui.hpp
@@ -66,6 +66,7 @@ It provides easy interface to:
- Add trackbars to the windows, handle simple mouse events as well as keyboard commands.
@{
+ @defgroup highgui_window_flags Flags related creating and manipulating HighGUI windows and mouse events
@defgroup highgui_opengl OpenGL support
@defgroup highgui_qt Qt New Functions
@@ -93,7 +94,7 @@ It provides easy interface to:
namedWindow("main1",WINDOW_NORMAL);
- namedWindow("main2",WINDOW_AUTOSIZE | CV_GUI_NORMAL);
+ namedWindow("main2",WINDOW_AUTOSIZE | WINDOW_GUI_NORMAL);
createTrackbar( "track1", "main1", &value, 255, NULL);
String nameb1 = "button1";
@@ -178,6 +179,9 @@ namespace cv
//! @addtogroup highgui
//! @{
+//! @addtogroup highgui_window_flags
+//! @{
+
//! Flags for cv::namedWindow
enum WindowFlags {
WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size.
@@ -227,6 +231,11 @@ enum MouseEventFlags {
EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed.
};
+//! @} highgui_window_flags
+
+//! @addtogroup highgui_qt
+//! @{
+
//! Qt font weight
enum QtFontWeights {
QT_FONT_LIGHT = 25, //!< Weight of 25
@@ -251,6 +260,8 @@ enum QtButtonTypes {
QT_NEW_BUTTONBAR = 1024 //!< Button should create a new buttonbar
};
+//! @} highgui_qt
+
/** @brief Callback function for mouse events. see cv::setMouseCallback
@param event one of the cv::MouseEventTypes constants.
@param x The x-coordinate of the mouse event.
@@ -389,7 +400,7 @@ videos, it will display the video frame-by-frame)
*/
CV_EXPORTS_W void imshow(const String& winname, InputArray mat);
-/** @brief Resizes window to the specified size
+/** @brief Resizes the window to the specified size
@note
@@ -408,7 +419,7 @@ CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height);
*/
CV_EXPORTS_W void resizeWindow(const String& winname, const cv::Size& size);
-/** @brief Moves window to the specified position
+/** @brief Moves the window to the specified position
@param winname Name of the window.
@param x The new x-coordinate of the window.
@@ -476,8 +487,6 @@ For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward
respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and
left scrolling, respectively.
-With the C API, the macro CV_GET_WHEEL_DELTA(flags) can be used alternatively.
-
@note
Mouse-wheel events are currently supported only on Windows.
@@ -486,8 +495,9 @@ Mouse-wheel events are currently supported only on Windows.
*/
CV_EXPORTS int getMouseWheelDelta(int flags);
-/** @brief Selects ROI on the given image.
-Function creates a window and allows user to select a ROI using mouse.
+/** @brief Allows users to select a ROI on the given image.
+
+The function creates a window and allows users to select a ROI using the mouse.
Controls: use `space` or `enter` to finish selection, use key `c` to cancel selection (function will return the zero cv::Rect).
@param windowName name of the window where selection process will be shown.
@@ -506,8 +516,9 @@ CV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showC
*/
CV_EXPORTS_W Rect selectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false);
-/** @brief Selects ROIs on the given image.
-Function creates a window and allows user to select a ROIs using mouse.
+/** @brief Allows users to select multiple ROIs on the given image.
+
+The function creates a window and allows users to select multiple ROIs using the mouse.
Controls: use `space` or `enter` to finish current selection and start a new one,
use `esc` to terminate multiple ROI selection process.
@@ -533,7 +544,7 @@ displayed in the specified window winname.
@note
-[__Qt Backend Only__] winname can be empty if the trackbar should be attached to the
+[__Qt Backend Only__] winname can be empty (or NULL) if the trackbar should be attached to the
control panel.
Clicking the label of each trackbar enables editing the trackbar values manually.
@@ -561,7 +572,7 @@ The function returns the current position of the specified trackbar.
@note
-[__Qt Backend Only__] winname can be empty if the trackbar is attached to the control
+[__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control
panel.
@param trackbarname Name of the trackbar.
@@ -575,7 +586,7 @@ The function sets the position of the specified trackbar in the specified window
@note
-[__Qt Backend Only__] winname can be empty if the trackbar is attached to the control
+[__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control
panel.
@param trackbarname Name of the trackbar.
@@ -590,7 +601,7 @@ The function sets the maximum position of the specified trackbar in the specifie
@note
-[__Qt Backend Only__] winname can be empty if the trackbar is attached to the control
+[__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control
panel.
@param trackbarname Name of the trackbar.
@@ -605,7 +616,7 @@ The function sets the minimum position of the specified trackbar in the specifie
@note
-[__Qt Backend Only__] winname can be empty if the trackbar is attached to the control
+[__Qt Backend Only__] winname can be empty (or NULL) if the trackbar is attached to the control
panel.
@param trackbarname Name of the trackbar.
@@ -812,7 +823,7 @@ QT_NEW_BUTTONBAR flag is added to the type.
See below various examples of the cv::createButton function call: :
@code
- createButton("",callbackButton);//create a push button "button 0", that will call callbackButton.
+ createButton(NULL,callbackButton);//create a push button "button 0", that will call callbackButton.
createButton("button2",callbackButton,NULL,QT_CHECKBOX,0);
createButton("button3",callbackButton,&value);
createButton("button5",callbackButton1,NULL,QT_RADIOBOX);
@@ -839,4 +850,8 @@ CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change,
} // cv
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/highgui/highgui_c.h"
+#endif
+
#endif
diff --git a/include/opencv2/imgcodecs.hpp b/include/opencv2/imgcodecs.hpp
index 143926b..7f6b24f 100755
--- a/include/opencv2/imgcodecs.hpp
+++ b/include/opencv2/imgcodecs.hpp
@@ -49,6 +49,7 @@
@defgroup imgcodecs Image file reading and writing
@{
@defgroup imgcodecs_c C API
+ @defgroup imgcodecs_flags Flags used for image file reading and writing
@defgroup imgcodecs_ios iOS glue
@}
*/
@@ -60,9 +61,12 @@ namespace cv
//! @addtogroup imgcodecs
//! @{
+//! @addtogroup imgcodecs_flags
+//! @{
+
//! Imread flags
enum ImreadModes {
- IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
+ IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation.
IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion).
IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image.
IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
@@ -92,11 +96,10 @@ enum ImwriteFlags {
IMWRITE_EXR_TYPE = (3 << 4) + 0, /* 48 */ //!< override EXR storage type (FLOAT (FP32) is default)
IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used.
IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format
- IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values
- IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI
- IMWRITE_TIFF_YDPI = 258, //!< For TIFF, use to specify the Y direction DPI
- IMWRITE_TIFF_COMPRESSION = 259, //!< For TIFF, use to specify the image compression scheme. See libtiff for integer constants corresponding to compression formats. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default.
- IMWRITE_JPEG2000_COMPRESSION_X1000 = 272 //!< For JPEG2000, use to specify the target compression rate (multiplied by 1000). The value can be from 0 to 1000. Default is 1000.
+ IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values.
+ IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI.
+ IMWRITE_TIFF_YDPI = 258, //!< For TIFF, use to specify the Y direction DPI.
+ IMWRITE_TIFF_COMPRESSION = 259 //!< For TIFF, use to specify the image compression scheme. See libtiff for integer constants corresponding to compression formats. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default.
};
enum ImwriteEXRTypeFlags {
@@ -131,6 +134,8 @@ enum ImwritePAMFlags {
IMWRITE_PAM_FORMAT_RGB_ALPHA = 5,
};
+//! @} imgcodecs_flags
+
/** @brief Loads an image from a file.
@anchor imread
@@ -147,7 +152,6 @@ Currently, the following file formats are supported:
- Portable Network Graphics - \*.png (see the *Note* section)
- WebP - \*.webp (see the *Note* section)
- Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported)
-- PFM files - \*.pfm (see the *Note* section)
- Sun rasters - \*.sr, \*.ras (always supported)
- TIFF files - \*.tiff, \*.tif (see the *Note* section)
- OpenEXR Image files - \*.exr (see the *Note* section)
@@ -172,9 +176,9 @@ Currently, the following file formats are supported:
then the [GDAL](http://www.gdal.org) driver will be used in order to decode the image, supporting
the following formats: [Raster](http://www.gdal.org/formats_list.html),
[Vector](http://www.gdal.org/ogr_formats.html).
-- If EXIF information are embedded in the image file, the EXIF orientation will be taken into account
- and thus the image will be rotated accordingly except if the flag @ref IMREAD_IGNORE_ORIENTATION is passed.
-- Use the IMREAD_UNCHANGED flag to keep the floating point values from PFM image.
+- If EXIF information is embedded in the image file, the EXIF orientation will be taken into account
+ and thus the image will be rotated accordingly except if the flags @ref IMREAD_IGNORE_ORIENTATION
+ or @ref IMREAD_UNCHANGED are passed.
- By default number of pixels must be less than 2^30. Limit can be set using system
variable OPENCV_IO_MAX_IMAGE_PIXELS
@@ -201,27 +205,35 @@ single-channel or 3-channel (with 'BGR' channel order) images
can be saved using this function, with these exceptions:
- 16-bit unsigned (CV_16U) images can be saved in the case of PNG, JPEG 2000, and TIFF formats
-- 32-bit float (CV_32F) images can be saved in PFM, TIFF, OpenEXR, and Radiance HDR formats;
- 3-channel (CV_32FC3) TIFF images will be saved using the LogLuv high dynamic range encoding
- (4 bytes per pixel)
+- 32-bit float (CV_32F) images can be saved in TIFF, OpenEXR, and Radiance HDR formats; 3-channel
+(CV_32FC3) TIFF images will be saved using the LogLuv high dynamic range encoding (4 bytes per pixel)
- PNG images with an alpha channel can be saved using this function. To do this, create
8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels
should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below).
+- Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below).
If the format, depth or channel order is different, use
Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O
functions to save the image to XML or YAML format.
-The sample below shows how to create a BGRA image and save it to a PNG file. It also demonstrates how to set custom
-compression parameters:
+The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file.
+It also demonstrates how to save multiple images in a TIFF file:
@include snippets/imgcodecs_imwrite.cpp
@param filename Name of the file.
-@param img Image to be saved.
+@param img (Mat or vector of Mat) Image or Images to be saved.
@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags
*/
CV_EXPORTS_W bool imwrite( const String& filename, InputArray img,
const std::vector<int>& params = std::vector<int>());
+/// @overload multi-image overload for bindings
+CV_WRAP static inline
+bool imwritemulti(const String& filename, InputArrayOfArrays img,
+ const std::vector<int>& params = std::vector<int>())
+{
+ return imwrite(filename, img, params);
+}
+
/** @brief Reads an image from a buffer in memory.
The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or
@@ -257,19 +269,6 @@ CV_EXPORTS_W bool imencode( const String& ext, InputArray img,
CV_OUT std::vector<uchar>& buf,
const std::vector<int>& params = std::vector<int>());
-/** @brief Returns true if the specified image can be decoded by OpenCV
-
-@param filename File name of the image
-*/
-CV_EXPORTS_W bool haveImageReader( const String& filename );
-
-/** @brief Returns true if an image with the specified filename can be encoded by OpenCV
-
- @param filename File name of the image
- */
-CV_EXPORTS_W bool haveImageWriter( const String& filename );
-
-
//! @} imgcodecs
} // cv
diff --git a/include/opencv2/imgproc.hpp b/include/opencv2/imgproc.hpp
index e5af81a..2739d28 100755
--- a/include/opencv2/imgproc.hpp
+++ b/include/opencv2/imgproc.hpp
@@ -204,10 +204,6 @@ namespace cv
//! @addtogroup imgproc_filter
//! @{
-enum SpecialFilter {
- FILTER_SCHARR = -1
-};
-
//! type of morphological operation
enum MorphTypes{
MORPH_ERODE = 0, //!< see #erode
@@ -230,7 +226,7 @@ enum MorphTypes{
enum MorphShapes {
MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f]
MORPH_CROSS = 1, //!< a cross-shaped structuring element:
- //!< \f[E_{ij} = \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}\f]
+ //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f]
MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed
//!< into the rectangle Rect(0, 0, esize.width, 0.esize.height)
};
@@ -256,6 +252,9 @@ enum InterpolationFlags{
INTER_LANCZOS4 = 4,
/** Bit exact bilinear interpolation */
INTER_LINEAR_EXACT = 5,
+ /** Bit exact nearest neighbor interpolation. This will produce same results as
+ the nearest neighbor method in PIL, scikit-image or Matlab. */
+ INTER_NEAREST_EXACT = 6,
/** mask for interpolation codes */
INTER_MAX = 7,
/** flag, fills all of the destination image pixels. If some of them correspond to outliers in the
@@ -337,6 +336,12 @@ enum AdaptiveThresholdTypes {
ADAPTIVE_THRESH_GAUSSIAN_C = 1
};
+//! cv::undistort mode
+enum UndistortTypes {
+ PROJ_SPHERICAL_ORTHO = 0,
+ PROJ_SPHERICAL_EQRECT = 1
+ };
+
//! class of the pixel in GrabCut algorithm
enum GrabCutClasses {
GC_BGD = 0, //!< an obvious background pixels
@@ -385,7 +390,7 @@ enum FloodFillFlags {
//! @addtogroup imgproc_shape
//! @{
-//! connected components algorithm output formats
+//! connected components statistics
enum ConnectedComponentsTypes {
CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding
//!< box in the horizontal direction.
@@ -401,7 +406,7 @@ enum ConnectedComponentsTypes {
//! connected components algorithm
enum ConnectedComponentsAlgorithmsTypes {
- CCL_WU = 0, //!< SAUF algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
+ CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
CCL_DEFAULT = -1, //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
CCL_GRANA = 1 //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
};
@@ -797,45 +802,6 @@ enum RectanglesIntersectTypes {
INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other
};
-/** types of line
-@ingroup imgproc_draw
-*/
-enum LineTypes {
- FILLED = -1,
- LINE_4 = 4, //!< 4-connected line
- LINE_8 = 8, //!< 8-connected line
- LINE_AA = 16 //!< antialiased line
-};
-
-/** Only a subset of Hershey fonts <https://en.wikipedia.org/wiki/Hershey_fonts> are supported
-@ingroup imgproc_draw
-*/
-enum HersheyFonts {
- FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font
- FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font
- FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
- FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font
- FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
- FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
- FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
- FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
- FONT_ITALIC = 16 //!< flag for italic font
-};
-
-/** Possible set of marker types used for the cv::drawMarker function
-@ingroup imgproc_draw
-*/
-enum MarkerTypes
-{
- MARKER_CROSS = 0, //!< A crosshair marker shape
- MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape
- MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross
- MARKER_DIAMOND = 3, //!< A diamond marker shape
- MARKER_SQUARE = 4, //!< A square marker shape
- MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape
- MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape
-};
-
/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
*/
class CV_EXPORTS_W GeneralizedHough : public Algorithm
@@ -1355,14 +1321,14 @@ CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F
/** @brief Returns filter coefficients for computing spatial image derivatives.
The function computes and returns the filter coefficients for spatial image derivatives. When
-`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel
+`ksize=CV_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel
kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to
@param kx Output matrix of row filter coefficients. It has the type ktype .
@param ky Output matrix of column filter coefficients. It has the type ktype .
@param dx Derivative order in respect of x.
@param dy Derivative order in respect of y.
-@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7.
+@param ksize Aperture size. It can be CV_SCHARR, 1, 3, 5, or 7.
@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not.
Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are
going to filter floating-point images, you are likely to use the normalized kernels. But if you
@@ -1446,7 +1412,7 @@ equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width an
respectively (see #getGaussianKernel for details); to fully control the result regardless of
possible future modifications of all this semantics, it is recommended to specify all of ksize,
sigmaX, and sigmaY.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur
*/
@@ -1494,7 +1460,7 @@ The function smooths an image using the kernel:
where
-\f[\alpha = \fork{\frac{1}{\texttt{ksize.width*ksize.height}}}{when \texttt{normalize=true}}{1}{otherwise}\f]
+\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f]
Unnormalized box filter is useful for computing various integral characteristics over each pixel
neighborhood, such as covariance matrices of image derivatives (used in dense optical flow
@@ -1507,7 +1473,7 @@ algorithms, and so on). If you need to compute pixel sums over variable-size win
@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
center.
@param normalize flag, specifying whether the kernel is normalized by its area or not.
-@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes
+@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
@sa blur, bilateralFilter, GaussianBlur, medianBlur, integral
*/
CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth,
@@ -1530,7 +1496,7 @@ variance and standard deviation around the neighborhood of a pixel.
@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel
center.
@param normalize flag, specifying whether the kernel is to be normalized by it's area or not.
-@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes
+@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
@sa boxFilter
*/
CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth,
@@ -1544,7 +1510,7 @@ The function smooths an image using the kernel:
\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f]
-The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(),
+The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize,
anchor, true, borderType)`.
@param src input image; it can have any number of channels, which are processed independently, but
@@ -1553,7 +1519,7 @@ the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
@param ksize blurring kernel size.
@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
center.
-@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes
+@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur
*/
CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
@@ -1568,7 +1534,7 @@ according to the specified border mode.
The function does actually compute correlation, not the convolution:
-\f[\texttt{dst} (x,y) = \sum _{ \stackrel{0\leq x' < \texttt{kernel.cols},}{0\leq y' < \texttt{kernel.rows}} } \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f]
+\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f]
That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip
the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows -
@@ -1587,7 +1553,7 @@ separate color planes using split and process them individually.
the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor
is at the kernel center.
@param delta optional value added to the filtered pixels before storing them in dst.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa sepFilter2D, dft, matchTemplate
*/
CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth,
@@ -1608,7 +1574,7 @@ kernel kernelY. The final result shifted by delta is stored in dst .
@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor
is at the kernel center.
@param delta Value added to the filtered results before storing them.
-@param borderType Pixel extrapolation method, see #BorderTypes
+@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa filter2D, Sobel, GaussianBlur, boxFilter, blur
*/
CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth,
@@ -1629,7 +1595,7 @@ calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or
kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first
or the second x- or y- derivatives.
-There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr
+There is also the special value `ksize = #CV_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr
filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is
\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f]
@@ -1661,7 +1627,7 @@ The second case corresponds to a kernel of:
@param scale optional scale factor for the computed derivative values; by default, no scaling is
applied (see #getDerivKernels for details).
@param delta optional delta value that is added to the results prior to storing them in dst.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar
*/
CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth,
@@ -1682,7 +1648,8 @@ Sobel( src, dy, CV_16SC1, 0, 1, 3 );
@param dx output image with first-order derivative in x.
@param dy output image with first-order derivative in y.
@param ksize size of Sobel kernel. It must be 3.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes.
+ Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported.
@sa Sobel
*/
@@ -1700,7 +1667,7 @@ call
is equivalent to
-\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f]
+\f[\texttt{Sobel(src, dst, ddepth, dx, dy, CV_SCHARR, scale, delta, borderType)} .\f]
@param src input image.
@param dst output image of the same size and the same number of channels as src.
@@ -1710,7 +1677,7 @@ is equivalent to
@param scale optional scale factor for the computed derivative values; by default, no scaling is
applied (see #getDerivKernels for details).
@param delta optional delta value that is added to the results prior to storing them in dst.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa cartToPolar
*/
CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth,
@@ -1741,7 +1708,7 @@ details. The size must be positive and odd.
@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is
applied. See #getDerivKernels for details.
@param delta Optional delta value that is added to the results prior to storing them in dst .
-@param borderType Pixel extrapolation method, see #BorderTypes
+@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@sa Sobel, Scharr
*/
CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth,
@@ -1810,7 +1777,7 @@ of the formulae in the cornerEigenValsAndVecs description.
src .
@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
@param ksize Aperture parameter for the Sobel operator.
-@param borderType Pixel extrapolation method. See #BorderTypes.
+@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
*/
CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst,
int blockSize, int ksize = 3,
@@ -1833,7 +1800,7 @@ size as src .
@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
@param ksize Aperture parameter for the Sobel operator.
@param k Harris detector free parameter. See the formula above.
-@param borderType Pixel extrapolation method. See #BorderTypes.
+@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
*/
CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize,
int ksize, double k,
@@ -1861,7 +1828,7 @@ The output of the function can be used for robust edge or corner detection.
@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) .
@param blockSize Neighborhood size (see details below).
@param ksize Aperture parameter for the Sobel operator.
-@param borderType Pixel extrapolation method. See #BorderTypes.
+@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
@sa cornerMinEigenVal, cornerHarris, preCornerDetect
*/
@@ -1890,15 +1857,15 @@ The corners can be found as local maximums of the functions, as shown below:
@param src Source single-channel 8-bit of floating-point image.
@param dst Output image that has the type CV_32F and the same size as src .
@param ksize %Aperture size of the Sobel .
-@param borderType Pixel extrapolation method. See #BorderTypes.
+@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
*/
CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize,
int borderType = BORDER_DEFAULT );
/** @brief Refines the corner locations.
-The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as
-shown on the figure below.
+The function iterates to find the sub-pixel accurate location of corners or radial saddle
+points as described in @cite forstner1987fast, and as shown on the figure below.
![image](pics/cornersubpix.png)
@@ -2154,7 +2121,7 @@ structuring element is used. Kernel can be created using #getStructuringElement.
@param anchor position of the anchor within the element; default value (-1, -1) means that the
anchor is at the element center.
@param iterations number of times erosion is applied.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@param borderValue border value in case of a constant border
@sa dilate, morphologyEx, getStructuringElement
*/
@@ -2186,7 +2153,7 @@ structuring element is used. Kernel can be created using #getStructuringElement
@param anchor position of the anchor within the element; default value (-1, -1) means that the
anchor is at the element center.
@param iterations number of times dilation is applied.
-@param borderType pixel extrapolation method, see #BorderTypes
+@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported.
@param borderValue border value in case of a constant border
@sa erode, morphologyEx, getStructuringElement
*/
@@ -2211,7 +2178,7 @@ CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the
kernel center.
@param iterations Number of times erosion and dilation are applied.
-@param borderType Pixel extrapolation method, see #BorderTypes
+@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
@param borderValue Border value in case of a constant border. The default value has a special
meaning.
@sa dilate, erode, getStructuringElement
@@ -2299,7 +2266,7 @@ CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst,
const Scalar& borderValue = Scalar());
/** @example samples/cpp/warpPerspective_demo.cpp
-An example program shows using cv::findHomography and cv::warpPerspective for image warping
+An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping
*/
/** @brief Applies a perspective transformation to an image.
@@ -2353,8 +2320,8 @@ CV_32FC1, or CV_32FC2. See convertMaps for details on converting a floating poin
representation to fixed-point for speed.
@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map
if map1 is (x,y) points), respectively.
-@param interpolation Interpolation method (see #InterpolationFlags). The method #INTER_AREA is
-not supported by this function.
+@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA
+and #INTER_LINEAR_EXACT are not supported by this function.
@param borderMode Pixel extrapolation method (see #BorderTypes). When
borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that
corresponds to the "outliers" in the source image are not modified by the function.
@@ -2420,16 +2387,10 @@ coordinate origin is assumed to be the top-left corner).
@sa getAffineTransform, warpAffine, transform
*/
-CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale);
+CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale );
-/** @sa getRotationMatrix2D */
-CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale);
-
-inline
-Mat getRotationMatrix2D(Point2f center, double angle, double scale)
-{
- return Mat(getRotationMatrix2D_(center, angle, scale), true);
-}
+//! returns 3x3 perspective transformation for the corresponding 4 point pairs.
+CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] );
/** @brief Calculates an affine transform from three pairs of the corresponding points.
@@ -2473,15 +2434,10 @@ where
@param src Coordinates of quadrangle vertices in the source image.
@param dst Coordinates of the corresponding quadrangle vertices in the destination image.
-@param solveMethod method passed to cv::solve (#DecompTypes)
@sa findHomography, warpPerspective, perspectiveTransform
*/
-CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU);
-
-/** @overload */
-CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU);
-
+CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst );
CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst );
@@ -3005,6 +2961,193 @@ CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
//! @} imgproc_filter
+//! @addtogroup imgproc_transform
+//! @{
+
+/** @brief Transforms an image to compensate for lens distortion.
+
+The function transforms an image to compensate radial and tangential lens distortion.
+
+The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap
+(with bilinear interpolation). See the former function for details of the transformation being
+performed.
+
+Those pixels in the destination image, for which there is no correspondent pixels in the source
+image, are filled with zeros (black color).
+
+A particular subset of the source image that will be visible in the corrected image can be regulated
+by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate
+newCameraMatrix depending on your requirements.
+
+The camera matrix and the distortion parameters can be determined using #calibrateCamera. If
+the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
+f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
+the same.
+
+@param src Input (distorted) image.
+@param dst Output (corrected) image that has the same size and type as src .
+@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param distCoeffs Input vector of distortion coefficients
+\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
+of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
+@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
+cameraMatrix but you may additionally scale and shift the result by using a different matrix.
+ */
+CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
+ InputArray cameraMatrix,
+ InputArray distCoeffs,
+ InputArray newCameraMatrix = noArray() );
+
+/** @brief Computes the undistortion and rectification transformation map.
+
+The function computes the joint undistortion and rectification transformation and represents the
+result in the form of maps for remap. The undistorted image looks like original, as if it is
+captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
+monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
+#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
+newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
+
+Also, this new camera is oriented differently in the coordinate space, according to R. That, for
+example, helps to align two heads of a stereo camera so that the epipolar lines on both images
+become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
+
+The function actually builds the maps for the inverse mapping algorithm that is used by remap. That
+is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
+computes the corresponding coordinates in the source image (that is, in the original image from
+camera). The following process is applied:
+\f[
+\begin{array}{l}
+x \leftarrow (u - {c'}_x)/{f'}_x \\
+y \leftarrow (v - {c'}_y)/{f'}_y \\
+{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\
+x' \leftarrow X/W \\
+y' \leftarrow Y/W \\
+r^2 \leftarrow x'^2 + y'^2 \\
+x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
++ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\
+y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
++ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
+s\vecthree{x'''}{y'''}{1} =
+\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
+{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
+{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
+map_x(u,v) \leftarrow x''' f_x + c_x \\
+map_y(u,v) \leftarrow y''' f_y + c_y
+\end{array}
+\f]
+where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
+are the distortion coefficients.
+
+In case of a stereo camera, this function is called twice: once for each camera head, after
+stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera
+was not calibrated, it is still possible to compute the rectification transformations directly from
+the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes
+homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
+space. R can be computed from H as
+\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
+where cameraMatrix can be chosen arbitrarily.
+
+@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param distCoeffs Input vector of distortion coefficients
+\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
+of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
+@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
+computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
+is assumed. In cvInitUndistortMap R assumed to be an identity matrix.
+@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
+@param size Undistorted image size.
+@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
+@param map1 The first output map.
+@param map2 The second output map.
+ */
+CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs,
+ InputArray R, InputArray newCameraMatrix,
+ Size size, int m1type, OutputArray map1, OutputArray map2 );
+
+//! initializes maps for #remap for wide-angle
+CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs,
+ Size imageSize, int destImageWidth,
+ int m1type, OutputArray map1, OutputArray map2,
+ int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
+
+/** @brief Returns the default new camera matrix.
+
+The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
+centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
+
+In the latter case, the new camera matrix will be:
+
+\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f]
+
+where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
+
+By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not
+move the principal point. However, when you work with stereo, it is important to move the principal
+points in both views to the same y-coordinate (which is required by most of stereo correspondence
+algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
+each view where the principal points are located at the center.
+
+@param cameraMatrix Input camera matrix.
+@param imgsize Camera view image size in pixels.
+@param centerPrincipalPoint Location of the principal point in the new camera matrix. The
+parameter indicates whether this location should be at the image center or not.
+ */
+CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(),
+ bool centerPrincipalPoint = false );
+
+/** @brief Computes the ideal point coordinates from the observed point coordinates.
+
+The function is similar to #undistort and #initUndistortRectifyMap but it operates on a
+sparse set of points instead of a raster image. Also the function performs a reverse transformation
+to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
+planar object, it does, up to a translation vector, if the proper R is specified.
+
+For each observed point coordinate \f$(u, v)\f$ the function computes:
+\f[
+\begin{array}{l}
+x^{"} \leftarrow (u - c_x)/f_x \\
+y^{"} \leftarrow (v - c_y)/f_y \\
+(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
+{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
+x \leftarrow X/W \\
+y \leftarrow Y/W \\
+\text{only performed if P is specified:} \\
+u' \leftarrow x {f'}_x + {c'}_x \\
+v' \leftarrow y {f'}_y + {c'}_y
+\end{array}
+\f]
+
+where *undistort* is an approximate iterative algorithm that estimates the normalized original
+point coordinates out of the normalized distorted point coordinates ("normalized" means that the
+coordinates do not depend on the camera matrix).
+
+The function can be used for both a stereo camera head or a monocular camera (when R is empty).
+@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or
+vector\<Point2f\> ).
+@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\<Point2f\> ) after undistortion and reverse perspective
+transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.
+@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
+@param distCoeffs Input vector of distortion coefficients
+\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
+of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
+@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
+#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
+@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by
+#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used.
+ */
+CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst,
+ InputArray cameraMatrix, InputArray distCoeffs,
+ InputArray R = noArray(), InputArray P = noArray() );
+/** @overload
+ @note Default version of #undistortPoints does 5 iterations to compute undistorted points.
+
+ */
+CV_EXPORTS_AS(undistortPointsIter) void undistortPoints( InputArray src, OutputArray dst,
+ InputArray cameraMatrix, InputArray distCoeffs,
+ InputArray R, InputArray P, TermCriteria criteria );
+
+//! @} imgproc_transform
+
//! @addtogroup imgproc_hist
//! @{
@@ -3357,7 +3500,7 @@ but also identifies the nearest connected component consisting of zero pixels
(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the
component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function
automatically finds connected components of zero pixels in the input image and marks them with
-distinct labels. When labelType==#DIST_LABEL_CCOMP, the function scans through the input image and
+distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and
marks all the zero pixels with distinct labels.
In this mode, the complexity is still linear. That is, the function provides a very fast way to
@@ -3702,7 +3845,7 @@ image with 4 or 8 way connectivity - returns N, the total number of labels [0, N
represents the background label. ltype specifies the output label image type, an important
consideration based on the total number of labels or alternatively the total number of pixels in
the source image. ccltype specifies the connected components labeling algorithm to use, currently
-Grana (BBDT) and Wu's (SAUF) algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
+Grana (BBDT) and Wu's (SAUF) @cite Wu2009 algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
This function uses parallel version of both Grana and Wu's algorithms if at least one allowed
parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
@@ -3734,16 +3877,16 @@ image with 4 or 8 way connectivity - returns N, the total number of labels [0, N
represents the background label. ltype specifies the output label image type, an important
consideration based on the total number of labels or alternatively the total number of pixels in
the source image. ccltype specifies the connected components labeling algorithm to use, currently
-Grana's (BBDT) and Wu's (SAUF) algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
+Grana's (BBDT) and Wu's (SAUF) @cite Wu2009 algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
This function uses parallel version of both Grana and Wu's algorithms (statistics included) if at least one allowed
parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
@param image the 8-bit single-channel image to be labeled
@param labels destination labeled image
-@param stats statistics output for each label, including the background label, see below for
-available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
-#ConnectedComponentsTypes. The data type is CV_32S.
+@param stats statistics output for each label, including the background label.
+Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
+#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
@param centroids centroid output for each label, including the background label. Centroids are
accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
@@ -3757,9 +3900,9 @@ CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponents
/** @overload
@param image the 8-bit single-channel image to be labeled
@param labels destination labeled image
-@param stats statistics output for each label, including the background label, see below for
-available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
-#ConnectedComponentsTypes. The data type is CV_32S.
+@param stats statistics output for each label, including the background label.
+Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
+#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
@param centroids centroid output for each label, including the background label. Centroids are
accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
@@ -3795,12 +3938,12 @@ parent, or nested contours, the corresponding elements of hierarchy[i] will be n
contours are extracted from the image ROI and then they should be analyzed in the whole image
context.
*/
-CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours,
+CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method, Point offset = Point());
/** @overload */
-CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours,
+CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
int mode, int method, Point offset = Point());
/** @example samples/cpp/squares.cpp
@@ -4236,7 +4379,8 @@ enum ColormapTypes
COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg)
COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg)
COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg)
- COLORMAP_TURBO = 20 //!< ![turbo](pics/colormaps/colorscale_turbo.jpg)
+ COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg)
+ COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg)
};
/** @example samples/cpp/falsecolor.cpp
@@ -4325,7 +4469,7 @@ CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2,
use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and
r.br()-Point(1,1)` are opposite corners
*/
-CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec,
+CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
const Scalar& color, int thickness = 1,
int lineType = LINE_8, int shift = 0);
@@ -4395,6 +4539,18 @@ CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Sc
/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */
/* ----------------------------------------------------------------------------------------- */
+//! Possible set of marker types used for the cv::drawMarker function
+enum MarkerTypes
+{
+ MARKER_CROSS = 0, //!< A crosshair marker shape
+ MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape
+ MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross
+ MARKER_DIAMOND = 3, //!< A diamond marker shape
+ MARKER_SQUARE = 4, //!< A square marker shape
+ MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape
+ MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape
+};
+
/** @brief Draws a marker on a predefined position in an image.
The function cv::drawMarker draws a marker on a given position in the image. For the moment several
@@ -4408,7 +4564,7 @@ marker types are supported, see #MarkerTypes for more information.
@param line_type Type of the line, See #LineTypes
@param markerSize The length of the marker axis [default = 20 pixels]
*/
-CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color,
+CV_EXPORTS_W void drawMarker(CV_IN_OUT Mat& img, Point position, const Scalar& color,
int markerType = MARKER_CROSS, int markerSize=20, int thickness=1,
int line_type=8);
@@ -4417,7 +4573,7 @@ CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar&
/* ----------------------------------------------------------------------------------------- */
/** @overload */
-CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts,
+CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
const Scalar& color, int lineType = LINE_8,
int shift = 0);
@@ -4439,7 +4595,7 @@ CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
int shift = 0);
/** @overload */
-CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts,
+CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
const int* npts, int ncontours,
const Scalar& color, int lineType = LINE_8, int shift = 0,
Point offset = Point() );
@@ -4467,7 +4623,7 @@ CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
Point offset = Point() );
/** @overload */
-CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts,
+CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts,
int ncontours, bool isClosed, const Scalar& color,
int thickness = 1, int lineType = LINE_8, int shift = 0 );
@@ -4783,4 +4939,8 @@ Point LineIterator::pos() const
} // cv
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/imgproc/imgproc_c.h"
+#endif
+
#endif
diff --git a/include/opencv2/imgproc/detail/gcgraph.hpp b/include/opencv2/imgproc/detail/gcgraph.hpp
deleted file mode 100755
index db2ea0f..0000000
--- a/include/opencv2/imgproc/detail/gcgraph.hpp
+++ /dev/null
@@ -1,393 +0,0 @@
-/*M///////////////////////////////////////////////////////////////////////////////////////
-//
-// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
-//
-// By downloading, copying, installing or using the software you agree to this license.
-// If you do not agree to this license, do not download, install,
-// copy or use the software.
-//
-//
-// Intel License Agreement
-// For Open Source Computer Vision Library
-//
-// Copyright (C) 2000, Intel Corporation, all rights reserved.
-// Third party copyrights are property of their respective owners.
-//
-// Redistribution and use in source and binary forms, with or without modification,
-// are permitted provided that the following conditions are met:
-//
-// * Redistribution's of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// * Redistribution's in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-//
-// * The name of Intel Corporation may not be used to endorse or promote products
-// derived from this software without specific prior written permission.
-//
-// This software is provided by the copyright holders and contributors "as is" and
-// any express or implied warranties, including, but not limited to, the implied
-// warranties of merchantability and fitness for a particular purpose are disclaimed.
-// In no event shall the Intel Corporation or contributors be liable for any direct,
-// indirect, incidental, special, exemplary, or consequential damages
-// (including, but not limited to, procurement of substitute goods or services;
-// loss of use, data, or profits; or business interruption) however caused
-// and on any theory of liability, whether in contract, strict liability,
-// or tort (including negligence or otherwise) arising in any way out of
-// the use of this software, even if advised of the possibility of such damage.
-//
-//M*/
-
-#ifndef OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP
-#define OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP
-
-//! @cond IGNORED
-
-namespace cv { namespace detail {
-template <class TWeight> class GCGraph
-{
-public:
- GCGraph();
- GCGraph( unsigned int vtxCount, unsigned int edgeCount );
- ~GCGraph();
- void create( unsigned int vtxCount, unsigned int edgeCount );
- int addVtx();
- void addEdges( int i, int j, TWeight w, TWeight revw );
- void addTermWeights( int i, TWeight sourceW, TWeight sinkW );
- TWeight maxFlow();
- bool inSourceSegment( int i );
-private:
- class Vtx
- {
- public:
- Vtx *next; // initialized and used in maxFlow() only
- int parent;
- int first;
- int ts;
- int dist;
- TWeight weight;
- uchar t;
- };
- class Edge
- {
- public:
- int dst;
- int next;
- TWeight weight;
- };
-
- std::vector<Vtx> vtcs;
- std::vector<Edge> edges;
- TWeight flow;
-};
-
-template <class TWeight>
-GCGraph<TWeight>::GCGraph()
-{
- flow = 0;
-}
-template <class TWeight>
-GCGraph<TWeight>::GCGraph( unsigned int vtxCount, unsigned int edgeCount )
-{
- create( vtxCount, edgeCount );
-}
-template <class TWeight>
-GCGraph<TWeight>::~GCGraph()
-{
-}
-template <class TWeight>
-void GCGraph<TWeight>::create( unsigned int vtxCount, unsigned int edgeCount )
-{
- vtcs.reserve( vtxCount );
- edges.reserve( edgeCount + 2 );
- flow = 0;
-}
-
-template <class TWeight>
-int GCGraph<TWeight>::addVtx()
-{
- Vtx v;
- memset( &v, 0, sizeof(Vtx));
- vtcs.push_back(v);
- return (int)vtcs.size() - 1;
-}
-
-template <class TWeight>
-void GCGraph<TWeight>::addEdges( int i, int j, TWeight w, TWeight revw )
-{
- CV_Assert( i>=0 && i<(int)vtcs.size() );
- CV_Assert( j>=0 && j<(int)vtcs.size() );
- CV_Assert( w>=0 && revw>=0 );
- CV_Assert( i != j );
-
- if( !edges.size() )
- edges.resize( 2 );
-
- Edge fromI, toI;
- fromI.dst = j;
- fromI.next = vtcs[i].first;
- fromI.weight = w;
- vtcs[i].first = (int)edges.size();
- edges.push_back( fromI );
-
- toI.dst = i;
- toI.next = vtcs[j].first;
- toI.weight = revw;
- vtcs[j].first = (int)edges.size();
- edges.push_back( toI );
-}
-
-template <class TWeight>
-void GCGraph<TWeight>::addTermWeights( int i, TWeight sourceW, TWeight sinkW )
-{
- CV_Assert( i>=0 && i<(int)vtcs.size() );
-
- TWeight dw = vtcs[i].weight;
- if( dw > 0 )
- sourceW += dw;
- else
- sinkW -= dw;
- flow += (sourceW < sinkW) ? sourceW : sinkW;
- vtcs[i].weight = sourceW - sinkW;
-}
-
-template <class TWeight>
-TWeight GCGraph<TWeight>::maxFlow()
-{
- const int TERMINAL = -1, ORPHAN = -2;
- Vtx stub, *nilNode = &stub, *first = nilNode, *last = nilNode;
- int curr_ts = 0;
- stub.next = nilNode;
- Vtx *vtxPtr = &vtcs[0];
- Edge *edgePtr = &edges[0];
-
- std::vector<Vtx*> orphans;
-
- // initialize the active queue and the graph vertices
- for( int i = 0; i < (int)vtcs.size(); i++ )
- {
- Vtx* v = vtxPtr + i;
- v->ts = 0;
- if( v->weight != 0 )
- {
- last = last->next = v;
- v->dist = 1;
- v->parent = TERMINAL;
- v->t = v->weight < 0;
- }
- else
- v->parent = 0;
- }
- first = first->next;
- last->next = nilNode;
- nilNode->next = 0;
-
- // run the search-path -> augment-graph -> restore-trees loop
- for(;;)
- {
- Vtx* v, *u;
- int e0 = -1, ei = 0, ej = 0;
- TWeight minWeight, weight;
- uchar vt;
-
- // grow S & T search trees, find an edge connecting them
- while( first != nilNode )
- {
- v = first;
- if( v->parent )
- {
- vt = v->t;
- for( ei = v->first; ei != 0; ei = edgePtr[ei].next )
- {
- if( edgePtr[ei^vt].weight == 0 )
- continue;
- u = vtxPtr+edgePtr[ei].dst;
- if( !u->parent )
- {
- u->t = vt;
- u->parent = ei ^ 1;
- u->ts = v->ts;
- u->dist = v->dist + 1;
- if( !u->next )
- {
- u->next = nilNode;
- last = last->next = u;
- }
- continue;
- }
-
- if( u->t != vt )
- {
- e0 = ei ^ vt;
- break;
- }
-
- if( u->dist > v->dist+1 && u->ts <= v->ts )
- {
- // reassign the parent
- u->parent = ei ^ 1;
- u->ts = v->ts;
- u->dist = v->dist + 1;
- }
- }
- if( e0 > 0 )
- break;
- }
- // exclude the vertex from the active list
- first = first->next;
- v->next = 0;
- }
-
- if( e0 <= 0 )
- break;
-
- // find the minimum edge weight along the path
- minWeight = edgePtr[e0].weight;
- CV_Assert( minWeight > 0 );
- // k = 1: source tree, k = 0: destination tree
- for( int k = 1; k >= 0; k-- )
- {
- for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst )
- {
- if( (ei = v->parent) < 0 )
- break;
- weight = edgePtr[ei^k].weight;
- minWeight = MIN(minWeight, weight);
- CV_Assert( minWeight > 0 );
- }
- weight = fabs(v->weight);
- minWeight = MIN(minWeight, weight);
- CV_Assert( minWeight > 0 );
- }
-
- // modify weights of the edges along the path and collect orphans
- edgePtr[e0].weight -= minWeight;
- edgePtr[e0^1].weight += minWeight;
- flow += minWeight;
-
- // k = 1: source tree, k = 0: destination tree
- for( int k = 1; k >= 0; k-- )
- {
- for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst )
- {
- if( (ei = v->parent) < 0 )
- break;
- edgePtr[ei^(k^1)].weight += minWeight;
- if( (edgePtr[ei^k].weight -= minWeight) == 0 )
- {
- orphans.push_back(v);
- v->parent = ORPHAN;
- }
- }
-
- v->weight = v->weight + minWeight*(1-k*2);
- if( v->weight == 0 )
- {
- orphans.push_back(v);
- v->parent = ORPHAN;
- }
- }
-
- // restore the search trees by finding new parents for the orphans
- curr_ts++;
- while( !orphans.empty() )
- {
- Vtx* v2 = orphans.back();
- orphans.pop_back();
-
- int d, minDist = INT_MAX;
- e0 = 0;
- vt = v2->t;
-
- for( ei = v2->first; ei != 0; ei = edgePtr[ei].next )
- {
- if( edgePtr[ei^(vt^1)].weight == 0 )
- continue;
- u = vtxPtr+edgePtr[ei].dst;
- if( u->t != vt || u->parent == 0 )
- continue;
- // compute the distance to the tree root
- for( d = 0;; )
- {
- if( u->ts == curr_ts )
- {
- d += u->dist;
- break;
- }
- ej = u->parent;
- d++;
- if( ej < 0 )
- {
- if( ej == ORPHAN )
- d = INT_MAX-1;
- else
- {
- u->ts = curr_ts;
- u->dist = 1;
- }
- break;
- }
- u = vtxPtr+edgePtr[ej].dst;
- }
-
- // update the distance
- if( ++d < INT_MAX )
- {
- if( d < minDist )
- {
- minDist = d;
- e0 = ei;
- }
- for( u = vtxPtr+edgePtr[ei].dst; u->ts != curr_ts; u = vtxPtr+edgePtr[u->parent].dst )
- {
- u->ts = curr_ts;
- u->dist = --d;
- }
- }
- }
-
- if( (v2->parent = e0) > 0 )
- {
- v2->ts = curr_ts;
- v2->dist = minDist;
- continue;
- }
-
- /* no parent is found */
- v2->ts = 0;
- for( ei = v2->first; ei != 0; ei = edgePtr[ei].next )
- {
- u = vtxPtr+edgePtr[ei].dst;
- ej = u->parent;
- if( u->t != vt || !ej )
- continue;
- if( edgePtr[ei^(vt^1)].weight && !u->next )
- {
- u->next = nilNode;
- last = last->next = u;
- }
- if( ej > 0 && vtxPtr+edgePtr[ej].dst == v2 )
- {
- orphans.push_back(u);
- u->parent = ORPHAN;
- }
- }
- }
- }
- return flow;
-}
-
-template <class TWeight>
-bool GCGraph<TWeight>::inSourceSegment( int i )
-{
- CV_Assert( i>=0 && i<(int)vtcs.size() );
- return vtcs[i].t == 0;
-}
-
-}} // namespace detail, cv
-
-
-//! @endcond
-
-#endif // OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP
diff --git a/include/opencv2/imgproc/hal/hal.hpp b/include/opencv2/imgproc/hal/hal.hpp
index ac20725..a435fd6 100755
--- a/include/opencv2/imgproc/hal/hal.hpp
+++ b/include/opencv2/imgproc/hal/hal.hpp
@@ -108,7 +108,7 @@ CV_EXPORTS void warpAffine(int src_type,
uchar * dst_data, size_t dst_step, int dst_width, int dst_height,
const double M[6], int interpolation, int borderType, const double borderValue[4]);
-CV_EXPORTS void warpPerspective(int src_type,
+CV_EXPORTS void warpPerspectve(int src_type,
const uchar * src_data, size_t src_step, int src_width, int src_height,
uchar * dst_data, size_t dst_step, int dst_width, int dst_height,
const double M[9], int interpolation, int borderType, const double borderValue[4]);
diff --git a/include/opencv2/imgproc/imgproc_c.h b/include/opencv2/imgproc/imgproc_c.h
index 9f7131f..2fe85b6 100755
--- a/include/opencv2/imgproc/imgproc_c.h
+++ b/include/opencv2/imgproc/imgproc_c.h
@@ -273,6 +273,39 @@ CVAPI(void) cvLinearPolar( const CvArr* src, CvArr* dst,
CvPoint2D32f center, double maxRadius,
int flags CV_DEFAULT(CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS));
+/** @brief Transforms the input image to compensate lens distortion
+@see cv::undistort
+*/
+CVAPI(void) cvUndistort2( const CvArr* src, CvArr* dst,
+ const CvMat* camera_matrix,
+ const CvMat* distortion_coeffs,
+ const CvMat* new_camera_matrix CV_DEFAULT(0) );
+
+/** @brief Computes transformation map from intrinsic camera parameters
+ that can used by cvRemap
+*/
+CVAPI(void) cvInitUndistortMap( const CvMat* camera_matrix,
+ const CvMat* distortion_coeffs,
+ CvArr* mapx, CvArr* mapy );
+
+/** @brief Computes undistortion+rectification map for a head of stereo camera
+@see cv::initUndistortRectifyMap
+*/
+CVAPI(void) cvInitUndistortRectifyMap( const CvMat* camera_matrix,
+ const CvMat* dist_coeffs,
+ const CvMat *R, const CvMat* new_camera_matrix,
+ CvArr* mapx, CvArr* mapy );
+
+/** @brief Computes the original (undistorted) feature coordinates
+ from the observed (distorted) coordinates
+@see cv::undistortPoints
+*/
+CVAPI(void) cvUndistortPoints( const CvMat* src, CvMat* dst,
+ const CvMat* camera_matrix,
+ const CvMat* dist_coeffs,
+ const CvMat* R CV_DEFAULT(0),
+ const CvMat* P CV_DEFAULT(0));
+
/** @brief Returns a structuring element of the specified size and shape for morphological operations.
@note the created structuring element IplConvKernel\* element must be released in the end using
@@ -1151,7 +1184,7 @@ CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype );
/** @brief Returns the polygon points which make up the given ellipse.
The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial
-sweep of the ellipse arc can be done by spcifying arc_start and arc_end to be something other than
+sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than
0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total
number of points stored into 'pts' is returned by this function.
@see cv::ellipse2Poly
diff --git a/include/opencv2/objdetect.hpp b/include/opencv2/objdetect.hpp
index 1cbbf84..0387b10 100755
--- a/include/opencv2/objdetect.hpp
+++ b/include/opencv2/objdetect.hpp
@@ -91,7 +91,7 @@ compensate for the differences in the size of areas. The sums of pixel values ov
regions are calculated rapidly using integral images (see below and the integral description).
To see the object detector at work, have a look at the facedetect demo:
-<https://github.com/opencv/opencv/tree/master/samples/cpp/dbt_face_detection.cpp>
+<https://github.com/opencv/opencv/tree/3.4/samples/cpp/dbt_face_detection.cpp>
The following reference is for the detection part only. There is a separate application called
opencv_traincascade that can train a cascade of boosted classifiers from a set of samples.
@@ -163,7 +163,7 @@ CV_EXPORTS void groupRectangles_meanshift(std::vector<Rect>& rectList, std::ve
std::vector<double>& foundScales,
double detectThreshold = 0.0, Size winDetSize = Size(64, 128));
-template<> struct DefaultDeleter<CvHaarClassifierCascade>{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; };
+template<> CV_EXPORTS void DefaultDeleter<CvHaarClassifierCascade>::operator ()(CvHaarClassifierCascade* obj) const;
enum { CASCADE_DO_CANNY_PRUNING = 1,
CASCADE_SCALE_IMAGE = 2,
@@ -372,15 +372,13 @@ http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-
struct CV_EXPORTS_W HOGDescriptor
{
public:
- enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType
+ enum { L2Hys = 0 //!< Default histogramNormType
};
enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value.
};
- enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW };
-
/**@brief Creates the HOG descriptor and detector with default params.
- aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 )
+ aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9, 1 )
*/
CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8),
cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1),
@@ -404,7 +402,7 @@ public:
*/
CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride,
Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1,
- HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys,
+ int _histogramNormType=HOGDescriptor::L2Hys,
double _L2HysThreshold=0.2, bool _gammaCorrection=false,
int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false)
: winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize),
@@ -414,7 +412,7 @@ public:
{}
/** @overload
- @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier.
+ @param filename the file name containing HOGDescriptor properties and coefficients of the trained classifier
*/
CV_WRAP HOGDescriptor(const String& filename)
{
@@ -448,28 +446,28 @@ public:
/**@example samples/cpp/peopledetect.cpp
*/
/**@brief Sets coefficients for the linear SVM classifier.
- @param svmdetector coefficients for the linear SVM classifier.
+ @param _svmdetector coefficients for the linear SVM classifier.
*/
- CV_WRAP virtual void setSVMDetector(InputArray svmdetector);
+ CV_WRAP virtual void setSVMDetector(InputArray _svmdetector);
- /** @brief Reads HOGDescriptor parameters from a cv::FileNode.
+ /** @brief Reads HOGDescriptor parameters from a file node.
@param fn File node
*/
virtual bool read(FileNode& fn);
- /** @brief Stores HOGDescriptor parameters in a cv::FileStorage.
+ /** @brief Stores HOGDescriptor parameters in a file storage.
@param fs File storage
@param objname Object name
*/
virtual void write(FileStorage& fs, const String& objname) const;
- /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file.
- @param filename Path of the file to read.
+ /** @brief loads coefficients for the linear SVM classifier from a file
+ @param filename Name of the file to read.
@param objname The optional name of the node to read (if empty, the first top-level node will be used).
*/
CV_WRAP virtual bool load(const String& filename, const String& objname = String());
- /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file
+ /** @brief saves coefficients for the linear SVM classifier to a file
@param filename File name
@param objname Object name
*/
@@ -505,7 +503,7 @@ public:
@param padding Padding
@param searchLocations Vector of Point includes set of requested locations to be evaluated.
*/
- CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
+ CV_WRAP virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
CV_OUT std::vector<double>& weights,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
@@ -521,7 +519,7 @@ public:
@param padding Padding
@param searchLocations Vector of Point includes locations to search.
*/
- virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
+ virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
const std::vector<Point>& searchLocations=std::vector<Point>()) const;
@@ -570,7 +568,7 @@ public:
@param paddingTL Padding from top-left
@param paddingBR Padding from bottom-right
*/
- CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs,
+ CV_WRAP virtual void computeGradient(const Mat& img, CV_OUT Mat& grad, CV_OUT Mat& angleOfs,
Size paddingTL = Size(), Size paddingBR = Size()) const;
/** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows).
@@ -605,7 +603,7 @@ public:
CV_PROP double winSigma;
//! histogramNormType
- CV_PROP HOGDescriptor::HistogramNormType histogramNormType;
+ CV_PROP int histogramNormType;
//! L2-Hys normalization method shrinkage.
CV_PROP double L2HysThreshold;
@@ -639,7 +637,7 @@ public:
@param winStride winStride
@param padding padding
*/
- virtual void detectROI(InputArray img, const std::vector<cv::Point> &locations,
+ virtual void detectROI(const cv::Mat& img, const std::vector<cv::Point> &locations,
CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
double hitThreshold = 0, cv::Size winStride = Size(),
cv::Size padding = Size()) const;
@@ -652,12 +650,17 @@ public:
in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
*/
- virtual void detectMultiScaleROI(InputArray img,
+ virtual void detectMultiScaleROI(const cv::Mat& img,
CV_OUT std::vector<cv::Rect>& foundLocations,
std::vector<DetectionROI>& locations,
double hitThreshold = 0,
int groupThreshold = 0) const;
+ /** @brief read/parse Dalal's alt model file
+ @param modelfile Path of Dalal's alt model file.
+ */
+ void readALTModel(String modelfile);
+
/** @brief Groups the object candidate rectangles.
@param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.)
@param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.)
@@ -691,30 +694,147 @@ public:
CV_WRAP bool detect(InputArray img, OutputArray points) const;
/** @brief Decodes QR code in image once it's found by the detect() method.
+
Returns UTF8-encoded output string or empty string if the code cannot be decoded.
+ @param img grayscale or color (BGR) image containing QR code.
+ @param points Quadrangle vertices found by detect() method (or some other algorithm).
+ @param straight_qrcode The optional output image containing rectified and binarized QR code
+ */
+ CV_WRAP cv::String decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
+
+ /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method.
+ Returns UTF8-encoded output string or empty string if the code cannot be decoded.
@param img grayscale or color (BGR) image containing QR code.
@param points Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
- CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
+ CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
/** @brief Both detects and decodes QR code
@param img grayscale or color (BGR) image containing QR code.
- @param points opiotnal output array of vertices of the found QR code quadrangle. Will be empty if not found.
+ @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
+ @param straight_qrcode The optional output image containing rectified and binarized QR code
+ */
+ CV_WRAP cv::String detectAndDecode(InputArray img, OutputArray points=noArray(),
+ OutputArray straight_qrcode = noArray());
+
+ /** @brief Both detects and decodes QR code on a curved surface
+
+ @param img grayscale or color (BGR) image containing QR code.
+ @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
- CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points=noArray(),
- OutputArray straight_qrcode = noArray());
+ CV_WRAP cv::String detectAndDecodeCurved(InputArray img, OutputArray points=noArray(),
+ OutputArray straight_qrcode = noArray());
+
+ /** @brief Detects QR codes in image and returns the vector of the quadrangles containing the codes.
+ @param img grayscale or color (BGR) image containing (or not) QR codes.
+ @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes.
+ */
+ CV_WRAP
+ bool detectMulti(InputArray img, OutputArray points) const;
+
+ /** @brief Decodes QR codes in image once it's found by the detect() method.
+ @param img grayscale or color (BGR) image containing QR codes.
+ @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
+ @param points vector of Quadrangle vertices found by detect() method (or some other algorithm).
+ @param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
+ */
+ CV_WRAP
+ bool decodeMulti(
+ InputArray img, InputArray points,
+ CV_OUT std::vector<cv::String>& decoded_info,
+ OutputArrayOfArrays straight_qrcode = noArray()
+ ) const;
+
+ /** @brief Both detects and decodes QR codes
+ @param img grayscale or color (BGR) image containing QR codes.
+ @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
+ @param points optional output vector of vertices of the found QR code quadrangles. Will be empty if not found.
+ @param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
+ */
+ CV_WRAP
+ bool detectAndDecodeMulti(
+ InputArray img, CV_OUT std::vector<cv::String>& decoded_info,
+ OutputArray points = noArray(),
+ OutputArrayOfArrays straight_qrcode = noArray()
+ ) const;
+
+
+#ifndef CV_DOXYGEN // COMPATIBILITY
+ inline bool decodeMulti(
+ InputArray img, InputArray points,
+ CV_OUT std::vector<std::string>& decoded_info,
+ OutputArrayOfArrays straight_qrcode = noArray()
+ ) const
+ {
+ std::vector<cv::String> decoded_info_;
+ bool res = decodeMulti(img, points, decoded_info_, straight_qrcode);
+ decoded_info.resize(decoded_info_.size());
+ for (size_t i = 0; i < decoded_info.size(); ++i)
+ {
+ cv::String s; std::swap(s, decoded_info_[i]);
+ decoded_info[i] = s;
+ }
+ return res;
+ }
+
+ inline bool detectAndDecodeMulti(
+ InputArray img, CV_OUT std::vector<std::string>& decoded_info,
+ OutputArray points = noArray(),
+ OutputArrayOfArrays straight_qrcode = noArray()
+ ) const
+ {
+ std::vector<cv::String> decoded_info_;
+ bool res = detectAndDecodeMulti(img, decoded_info_, points, straight_qrcode);
+ decoded_info.resize(decoded_info_.size());
+ for (size_t i = 0; i < decoded_info.size(); ++i)
+ {
+ cv::String s; std::swap(s, decoded_info_[i]);
+ decoded_info[i] = s;
+ }
+ return res;
+ }
+#endif
+
protected:
struct Impl;
Ptr<Impl> p;
};
+/** @brief Detect QR code in image and return minimum area of quadrangle that describes QR code.
+ @param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
+ @param points Output vector of vertices of a quadrangle of minimal area that describes QR code.
+ @param eps_x Epsilon neighborhood, which allows you to determine the horizontal pattern of the scheme 1:1:3:1:1 according to QR code standard.
+ @param eps_y Epsilon neighborhood, which allows you to determine the vertical pattern of the scheme 1:1:3:1:1 according to QR code standard.
+ */
+CV_EXPORTS bool detectQRCode(InputArray in, std::vector<Point> &points, double eps_x = 0.2, double eps_y = 0.1);
+
+/** @brief Decode QR code in image and return text that is encrypted in QR code.
+ @param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
+ @param points Input vector of vertices of a quadrangle of minimal area that describes QR code.
+ @param decoded_info String information that is encrypted in QR code.
+ @param straight_qrcode Matrix of the type CV_8UC1 containing an binary straight QR code.
+ */
+CV_EXPORTS bool decodeQRCode(InputArray in, InputArray points, std::string &decoded_info, OutputArray straight_qrcode = noArray());
+
+/** @brief Decode QR code on a curved surface in image and return text that is encrypted in QR code.
+ @param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
+ @param points Input vector of vertices of a quadrangle of minimal area that describes QR code.
+ @param decoded_info String information that is encrypted in QR code.
+ @param straight_qrcode Matrix of the type CV_8UC1 containing an binary straight QR code.
+ */
+CV_EXPORTS bool decodeCurvedQRCode(InputArray in, InputArray points, std::string &decoded_info, OutputArray straight_qrcode = noArray());
+
//! @} objdetect
}
#include "opencv2/objdetect/detection_based_tracker.hpp"
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/objdetect/objdetect_c.h"
+#endif
+
#endif
diff --git a/include/opencv2/objdetect/detection_based_tracker.hpp b/include/opencv2/objdetect/detection_based_tracker.hpp
index 18cde13..07dd587 100755
--- a/include/opencv2/objdetect/detection_based_tracker.hpp
+++ b/include/opencv2/objdetect/detection_based_tracker.hpp
@@ -46,6 +46,10 @@
#include <opencv2/core.hpp>
+// After this condition removal update blacklist for bindings: modules/python/common.cmake
+#if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(__ANDROID__) || \
+ defined(CV_CXX11)
+
#include <vector>
namespace cv
@@ -218,5 +222,6 @@ class CV_EXPORTS DetectionBasedTracker
//! @} objdetect
} //end of cv namespace
+#endif
#endif
diff --git a/include/opencv2/objdetect/objdetect_c.h b/include/opencv2/objdetect/objdetect_c.h
index b3ee7f4..67dc2f4 100755
--- a/include/opencv2/objdetect/objdetect_c.h
+++ b/include/opencv2/objdetect/objdetect_c.h
@@ -69,6 +69,7 @@ extern "C" {
(((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL)
#define CV_HAAR_FEATURE_MAX 3
+#define CV_HAAR_STAGE_MAX 1000
typedef struct CvHaarFeature
{
diff --git a/include/opencv2/opencv_modules.hpp b/include/opencv2/opencv_modules.hpp
index 370d501..d0f2dc5 100755
--- a/include/opencv2/opencv_modules.hpp
+++ b/include/opencv2/opencv_modules.hpp
@@ -10,53 +10,23 @@
// For example, patented algorithms for non-profit/non-commercial use only.
/* #undef OPENCV_ENABLE_NONFREE */
-#define HAVE_OPENCV_ARUCO
-#define HAVE_OPENCV_BGSEGM
-#define HAVE_OPENCV_BIOINSPIRED
#define HAVE_OPENCV_CALIB3D
-#define HAVE_OPENCV_CCALIB
#define HAVE_OPENCV_CORE
-#define HAVE_OPENCV_DATASETS
#define HAVE_OPENCV_DNN
-#define HAVE_OPENCV_DNN_OBJDETECT
-#define HAVE_OPENCV_DNN_SUPERRES
-#define HAVE_OPENCV_DPM
-#define HAVE_OPENCV_FACE
#define HAVE_OPENCV_FEATURES2D
#define HAVE_OPENCV_FLANN
-#define HAVE_OPENCV_FREETYPE
-#define HAVE_OPENCV_FUZZY
-#define HAVE_OPENCV_HDF
-#define HAVE_OPENCV_HFS
#define HAVE_OPENCV_HIGHGUI
-#define HAVE_OPENCV_IMG_HASH
#define HAVE_OPENCV_IMGCODECS
#define HAVE_OPENCV_IMGPROC
-#define HAVE_OPENCV_LINE_DESCRIPTOR
#define HAVE_OPENCV_ML
#define HAVE_OPENCV_OBJDETECT
-#define HAVE_OPENCV_OPTFLOW
-#define HAVE_OPENCV_PHASE_UNWRAPPING
#define HAVE_OPENCV_PHOTO
-#define HAVE_OPENCV_PLOT
-#define HAVE_OPENCV_QUALITY
-#define HAVE_OPENCV_REG
-#define HAVE_OPENCV_RGBD
-#define HAVE_OPENCV_SALIENCY
#define HAVE_OPENCV_SHAPE
-#define HAVE_OPENCV_STEREO
#define HAVE_OPENCV_STITCHING
-#define HAVE_OPENCV_STRUCTURED_LIGHT
#define HAVE_OPENCV_SUPERRES
-#define HAVE_OPENCV_SURFACE_MATCHING
-#define HAVE_OPENCV_TEXT
-#define HAVE_OPENCV_TRACKING
#define HAVE_OPENCV_VIDEO
#define HAVE_OPENCV_VIDEOIO
#define HAVE_OPENCV_VIDEOSTAB
-#define HAVE_OPENCV_VIZ
-#define HAVE_OPENCV_XIMGPROC
-#define HAVE_OPENCV_XOBJDETECT
-#define HAVE_OPENCV_XPHOTO
+#define HAVE_OPENCV_WORLD
diff --git a/include/opencv2/photo.hpp b/include/opencv2/photo.hpp
index a445dd3..a457295 100755
--- a/include/opencv2/photo.hpp
+++ b/include/opencv2/photo.hpp
@@ -48,15 +48,36 @@
/**
@defgroup photo Computational Photography
+
+This module includes photo processing algorithms
@{
+ @defgroup photo_inpaint Inpainting
@defgroup photo_denoise Denoising
@defgroup photo_hdr HDR imaging
This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment,
camera calibration with multiple exposures and exposure fusion.
+ @defgroup photo_decolor Contrast Preserving Decolorization
+
+Useful links:
+
+http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html
+
@defgroup photo_clone Seamless Cloning
+
+Useful links:
+
+https://www.learnopencv.com/seamless-cloning-using-opencv-python-cpp
+
@defgroup photo_render Non-Photorealistic Rendering
+
+Useful links:
+
+http://www.inf.ufrgs.br/~eslgastal/DomainTransform
+
+https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/
+
@defgroup photo_c C API
@}
*/
@@ -67,37 +88,24 @@ namespace cv
//! @addtogroup photo
//! @{
+//! @addtogroup photo_inpaint
+//! @{
//! the inpainting algorithm
enum
{
- INPAINT_NS = 0, // Navier-Stokes algorithm
- INPAINT_TELEA = 1 // A. Telea algorithm
-};
-
-enum
-{
- NORMAL_CLONE = 1,
- MIXED_CLONE = 2,
- MONOCHROME_TRANSFER = 3
-};
-
-enum
-{
- RECURS_FILTER = 1,
- NORMCONV_FILTER = 2
+ INPAINT_NS = 0, //!< Use Navier-Stokes based method
+ INPAINT_TELEA = 1 //!< Use the algorithm proposed by Alexandru Telea @cite Telea04
};
/** @brief Restores the selected region in an image using the region neighborhood.
-@param src Input 8-bit 1-channel or 3-channel image.
+@param src Input 8-bit, 16-bit unsigned or 32-bit float 1-channel or 8-bit 3-channel image.
@param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that
needs to be inpainted.
@param dst Output image with the same size and type as src .
@param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered
by the algorithm.
-@param flags Inpainting method that could be one of the following:
-- **INPAINT_NS** Navier-Stokes based method [Navier01]
-- **INPAINT_TELEA** Method by Alexandru Telea @cite Telea04 .
+@param flags Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA
The function reconstructs the selected image area from the pixel near the area boundary. The
function may be used to remove dust and scratches from a scanned photo, or to remove undesirable
@@ -106,12 +114,14 @@ objects from still images or video. See <http://en.wikipedia.org/wiki/Inpainting
@note
- An example using the inpainting technique can be found at
opencv_source_code/samples/cpp/inpaint.cpp
- - (Python) An example using the inpainting technique can be found at
+ - (Python) An example using the inpainting technique can be found at
opencv_source_code/samples/python/inpaint.py
*/
CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask,
OutputArray dst, double inpaintRadius, int flags );
+//! @} photo_inpaint
+
//! @addtogroup photo_denoise
//! @{
@@ -189,7 +199,7 @@ CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst,
float h = 3, float hColor = 3,
int templateWindowSize = 7, int searchWindowSize = 21);
-/** @brief Modification of fastNlMeansDenoising function for images sequence where consequtive images have been
+/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been
captured in small period of time. For example video. This version of the function is for grayscale
images or for manual manipulation with colorspaces. For more details see
<http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.131.6394>
@@ -216,7 +226,7 @@ CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputA
int imgToDenoiseIndex, int temporalWindowSize,
float h = 3, int templateWindowSize = 7, int searchWindowSize = 21);
-/** @brief Modification of fastNlMeansDenoising function for images sequence where consequtive images have been
+/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been
captured in small period of time. For example video. This version of the function is for grayscale
images or for manual manipulation with colorspaces. For more details see
<http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.131.6394>
@@ -328,8 +338,8 @@ class CV_EXPORTS_W Tonemap : public Algorithm
public:
/** @brief Tonemaps image
- @param src source image - 32-bit 3-channel Mat
- @param dst destination image - 32-bit 3-channel Mat with values in [0, 1] range
+ @param src source image - CV_32FC3 Mat (float 32 bits 3 channels)
+ @param dst destination image - CV_32FC3 Mat with values in [0, 1] range
*/
CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0;
@@ -376,43 +386,6 @@ results, default value is 0.85.
*/
CV_EXPORTS_W Ptr<TonemapDrago> createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f);
-/** @brief This algorithm decomposes image into two layers: base layer and detail layer using bilateral filter
-and compresses contrast of the base layer thus preserving all the details.
-
-This implementation uses regular bilateral filter from opencv.
-
-Saturation enhancement is possible as in ocvTonemapDrago.
-
-For more information see @cite DD02 .
- */
-class CV_EXPORTS_W TonemapDurand : public Tonemap
-{
-public:
-
- CV_WRAP virtual float getSaturation() const = 0;
- CV_WRAP virtual void setSaturation(float saturation) = 0;
-
- CV_WRAP virtual float getContrast() const = 0;
- CV_WRAP virtual void setContrast(float contrast) = 0;
-
- CV_WRAP virtual float getSigmaSpace() const = 0;
- CV_WRAP virtual void setSigmaSpace(float sigma_space) = 0;
-
- CV_WRAP virtual float getSigmaColor() const = 0;
- CV_WRAP virtual void setSigmaColor(float sigma_color) = 0;
-};
-
-/** @brief Creates TonemapDurand object
-
-@param gamma gamma value for gamma correction. See createTonemap
-@param contrast resulting contrast on logarithmic scale, i. e. log(max / min), where max and min
-are maximum and minimum luminance values of the resulting image.
-@param saturation saturation enhancement value. See createTonemapDrago
-@param sigma_space bilateral filter sigma in color space
-@param sigma_color bilateral filter sigma in coordinate space
- */
-CV_EXPORTS_W Ptr<TonemapDurand>
-createTonemapDurand(float gamma = 1.0f, float contrast = 4.0f, float saturation = 1.0f, float sigma_space = 2.0f, float sigma_color = 2.0f);
/** @brief This is a global tonemapping operator that models human visual system.
@@ -502,7 +475,7 @@ class CV_EXPORTS_W AlignMTB : public AlignExposures
{
public:
CV_WRAP virtual void process(InputArrayOfArrays src, std::vector<Mat>& dst,
- InputArray times, InputArray response) = 0;
+ InputArray times, InputArray response) CV_OVERRIDE = 0;
/** @brief Short version of process, that doesn't take extra arguments.
@@ -591,7 +564,7 @@ public:
@param samples number of pixel locations to use
@param lambda smoothness term weight. Greater values produce smoother results, but can alter the
response.
-@param random if true sample pixel locations are chosen at random, otherwise the form a
+@param random if true sample pixel locations are chosen at random, otherwise they form a
rectangular grid.
*/
CV_EXPORTS_W Ptr<CalibrateDebevec> createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false);
@@ -646,7 +619,7 @@ class CV_EXPORTS_W MergeDebevec : public MergeExposures
{
public:
CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst,
- InputArray times, InputArray response) = 0;
+ InputArray times, InputArray response) CV_OVERRIDE = 0;
CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0;
};
@@ -669,7 +642,7 @@ class CV_EXPORTS_W MergeMertens : public MergeExposures
{
public:
CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst,
- InputArray times, InputArray response) = 0;
+ InputArray times, InputArray response) CV_OVERRIDE = 0;
/** @brief Short version of process, that doesn't take extra arguments.
@param src vector of input images
@@ -705,7 +678,7 @@ class CV_EXPORTS_W MergeRobertson : public MergeExposures
{
public:
CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst,
- InputArray times, InputArray response) = 0;
+ InputArray times, InputArray response) CV_OVERRIDE = 0;
CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0;
};
@@ -715,6 +688,9 @@ CV_EXPORTS_W Ptr<MergeRobertson> createMergeRobertson();
//! @} photo_hdr
+//! @addtogroup photo_decolor
+//! @{
+
/** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized
black-and-white photograph rendering, and in many single channel image processing applications
@cite CL12 .
@@ -727,9 +703,27 @@ This function is to be applied on color images.
*/
CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost);
+//! @} photo_decolor
+
//! @addtogroup photo_clone
//! @{
+
+//! seamlessClone algorithm flags
+enum
+{
+ /** The power of the method is fully expressed when inserting objects with complex outlines into a new background*/
+ NORMAL_CLONE = 1,
+ /** The classic method, color-based selection and alpha masking might be time consuming and often leaves an undesirable
+ halo. Seamless cloning, even averaged with the original image, is not effective. Mixed seamless cloning based on a loose selection proves effective.*/
+ MIXED_CLONE = 2,
+ /** Monochrome transfer allows the user to easily replace certain features of one object by alternative features.*/
+ MONOCHROME_TRANSFER = 3};
+
+
+/** @example samples/cpp/tutorial_code/photo/seamless_cloning/cloning_demo.cpp
+An example using seamlessClone function
+*/
/** @brief Image editing tasks concern either global changes (color/intensity corrections, filters,
deformations) or local changes concerned to a selection. Here we are interested in achieving local
changes, ones that are restricted to a region manually selected (ROI), in a seamless and effortless
@@ -741,15 +735,7 @@ content @cite PM03 .
@param mask Input 8-bit 1 or 3-channel image.
@param p Point in dst image where object is placed.
@param blend Output image with the same size and type as dst.
-@param flags Cloning method that could be one of the following:
-- **NORMAL_CLONE** The power of the method is fully expressed when inserting objects with
-complex outlines into a new background
-- **MIXED_CLONE** The classic method, color-based selection and alpha masking might be time
-consuming and often leaves an undesirable halo. Seamless cloning, even averaged with the
-original image, is not effective. Mixed seamless cloning based on a loose selection proves
-effective.
-- **FEATURE_EXCHANGE** Feature exchange allows the user to easily replace certain features of
-one object by alternative features.
+@param flags Cloning method that could be cv::NORMAL_CLONE, cv::MIXED_CLONE or cv::MONOCHROME_TRANSFER
*/
CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p,
OutputArray blend, int flags);
@@ -784,18 +770,16 @@ CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArra
float alpha = 0.2f, float beta = 0.4f);
/** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one
-washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge
-Detector is used.
+washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge %Detector is used.
@param src Input 8-bit 3-channel image.
@param mask Input 8-bit 1 or 3-channel image.
@param dst Output image with the same size and type as src.
-@param low_threshold Range from 0 to 100.
+@param low_threshold %Range from 0 to 100.
@param high_threshold Value \> 100.
@param kernel_size The size of the Sobel kernel to be used.
-**NOTE:**
-
+@note
The algorithm assumes that the color of the source image is close to that of the destination. This
assumption means that when the colors don't match, the source image color gets tinted toward the
color of the destination image.
@@ -809,16 +793,21 @@ CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray
//! @addtogroup photo_render
//! @{
+//! Edge preserving filters
+enum
+{
+ RECURS_FILTER = 1, //!< Recursive Filtering
+ NORMCONV_FILTER = 2 //!< Normalized Convolution Filtering
+};
+
/** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing
filters are used in many different applications @cite EM11 .
@param src Input 8-bit 3-channel image.
@param dst Output 8-bit 3-channel image.
-@param flags Edge preserving filters:
-- **RECURS_FILTER** = 1
-- **NORMCONV_FILTER** = 2
-@param sigma_s Range between 0 to 200.
-@param sigma_r Range between 0 to 1.
+@param flags Edge preserving filters: cv::RECURS_FILTER or cv::NORMCONV_FILTER
+@param sigma_s %Range between 0 to 200.
+@param sigma_r %Range between 0 to 1.
*/
CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1,
float sigma_s = 60, float sigma_r = 0.4f);
@@ -827,20 +816,23 @@ CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flag
@param src Input 8-bit 3-channel image.
@param dst Output image with the same size and type as src.
-@param sigma_s Range between 0 to 200.
-@param sigma_r Range between 0 to 1.
+@param sigma_s %Range between 0 to 200.
+@param sigma_r %Range between 0 to 1.
*/
CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10,
float sigma_r = 0.15f);
+/** @example samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp
+An example using non-photorealistic line drawing functions
+*/
/** @brief Pencil-like non-photorealistic line drawing
@param src Input 8-bit 3-channel image.
@param dst1 Output 8-bit 1-channel image.
@param dst2 Output image with the same size and type as src.
-@param sigma_s Range between 0 to 200.
-@param sigma_r Range between 0 to 1.
-@param shade_factor Range between 0 to 0.1.
+@param sigma_s %Range between 0 to 200.
+@param sigma_r %Range between 0 to 1.
+@param shade_factor %Range between 0 to 0.1.
*/
CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2,
float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f);
@@ -851,8 +843,8 @@ contrast while preserving, or enhancing, high-contrast features.
@param src Input 8-bit 3-channel image.
@param dst Output image with the same size and type as src.
-@param sigma_s Range between 0 to 200.
-@param sigma_r Range between 0 to 1.
+@param sigma_s %Range between 0 to 200.
+@param sigma_r %Range between 0 to 1.
*/
CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60,
float sigma_r = 0.45f);
diff --git a/include/opencv2/photo/legacy/constants_c.h b/include/opencv2/photo/legacy/constants_c.h
deleted file mode 100755
index ec1d440..0000000
--- a/include/opencv2/photo/legacy/constants_c.h
+++ /dev/null
@@ -1,14 +0,0 @@
-// This file is part of OpenCV project.
-// It is subject to the license terms in the LICENSE file found in the top-level directory
-// of this distribution and at http://opencv.org/license.html.
-
-#ifndef OPENCV_PHOTO_LEGACY_CONSTANTS_H
-#define OPENCV_PHOTO_LEGACY_CONSTANTS_H
-
-enum InpaintingModes
-{
- CV_INPAINT_NS =0,
- CV_INPAINT_TELEA =1
-};
-
-#endif // OPENCV_PHOTO_LEGACY_CONSTANTS_H
diff --git a/include/opencv2/video.hpp b/include/opencv2/video.hpp
index a3dde60..aa644a9 100755
--- a/include/opencv2/video.hpp
+++ b/include/opencv2/video.hpp
@@ -56,4 +56,8 @@
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/background_segm.hpp"
+#ifndef DISABLE_OPENCV_24_COMPATIBILITY
+#include "opencv2/video/tracking_c.h"
+#endif
+
#endif //OPENCV_VIDEO_HPP
diff --git a/include/opencv2/video/legacy/constants_c.h b/include/opencv2/video/legacy/constants_c.h
deleted file mode 100755
index 1a98f52..0000000
--- a/include/opencv2/video/legacy/constants_c.h
+++ /dev/null
@@ -1,16 +0,0 @@
-// This file is part of OpenCV project.
-// It is subject to the license terms in the LICENSE file found in the top-level directory
-// of this distribution and at http://opencv.org/license.html.
-
-#ifndef OPENCV_VIDEO_LEGACY_CONSTANTS_H
-#define OPENCV_VIDEO_LEGACY_CONSTANTS_H
-
-enum
-{
- CV_LKFLOW_PYR_A_READY = 1,
- CV_LKFLOW_PYR_B_READY = 2,
- CV_LKFLOW_INITIAL_GUESSES = 4,
- CV_LKFLOW_GET_MIN_EIGENVALS = 8
-};
-
-#endif // OPENCV_VIDEO_LEGACY_CONSTANTS_H
diff --git a/include/opencv2/video/tracking.hpp b/include/opencv2/video/tracking.hpp
index e978886..9f344be 100755
--- a/include/opencv2/video/tracking.hpp
+++ b/include/opencv2/video/tracking.hpp
@@ -249,13 +249,13 @@ where src[i] and dst[i] are the i-th points in src and dst, respectively
\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f]
when fullAffine=false.
-@deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function
-with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions.
-
@sa
estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography
*/
-CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine );
+CV_EXPORTS_W Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine);
+CV_EXPORTS_W Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine, int ransacMaxIters, double ransacGoodRatio,
+ int ransacSize0);
+
enum
{
@@ -308,7 +308,7 @@ Default values are shown in the declaration above.
The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion
(@cite EP08), that is
-\f[\texttt{warpMatrix} = \texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f]
+\f[\texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f]
where
@@ -410,29 +410,6 @@ public:
};
-/** @brief Read a .flo file
-
- @param path Path to the file to be loaded
-
- The function readOpticalFlow loads a flow field from a file and returns it as a single matrix.
- Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the
- flow in the horizontal direction (u), second - vertical (v).
- */
-CV_EXPORTS_W Mat readOpticalFlow( const String& path );
-/** @brief Write a .flo to disk
-
- @param path Path to the file to be written
- @param flow Flow field to be stored
-
- The function stores a flow field in a file, returns true on success, false otherwise.
- The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds
- to the flow in the horizontal direction (u), second - vertical (v).
- */
-CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow );
-
-/**
- Base class for dense optical flow algorithms
-*/
class CV_EXPORTS_W DenseOpticalFlow : public Algorithm
{
public:
@@ -469,6 +446,131 @@ public:
OutputArray err = cv::noArray()) = 0;
};
+/** @brief "Dual TV L1" Optical Flow Algorithm.
+
+The class implements the "Dual TV L1" optical flow algorithm described in @cite Zach2007 and
+@cite Javier2012 .
+Here are important members of the class that control the algorithm, which you can set after
+constructing the class instance:
+
+- member double tau
+ Time step of the numerical scheme.
+
+- member double lambda
+ Weight parameter for the data term, attachment parameter. This is the most relevant
+ parameter, which determines the smoothness of the output. The smaller this parameter is,
+ the smoother the solutions we obtain. It depends on the range of motions of the images, so
+ its value should be adapted to each image sequence.
+
+- member double theta
+ Weight parameter for (u - v)\^2, tightness parameter. It serves as a link between the
+ attachment and the regularization terms. In theory, it should have a small value in order
+ to maintain both parts in correspondence. The method is stable for a large range of values
+ of this parameter.
+
+- member int nscales
+ Number of scales used to create the pyramid of images.
+
+- member int warps
+ Number of warpings per scale. Represents the number of times that I1(x+u0) and grad(
+ I1(x+u0) ) are computed per scale. This is a parameter that assures the stability of the
+ method. It also affects the running time, so it is a compromise between speed and
+ accuracy.
+
+- member double epsilon
+ Stopping criterion threshold used in the numerical scheme, which is a trade-off between
+ precision and running time. A small value will yield more accurate solutions at the
+ expense of a slower convergence.
+
+- member int iterations
+ Stopping criterion iterations number used in the numerical scheme.
+
+C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime TV-L1 Optical Flow".
+Javier Sanchez, Enric Meinhardt-Llopis and Gabriele Facciolo. "TV-L1 Optical Flow Estimation".
+*/
+class CV_EXPORTS_W DualTVL1OpticalFlow : public DenseOpticalFlow
+{
+public:
+ //! @brief Time step of the numerical scheme
+ /** @see setTau */
+ CV_WRAP virtual double getTau() const = 0;
+ /** @copybrief getTau @see getTau */
+ CV_WRAP virtual void setTau(double val) = 0;
+ //! @brief Weight parameter for the data term, attachment parameter
+ /** @see setLambda */
+ CV_WRAP virtual double getLambda() const = 0;
+ /** @copybrief getLambda @see getLambda */
+ CV_WRAP virtual void setLambda(double val) = 0;
+ //! @brief Weight parameter for (u - v)^2, tightness parameter
+ /** @see setTheta */
+ CV_WRAP virtual double getTheta() const = 0;
+ /** @copybrief getTheta @see getTheta */
+ CV_WRAP virtual void setTheta(double val) = 0;
+ //! @brief coefficient for additional illumination variation term
+ /** @see setGamma */
+ CV_WRAP virtual double getGamma() const = 0;
+ /** @copybrief getGamma @see getGamma */
+ CV_WRAP virtual void setGamma(double val) = 0;
+ //! @brief Number of scales used to create the pyramid of images
+ /** @see setScalesNumber */
+ CV_WRAP virtual int getScalesNumber() const = 0;
+ /** @copybrief getScalesNumber @see getScalesNumber */
+ CV_WRAP virtual void setScalesNumber(int val) = 0;
+ //! @brief Number of warpings per scale
+ /** @see setWarpingsNumber */
+ CV_WRAP virtual int getWarpingsNumber() const = 0;
+ /** @copybrief getWarpingsNumber @see getWarpingsNumber */
+ CV_WRAP virtual void setWarpingsNumber(int val) = 0;
+ //! @brief Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time
+ /** @see setEpsilon */
+ CV_WRAP virtual double getEpsilon() const = 0;
+ /** @copybrief getEpsilon @see getEpsilon */
+ CV_WRAP virtual void setEpsilon(double val) = 0;
+ //! @brief Inner iterations (between outlier filtering) used in the numerical scheme
+ /** @see setInnerIterations */
+ CV_WRAP virtual int getInnerIterations() const = 0;
+ /** @copybrief getInnerIterations @see getInnerIterations */
+ CV_WRAP virtual void setInnerIterations(int val) = 0;
+ //! @brief Outer iterations (number of inner loops) used in the numerical scheme
+ /** @see setOuterIterations */
+ CV_WRAP virtual int getOuterIterations() const = 0;
+ /** @copybrief getOuterIterations @see getOuterIterations */
+ CV_WRAP virtual void setOuterIterations(int val) = 0;
+ //! @brief Use initial flow
+ /** @see setUseInitialFlow */
+ CV_WRAP virtual bool getUseInitialFlow() const = 0;
+ /** @copybrief getUseInitialFlow @see getUseInitialFlow */
+ CV_WRAP virtual void setUseInitialFlow(bool val) = 0;
+ //! @brief Step between scales (<1)
+ /** @see setScaleStep */
+ CV_WRAP virtual double getScaleStep() const = 0;
+ /** @copybrief getScaleStep @see getScaleStep */
+ CV_WRAP virtual void setScaleStep(double val) = 0;
+ //! @brief Median filter kernel size (1 = no filter) (3 or 5)
+ /** @see setMedianFiltering */
+ CV_WRAP virtual int getMedianFiltering() const = 0;
+ /** @copybrief getMedianFiltering @see getMedianFiltering */
+ CV_WRAP virtual void setMedianFiltering(int val) = 0;
+
+ /** @brief Creates instance of cv::DualTVL1OpticalFlow*/
+ CV_WRAP static Ptr<DualTVL1OpticalFlow> create(
+ double tau = 0.25,
+ double lambda = 0.15,
+ double theta = 0.3,
+ int nscales = 5,
+ int warps = 5,
+ double epsilon = 0.01,
+ int innnerIterations = 30,
+ int outerIterations = 10,
+ double scaleStep = 0.8,
+ double gamma = 0.0,
+ int medianFiltering = 5,
+ bool useInitialFlow = false);
+};
+
+/** @brief Creates instance of cv::DenseOpticalFlow
+*/
+CV_EXPORTS_W Ptr<DualTVL1OpticalFlow> createOptFlow_DualTVL1();
/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm.
*/
@@ -510,166 +612,6 @@ public:
int flags = 0);
};
-/** @brief Variational optical flow refinement
-
-This class implements variational refinement of the input flow field, i.e.
-it uses input flow to initialize the minimization of the following functional:
-\f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$,
-where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms
-respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the
-influence of outliers. A complete formulation and a description of the minimization
-procedure can be found in @cite Brox2004
-*/
-class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow
-{
-public:
- /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components
- (to avoid extra splits/merges) */
- CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0;
-
- /** @brief Number of outer (fixed-point) iterations in the minimization procedure.
- @see setFixedPointIterations */
- CV_WRAP virtual int getFixedPointIterations() const = 0;
- /** @copybrief getFixedPointIterations @see getFixedPointIterations */
- CV_WRAP virtual void setFixedPointIterations(int val) = 0;
-
- /** @brief Number of inner successive over-relaxation (SOR) iterations
- in the minimization procedure to solve the respective linear system.
- @see setSorIterations */
- CV_WRAP virtual int getSorIterations() const = 0;
- /** @copybrief getSorIterations @see getSorIterations */
- CV_WRAP virtual void setSorIterations(int val) = 0;
-
- /** @brief Relaxation factor in SOR
- @see setOmega */
- CV_WRAP virtual float getOmega() const = 0;
- /** @copybrief getOmega @see getOmega */
- CV_WRAP virtual void setOmega(float val) = 0;
-
- /** @brief Weight of the smoothness term
- @see setAlpha */
- CV_WRAP virtual float getAlpha() const = 0;
- /** @copybrief getAlpha @see getAlpha */
- CV_WRAP virtual void setAlpha(float val) = 0;
-
- /** @brief Weight of the color constancy term
- @see setDelta */
- CV_WRAP virtual float getDelta() const = 0;
- /** @copybrief getDelta @see getDelta */
- CV_WRAP virtual void setDelta(float val) = 0;
-
- /** @brief Weight of the gradient constancy term
- @see setGamma */
- CV_WRAP virtual float getGamma() const = 0;
- /** @copybrief getGamma @see getGamma */
- CV_WRAP virtual void setGamma(float val) = 0;
-
- /** @brief Creates an instance of VariationalRefinement
- */
- CV_WRAP static Ptr<VariationalRefinement> create();
-};
-
-/** @brief DIS optical flow algorithm.
-
-This class implements the Dense Inverse Search (DIS) optical flow algorithm. More
-details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected
-parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is
-still relatively fast, use DeepFlow if you need better quality and don't care about speed.
-
-This implementation includes several additional features compared to the algorithm described in the paper,
-including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to
-utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation,
-if the previous frame's flow field is passed).
-*/
-class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow
-{
-public:
- enum
- {
- PRESET_ULTRAFAST = 0,
- PRESET_FAST = 1,
- PRESET_MEDIUM = 2
- };
-
- /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level
- corresponds to the original image resolution). The final flow is obtained by bilinear upscaling.
- @see setFinestScale */
- CV_WRAP virtual int getFinestScale() const = 0;
- /** @copybrief getFinestScale @see getFinestScale */
- CV_WRAP virtual void setFinestScale(int val) = 0;
-
- /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well
- enough in most cases.
- @see setPatchSize */
- CV_WRAP virtual int getPatchSize() const = 0;
- /** @copybrief getPatchSize @see getPatchSize */
- CV_WRAP virtual void setPatchSize(int val) = 0;
-
- /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond
- to higher flow quality.
- @see setPatchStride */
- CV_WRAP virtual int getPatchStride() const = 0;
- /** @copybrief getPatchStride @see getPatchStride */
- CV_WRAP virtual void setPatchStride(int val) = 0;
-
- /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values
- may improve quality in some cases.
- @see setGradientDescentIterations */
- CV_WRAP virtual int getGradientDescentIterations() const = 0;
- /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */
- CV_WRAP virtual void setGradientDescentIterations(int val) = 0;
-
- /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to
- disable variational refinement completely. Higher values will typically result in more smooth and
- high-quality flow.
- @see setGradientDescentIterations */
- CV_WRAP virtual int getVariationalRefinementIterations() const = 0;
- /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */
- CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0;
-
- /** @brief Weight of the smoothness term
- @see setVariationalRefinementAlpha */
- CV_WRAP virtual float getVariationalRefinementAlpha() const = 0;
- /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */
- CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0;
-
- /** @brief Weight of the color constancy term
- @see setVariationalRefinementDelta */
- CV_WRAP virtual float getVariationalRefinementDelta() const = 0;
- /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */
- CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0;
-
- /** @brief Weight of the gradient constancy term
- @see setVariationalRefinementGamma */
- CV_WRAP virtual float getVariationalRefinementGamma() const = 0;
- /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */
- CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0;
-
-
- /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on
- by default as it typically provides a noticeable quality boost because of increased robustness to
- illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes
- in illumination.
- @see setUseMeanNormalization */
- CV_WRAP virtual bool getUseMeanNormalization() const = 0;
- /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */
- CV_WRAP virtual void setUseMeanNormalization(bool val) = 0;
-
- /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by
- default, as it tends to work better on average and can sometimes help recover from major errors
- introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this
- option off can make the output flow field a bit smoother, however.
- @see setUseSpatialPropagation */
- CV_WRAP virtual bool getUseSpatialPropagation() const = 0;
- /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */
- CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0;
-
- /** @brief Creates an instance of DISOpticalFlow
-
- @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM
- */
- CV_WRAP static Ptr<DISOpticalFlow> create(int preset = DISOpticalFlow::PRESET_FAST);
-};
/** @brief Class used for calculating a sparse optical flow.
diff --git a/include/opencv2/videoio.hpp b/include/opencv2/videoio.hpp
index 999643d..df1d181 100755
--- a/include/opencv2/videoio.hpp
+++ b/include/opencv2/videoio.hpp
@@ -88,16 +88,16 @@ See @ref videoio_overview for more information.
*/
enum VideoCaptureAPIs {
CAP_ANY = 0, //!< Auto detect == 0
- CAP_VFW = 200, //!< Video For Windows (obsolete, removed)
- CAP_V4L = 200, //!< V4L/V4L2 capturing support
+ CAP_VFW = 200, //!< Video For Windows (platform native)
+ CAP_V4L = 200, //!< V4L/V4L2 capturing support via libv4l
CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L
CAP_FIREWIRE = 300, //!< IEEE 1394 drivers
- CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
- CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
- CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
- CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
- CAP_QT = 500, //!< QuickTime (obsolete, removed)
- CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed)
+ CAP_FIREWARE = CAP_FIREWIRE, //!< Same as CAP_FIREWIRE
+ CAP_IEEE1394 = CAP_FIREWIRE, //!< Same as CAP_FIREWIRE
+ CAP_DC1394 = CAP_FIREWIRE, //!< Same as CAP_FIREWIRE
+ CAP_CMU1394 = CAP_FIREWIRE, //!< Same as CAP_FIREWIRE
+ CAP_QT = 500, //!< QuickTime
+ CAP_UNICAP = 600, //!< Unicap drivers
CAP_DSHOW = 700, //!< DirectShow (via videoInput)
CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK
CAP_OPENNI = 900, //!< OpenNI (for Kinect)
@@ -108,8 +108,7 @@ enum VideoCaptureAPIs {
CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK
CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput)
CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation
- CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK)
- CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC
+ CAP_INTELPERC = 1500, //!< Intel Perceptual Computing SDK
CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect)
CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors)
CAP_GPHOTO2 = 1700, //!< gPhoto2 connection
@@ -146,7 +145,8 @@ enum VideoCaptureProperties {
CAP_PROP_HUE =13, //!< Hue of the image (only for cameras).
CAP_PROP_GAIN =14, //!< Gain of the image (only for those cameras that support).
CAP_PROP_EXPOSURE =15, //!< Exposure (only for those cameras that support).
- CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB.
+ CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB. <br/>
+ //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output.
CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported.
CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently).
CAP_PROP_MONOCHROME =19,
@@ -176,11 +176,25 @@ enum VideoCaptureProperties {
CAP_PROP_AUTO_WB =44, //!< enable/ disable auto white-balance
CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature
CAP_PROP_CODEC_PIXEL_FORMAT =46, //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown
+ CAP_PROP_BITRATE =47, //!< (read-only) Video bitrate in kbits/s
+ CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg back-end only)
+ CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata (applicable for FFmpeg back-end only) (https://github.com/opencv/opencv/issues/15499)
#ifndef CV_DOXYGEN
CV__CAP_PROP_LATEST
#endif
};
+
+/** @brief Generic camera output modes identifier.
+@note Currently, these are supported through the libv4l backend only.
+*/
+enum VideoCaptureModes {
+ CAP_MODE_BGR = 0, //!< BGR24 (default)
+ CAP_MODE_RGB = 1, //!< RGB24
+ CAP_MODE_GRAY = 2, //!< Y8
+ CAP_MODE_YUYV = 3 //!< YUYV
+ };
+
/** @brief %VideoWriter generic properties identifier.
@sa VideoWriter::get(), VideoWriter::set()
*/
@@ -529,8 +543,7 @@ enum { CAP_PROP_INTELPERC_PROFILE_COUNT = 11001,
//! Intel Perceptual Streams
enum { CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29,
CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28,
- CAP_INTELPERC_IR_GENERATOR = 1 << 27,
- CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR + CAP_INTELPERC_IR_GENERATOR
+ CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR
};
enum { CAP_INTELPERC_DEPTH_MAP = 0, //!< Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth.
@@ -583,9 +596,6 @@ enum { CAP_PROP_IMAGES_BASE = 18000,
class IVideoCapture;
-//! @cond IGNORED
-namespace internal { class VideoCapturePrivateAccessor; }
-//! @endcond IGNORED
/** @brief Class for video capturing from video files, image sequences or cameras.
@@ -616,19 +626,39 @@ public:
CV_WRAP VideoCapture();
/** @overload
- @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference
+ @brief Open video file or image file sequence or a capturing device or a IP video stream for video capturing
+
+ Same as VideoCapture(const String& filename, int apiPreference) but using default Capture API backends
+ */
+ CV_WRAP VideoCapture(const String& filename);
+
+ /** @overload
+ @brief Open video file or a capturing device or a IP video stream for video capturing with API Preference
@param filename it can be:
- name of video file (eg. `video.avi`)
- or image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`)
- - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`).
+ - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`)
+ - or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend
Note that each video stream or IP camera feed has its own URL scheme. Please refer to the
documentation of source stream to know the right URL.
@param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader
implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW.
- @sa The list of supported API backends cv::VideoCaptureAPIs
+
+ @sa cv::VideoCaptureAPIs
+ */
+ CV_WRAP VideoCapture(const String& filename, int apiPreference);
+
+ /** @overload
+ @brief Open a camera for video capturing
+
+ @param index camera_id + domain_offset (CAP_*) id of the video capturing device to open. To open default camera using default backend just pass 0.
+ Use a `domain_offset` to enforce a specific reader implementation if multiple are available like cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW.
+ e.g. to open Camera 1 using the MS Media Foundation API use `index = 1 + cv::CAP_MSMF`
+
+ @sa cv::VideoCaptureAPIs
*/
- CV_WRAP VideoCapture(const String& filename, int apiPreference = CAP_ANY);
+ CV_WRAP VideoCapture(int index);
/** @overload
@brief Opens a camera for video capturing
@@ -636,11 +666,11 @@ public:
@param index id of the video capturing device to open. To open default camera using default backend just pass 0.
(to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY)
@param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader
- implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L.
+ implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L2.
- @sa The list of supported API backends cv::VideoCaptureAPIs
+ @sa cv::VideoCaptureAPIs
*/
- CV_WRAP VideoCapture(int index, int apiPreference = CAP_ANY);
+ CV_WRAP VideoCapture(int index, int apiPreference);
/** @brief Default destructor
@@ -648,27 +678,37 @@ public:
*/
virtual ~VideoCapture();
- /** @brief Opens a video file or a capturing device or an IP video stream for video capturing.
+ /** @brief Open video file or a capturing device or a IP video stream for video capturing
@overload
- Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference = CAP_ANY)
+ Parameters are same as the constructor VideoCapture(const String& filename)
@return `true` if the file has been successfully opened
The method first calls VideoCapture::release to close the already opened file or camera.
*/
- CV_WRAP virtual bool open(const String& filename, int apiPreference = CAP_ANY);
+ CV_WRAP virtual bool open(const String& filename);
- /** @brief Opens a camera for video capturing
+ /** @brief Open a camera for video capturing
@overload
- Parameters are same as the constructor VideoCapture(int index, int apiPreference = CAP_ANY)
+ Parameters are same as the constructor VideoCapture(int index)
@return `true` if the camera has been successfully opened.
The method first calls VideoCapture::release to close the already opened file or camera.
*/
- CV_WRAP virtual bool open(int index, int apiPreference = CAP_ANY);
+ CV_WRAP virtual bool open(int index);
+
+ /** @brief Open a camera for video capturing
+
+ @overload
+
+ Parameters are similar as the constructor VideoCapture(int index),except it takes an additional argument apiPreference.
+ Definitely, is same as open(int index) where `index=cameraNum + apiPreference`
+ @return `true` if the camera has been successfully opened.
+ */
+ CV_WRAP bool open(int cameraNum, int apiPreference);
/** @brief Returns true if video capturing has been initialized already.
@@ -781,48 +821,26 @@ public:
*/
CV_WRAP virtual double get(int propId) const;
- /** @brief Returns used backend API name
+ /** @brief Open video file or a capturing device or a IP video stream for video capturing with API Preference
- @note Stream should be opened.
- */
- CV_WRAP String getBackendName() const;
-
- /** Switches exceptions mode
- *
- * methods raise exceptions if not successful instead of returning an error code
- */
- CV_WRAP void setExceptionMode(bool enable) { throwOnFail = enable; }
-
- /// query if exception mode is active
- CV_WRAP bool getExceptionMode() { return throwOnFail; }
-
-
- /** @brief Wait for ready frames from VideoCapture.
+ @overload
- @param streams input video streams
- @param readyIndex stream indexes with grabbed frames (ready to use .retrieve() to fetch actual frame)
- @param timeoutNs number of nanoseconds (0 - infinite)
- @return `true` if streamReady is not empty
+ Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference)
+ @return `true` if the file has been successfully opened
- @throws Exception %Exception on stream errors (check .isOpened() to filter out malformed streams) or VideoCapture type is not supported
+ The method first calls VideoCapture::release to close the already opened file or camera.
+ */
+ CV_WRAP virtual bool open(const String& filename, int apiPreference);
- The primary use of the function is in multi-camera environments.
- The method fills the ready state vector, grabbs video frame, if camera is ready.
+ /** @brief Returns used backend API name
- After this call use VideoCapture::retrieve() to decode and fetch frame data.
- */
- static /*CV_WRAP*/
- bool waitAny(
- const std::vector<VideoCapture>& streams,
- CV_OUT std::vector<int>& readyIndex,
- int64 timeoutNs = 0);
+ @note Stream should be opened.
+ */
+ CV_WRAP String getBackendName() const;
protected:
Ptr<CvCapture> cap;
Ptr<IVideoCapture> icap;
- bool throwOnFail;
-
- friend class internal::VideoCapturePrivateAccessor;
};
class IVideoWriter;
@@ -846,8 +864,8 @@ public:
The constructors/functions initialize video writers.
- On Linux FFMPEG is used to write videos;
- - On Windows FFMPEG or MSWF or DSHOW is used;
- - On MacOSX AVFoundation is used.
+ - On Windows FFMPEG or VFW is used;
+ - On MacOSX QTKit is used.
*/
CV_WRAP VideoWriter();
@@ -857,7 +875,7 @@ public:
VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, VideoWriter::fourcc('M','J','P','G') is a
motion-jpeg codec etc. List of codes can be obtained at [Video Codecs by
FOURCC](http://www.fourcc.org/codecs.php) page. FFMPEG backend with MP4 container natively uses
- other values as fourcc code: see [ObjectType](http://www.mp4ra.org/codecs.html),
+ other values as fourcc code: see [ObjectType](http://mp4ra.org/#/codecs),
so you may receive a warning message from OpenCV about fourcc code conversion.
@param fps Framerate of the created video stream.
@param frameSize Size of the video frames.
@@ -920,11 +938,6 @@ public:
*/
virtual VideoWriter& operator << (const Mat& image);
- /** @overload
- @sa write
- */
- virtual VideoWriter& operator << (const UMat& image);
-
/** @brief Writes the next video frame
@param image The written frame. In general, color images are expected in BGR format.
@@ -932,7 +945,7 @@ public:
The function/method writes the specified image to video file. It must have the same size as has
been specified when opening the video writer.
*/
- CV_WRAP virtual void write(InputArray image);
+ CV_WRAP virtual void write(const Mat& image);
/** @brief Sets a property in the VideoWriter.
@@ -977,8 +990,8 @@ protected:
Size frameSize, bool isColor = true);
};
-template<> struct DefaultDeleter<CvCapture>{ CV_EXPORTS void operator ()(CvCapture* obj) const; };
-template<> struct DefaultDeleter<CvVideoWriter>{ CV_EXPORTS void operator ()(CvVideoWriter* obj) const; };
+template<> CV_EXPORTS void DefaultDeleter<CvCapture>::operator ()(CvCapture* obj) const;
+template<> CV_EXPORTS void DefaultDeleter<CvVideoWriter>::operator ()(CvVideoWriter* obj) const;
//! @} videoio