chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:06:04 +08:00
commit 86c9b1c39f
7743 changed files with 3316339 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
if(OPENCV_INITIAL_PASS)
# generator for Objective-C source code and documentation signatures
add_subdirectory(generator)
endif()
if(NOT APPLE_FRAMEWORK)
return()
endif()
set(the_description "The Objective-C bindings")
ocv_add_module(objc BINDINGS opencv_core opencv_imgproc PRIVATE_REQUIRED opencv_objc_bindings_generator)
add_custom_target(${the_module}
ALL
COMMENT "Objective-C framework"
)
add_dependencies(${the_module} gen_opencv_objc_source)
#include(${CMAKE_CURRENT_SOURCE_DIR}/common.cmake)
+11
View File
@@ -0,0 +1,11 @@
ocv_warnings_disable(CMAKE_CXX_FLAGS -Wdeprecated-declarations)
# get list of modules to wrap
# message(STATUS "Wrapped in Objective-C:")
set(OPENCV_OBJC_MODULES)
foreach(m ${OPENCV_MODULES_BUILD})
if (";${OPENCV_MODULE_${m}_WRAPPERS};" MATCHES ";objc;" AND HAVE_${m})
list(APPEND OPENCV_OBJC_MODULES ${m})
#message(STATUS "\t${m}")
endif()
endforeach()
+69
View File
@@ -0,0 +1,69 @@
This is the documentation for the iOS OpenCV framework.
## Quick Start Tutorial
Follow the steps below to get a simple "Hello World" app running on iOS
* Open Xcode and create a new project from the **File** > **New** > **Project...** menu
![New Project menu](common-create-project.png)
* From template selection dialog select the `iOS` tab and then select `App`
![Template selection dialog](ios-create-app.png)
* Enter a name for the project and set **Interface** to **Storyboard** and **Language** to **Swift**
![App settings dialog](ios-create-app-settings.png)
* Choose a location to save the project
![Choose project location dialog](common-create-app-location.png)
* Create a new folder `Framework`
![Create new folder menu](ios-create-framework-folder.png)
* In a Finder window copy the framework file to the newly created folder. The framework should appear in the project navigator as below. (Note: in this case the framework has extension `.framework` but depending on how you built it or from where you obtained it your framework may have extension `.xcframework`)
![Add framework](ios-add-framework.png)
* In the project navigator select the `ViewController.swift` file
![Select ViewController file](ios-select-viewcontroller.png)
* Add an `import` for the OpenCV framework below the existing import for `UIKit`
```swift, copy
import opencv2
```
* Replace the implementation of the `viewDidLoad` function with the following code
```swift, copy
override func viewDidLoad() {
super.viewDidLoad()
let white = Scalar(255, 255, 255, 255)
let black = Scalar(0, 0, 0, 255)
let m = Mat(rows: 400, cols: Int32(view.frame.width), type: CvType.CV_8UC4, scalar: white)
Imgproc.putText(img: m, text: "Hello World", org: Point(x: 10, y: 150), fontFace: HersheyFonts.FONT_HERSHEY_DUPLEX, fontScale: 2, color: black)
let image = m.toUIImage()
let imageView = UIImageView(image: image)
self.view.addSubview(imageView)
}
```
* The `ViewController.swift` file should now look like this
![Updated ViewController code](ios-add-opencv-code.png)
* Launch the app
![Launch app button](ios-launch-app.png)
* The app home screen should look like this
![App screenshot](ios-app-screenshot.png)
If that has all worked well then congratulations. If not then feel free to reach out to the OpenCV community for help. Also feel free to contribute fixes and improvements.
+85
View File
@@ -0,0 +1,85 @@
This is the documentation for the macOS OpenCV framework.
## Quick Start Tutorial
Follow the steps below to get a simple "Hello World" app running on macOS
* Open Xcode and create a new project from the **File** > **New** > **Project...** menu
![New Project menu](common-create-project.png)
* From the template selection dialog select the **macOS** tab and then select **App**
![Template selection dialog](macos-create-app.png)
* Enter a name for the project and set **Interface** to **Storyboard** and **Language** to **Swift**
![App settings dialog](macos-create-app-settings.png)
* Choose a location to save the project
![Choose project location dialog](common-create-app-location.png)
* Create a new folder `Framework`
![Create new folder menu](macos-create-framework-folder.png)
* In a Finder window copy the framework file to the newly created folder. The framework should appear in the project navigator as below. (Note: in this case the framework has extension `.framework` but depending on how you built it or from where you obtained it your framework may have extension `.xcframework`)
![Add framework](macos-add-framework.png)
* Select the project root in the project navigator and on the **General** tab locate the **Frameworks, Libraries and Embedded Content** section
![Frameworks, Libraries and Embedded Content](macos-add-dependencies-1.png)
* In the **Choose frameworks and libraries to add** dialog add the following
* OpenCL.framework
* liblapack.tbd
* libblas.tbd
![Choose frameworks and libraries to add](macos-add-dependencies-2.png)
* The **Frameworks, Libraries and Embedded Content** section should now look like this
![Choose frameworks and libraries to add](macos-add-dependencies-3.png)
* In the project navigator select the `ViewController.swift` file
![Select ViewController file](macos-select-viewcontroller.png)
* Add an `import` for the OpenCV framework below the existing import for `Cocoa`
```swift, copy
import opencv2
```
* Replace the implementation of the `viewDidLoad` function with the following code
```swift, copy
override func viewDidLoad() {
super.viewDidLoad()
let white = Scalar(255, 255, 255, 255)
let black = Scalar(0, 0, 0, 255)
let m = Mat(rows: 400, cols: Int32(view.frame.width), type: CvType.CV_8UC4, scalar: white)
Imgproc.putText(img: m, text: "Hello World", org: Point(x: 10, y: 250), fontFace: HersheyFonts.FONT_HERSHEY_DUPLEX, fontScale: 2, color: black)
let image = m.toNSImage()
let imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: Int(m.cols()), height: Int(m.rows())))
imageView.image = image
self.view.addSubview(imageView)
}
```
* The `ViewController.swift` file should now look like this
![Updated ViewController code](macos-add-opencv-code.png)
* Launch the app
![Launch app button](macos-launch-app.png)
* The app home screen should look like this
![App screenshot](macos-app-screenshot.png)
If that has all worked well then congratulations. If not then feel free to reach out to the OpenCV community for help. Also feel free to contribute fixes and improvements.
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+140
View File
@@ -0,0 +1,140 @@
set(MODULE_NAME "objc_bindings_generator")
set(OPENCV_MODULE_IS_PART_OF_WORLD FALSE)
ocv_add_module(${MODULE_NAME} INTERNAL opencv_core opencv_imgproc)
#set(OPENCV_OBJC_SIGNATURES_FILE "${CMAKE_CURRENT_BINARY_DIR}/opencv_objc_signatures.json" CACHE INTERNAL "")
set(OPENCV_OBJC_BINDINGS_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE INTERNAL "")
file(REMOVE_RECURSE "${OPENCV_OBJC_BINDINGS_DIR}/osx")
file(REMOVE "${OPENCV_DEPHELPER}/gen_opencv_objc_source_osx") # force re-run after CMake
file(REMOVE_RECURSE "${OPENCV_OBJC_BINDINGS_DIR}/ios")
file(REMOVE "${OPENCV_DEPHELPER}/gen_opencv_objc_source_ios") # force re-run after CMake
file(REMOVE_RECURSE "${OPENCV_OBJC_BINDINGS_DIR}/visionos")
file(REMOVE "${OPENCV_DEPHELPER}/gen_opencv_objc_source_visionos") # force re-run after CMake
# This file is included from a subdirectory
set(OBJC_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/..")
include(${OBJC_SOURCE_DIR}/common.cmake) # fill OPENCV_OBJC_MODULES
# common files
file(GLOB_RECURSE deps "${CMAKE_CURRENT_SOURCE_DIR}/templates/*")
set(__modules_config "") # list of OpenCV modules
foreach(m ${OPENCV_OBJC_MODULES})
set(module_objc_dir "${OPENCV_MODULE_${m}_LOCATION}/misc/objc")
list(APPEND deps ${OPENCV_MODULE_${m}_HEADERS})
file(GLOB_RECURSE misc_files "${module_objc_dir}/*")
list(APPEND deps ${misc_files})
string(REGEX REPLACE "^opencv_" "" m_ "${m}")
if(__modules_config)
set(__modules_config "${__modules_config},\n")
endif()
file(RELATIVE_PATH rel_path "${OpenCV_SOURCE_DIR}" "${OPENCV_MODULE_${m}_LOCATION}")
set(__modules_config "${__modules_config} { \"name\": \"${m_}\", \"location\": \"${rel_path}\" }")
endforeach(m)
if(HAVE_opencv_objc)
set(__objc_build_dir "\"objc_build_dir\": \"${CMAKE_CURRENT_BINARY_DIR}/../objc\",")
endif()
include("${OpenCV_SOURCE_DIR}/cmake/OpenCVBindingsPreprocessorDefinitions.cmake")
ocv_bindings_generator_populate_preprocessor_definitions(
OPENCV_MODULES_BUILD
opencv_preprocessor_defs
)
set(CONFIG_FILE "${CMAKE_CURRENT_BINARY_DIR}/gen_objc.json")
set(__config_str
"{
\"rootdir\": \"${OpenCV_SOURCE_DIR}\",
${__objc_build_dir}
\"modules\": [
${__modules_config}
],
\"preprocessor_definitions\": {
${opencv_preprocessor_defs}
}
}
")
#TODO: ocv_update_file("${CONFIG_FILE}" "${__config_str}" ON_CHANGE_REMOVE "${OPENCV_DEPHELPER}/gen_opencv_objc_source")
if(EXISTS "${CONFIG_FILE}")
file(READ "${CONFIG_FILE}" __content)
else()
set(__content "")
endif()
if(NOT "${__content}" STREQUAL "${__config_str}")
file(WRITE "${CONFIG_FILE}" "${__config_str}")
file(REMOVE "${OPENCV_DEPHELPER}/gen_opencv_objc_source")
endif()
unset(__config_str)
set(objc_generated_files
# "${OPENCV_OBJC_SIGNATURES_FILE}"
)
string(REPLACE "opencv_" "" MODULES "${OPENCV_OBJC_MODULES}")
if(NOT DEFINED OPENCV_OBJC_TARGET AND APPLE_FRAMEWORK)
if(IOS)
set(OPENCV_OBJC_TARGET "ios")
elseif(XROS)
set(OPENCV_OBJC_TARGET "visionos")
else()
set(OPENCV_OBJC_TARGET "osx")
endif()
endif()
if(NOT DEFINED OPENCV_OBJC_FRAMEWORK_NAME)
if(DEFINED FRAMEWORK_NAME)
set(OPENCV_OBJC_FRAMEWORK_NAME "${FRAMEWORK_NAME}")
else()
set(OPENCV_OBJC_FRAMEWORK_NAME "opencv2")
endif()
endif()
set(objc_generated_targets "")
macro(ocv_add_objc_generated_target TARGET)
set(objc_${TARGET}_generated_output_dependecy "${OPENCV_DEPHELPER}/gen_opencv_objc_source_${TARGET}")
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}")
add_custom_command(
OUTPUT ${objc_generated_files} "${objc_${TARGET}_generated_output_dependecy}"
COMMAND ${PYTHON_DEFAULT_EXECUTABLE} "${OBJC_SOURCE_DIR}/generator/gen_objc.py"
-p "${OBJC_SOURCE_DIR}/../python/src2/gen2.py"
-c "${CONFIG_FILE}"
-t "${TARGET}"
-f "${OPENCV_OBJC_FRAMEWORK_NAME}"
COMMAND ${CMAKE_COMMAND} -E touch "${objc_${TARGET}_generated_output_dependecy}"
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}"
DEPENDS "${OpenCV_SOURCE_DIR}/modules/objc/generator/gen_objc.py"
"${OpenCV_SOURCE_DIR}/modules/python/src2/gen2.py"
"${OpenCV_SOURCE_DIR}/modules/python/src2/hdr_parser.py"
# don't, result of file(WRITE): "${CMAKE_CURRENT_BINARY_DIR}/gen_objc.json"
${deps}
# not allowed (file(WRITE) result): "${CONFIG_FILE}"
COMMENT "Generate files for Objective-C bindings (${TARGET})"
)
add_custom_target(gen_opencv_objc_source_${TARGET}
# excluded from all: ALL
DEPENDS ${objc_generated_files} ${objc_${TARGET}_generated_output_dependecy}
SOURCES "${OBJC_SOURCE_DIR}/generator/gen_objc.py"
"${OBJC_SOURCE_DIR}/generator/templates/cmakelists.template"
"${CMAKE_CURRENT_BINARY_DIR}/gen_objc.json"
)
list(APPEND objc_generated_targets gen_opencv_objc_source_${TARGET})
endmacro()
if(OPENCV_OBJC_TARGET)
ocv_add_objc_generated_target(${OPENCV_OBJC_TARGET})
else()
ocv_add_objc_generated_target(osx)
ocv_add_objc_generated_target(ios)
ocv_add_objc_generated_target(visionos)
endif()
add_custom_target(gen_opencv_objc_source
# excluded from all: ALL
DEPENDS ${objc_generated_targets}
)
+1777
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,75 @@
cmake_minimum_required(VERSION 3.15)
project($framework)
set(MODULES "$modules")
# Enable C++11
set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
set (OBJC_COMPILE_FLAGS "-fobjc-arc -fobjc-weak -fvisibility=hidden -fPIC -D__OPENCV_BUILD=1 $module_availability_defines")
set (SUPPRESS_WARNINGS_FLAGS "-Wno-incomplete-umbrella")
set (CMAKE_CXX_FLAGS "$${CMAKE_CXX_FLAGS} $${OBJC_COMPILE_FLAGS} $${SUPPRESS_WARNINGS_FLAGS}")
# grab the files
if(SWIFT_DISABLED)
message(STATUS "Swift wrapper disabled")
file(GLOB_RECURSE objc_sources "objc/*\.h" "objc/*\.m" "objc/*\.mm" "objc/*\.modulemap")
else()
enable_language(Swift)
file(GLOB_RECURSE objc_sources "objc/*\.h" "objc/*\.m" "objc/*\.mm" "objc/*\.swift" "objc/*\.modulemap")
endif()
file(GLOB_RECURSE objc_headers "*\.h")
set_source_files_properties(Documentation.docc PROPERTIES
XCODE_LAST_KNOWN_FILE_TYPE folder.documentationcatalog
)
add_library($framework STATIC
$${objc_sources}
Documentation.docc
)
set_target_properties($framework PROPERTIES LINKER_LANGUAGE CXX)
target_include_directories($framework PRIVATE "$${BUILD_ROOT}")
target_include_directories($framework PRIVATE "$${BUILD_ROOT}/install/include")
target_include_directories($framework PRIVATE "$${BUILD_ROOT}/install/include/opencv2")
foreach(m $${MODULES})
target_include_directories($framework PRIVATE "$${BUILD_ROOT}/modules/objc_bindings_generator/$objc_target/gen/objc/$${m}")
endforeach()
install(TARGETS $framework LIBRARY DESTINATION lib)
# Additional target properties
if (CMAKE_XCODE_BUILD_SYSTEM GREATER_EQUAL 12)
set_target_properties($framework PROPERTIES
OUTPUT_NAME "$framework"
ARCHIVE_OUTPUT_DIRECTORY "$${BUILD_ROOT}/lib"
XCODE_ATTRIBUTE_SWIFT_VERSION 5.0
XCODE_ATTRIBUTE_DEFINES_MODULE YES
XCODE_ATTRIBUTE_BUILD_LIBRARY_FOR_DISTRIBUTION YES
XCODE_ATTRIBUTE_OTHER_SWIFT_FLAGS "-Xcc $${SUPPRESS_WARNINGS_FLAGS}"
XCODE_ATTRIBUTE_MODULEMAP_FILE objc/$framework.modulemap
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER org.opencv.$framework
FRAMEWORK TRUE
MACOSX_FRAMEWORK_IDENTIFIER org.opencv.$framework
PUBLIC_HEADER "$${objc_headers}"
DEFINE_SYMBOL CVAPI_EXPORTS
)
else()
set_target_properties($framework PROPERTIES
OUTPUT_NAME "$framework"
ARCHIVE_OUTPUT_DIRECTORY "$${BUILD_ROOT}/lib"
XCODE_ATTRIBUTE_SWIFT_VERSION 5.0
XCODE_ATTRIBUTE_DEFINES_MODULE YES
XCODE_ATTRIBUTE_OTHER_SWIFT_FLAGS "-Xcc $${SUPPRESS_WARNINGS_FLAGS}"
XCODE_ATTRIBUTE_MODULEMAP_FILE objc/$framework.modulemap
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER org.opencv.$framework
FRAMEWORK TRUE
MACOSX_FRAMEWORK_IDENTIFIER org.opencv.$framework
PUBLIC_HEADER "$${objc_headers}"
DEFINE_SYMBOL CVAPI_EXPORTS
)
endif()
@@ -0,0 +1,11 @@
# $framework Documentation - How To View
## View Locally
* Start a web server in the directory where this HowTo file is located. For example ``python3 -m http.server 8000``
* In a browser navigate to URL http://127.0.0.1:8000/$hosting_base_path/documentation/$framework/
## Deploying to a server
* Upload the content of the directory where this HowTo file is located to the document root of the web server maintaining the same folder hierarchy
* In a browser navigate to URL https://{server-domain}/$hosting_base_path/documentation/$framework/
@@ -0,0 +1,16 @@
//
// This file is auto-generated. Please don't modify it!
//
#import "$objcName.h"
#import "CVObjcUtil.h"
$imports
@implementation $objcName
$nativePointerHandling
$methodImplementations
@end
@@ -0,0 +1,31 @@
//
// This file is auto-generated. Please don't modify it!
//
#pragma once
#ifdef __cplusplus
//#import "opencv.hpp"
$additionalImports
#else
#define CV_EXPORTS
#endif
#import <Foundation/Foundation.h>
$importBaseClass
$forwardDeclarations
$enumDeclarations
NS_ASSUME_NONNULL_BEGIN
$docs
CV_EXPORTS @interface $objcName : $base
$nativePointerHandling
$methodDeclarations
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,14 @@
//
// This file is auto-generated. Please don't modify it!
//
#import "$objcName.h"
#import "CVObjcUtil.h"
$imports
@implementation $objcName
$methodImplementations
@end
@@ -0,0 +1,28 @@
//
// This file is auto-generated. Please don't modify it!
//
#pragma once
#ifdef __cplusplus
//#import "opencv.hpp"
$additionalImports
#else
#define CV_EXPORTS
#endif
#import <Foundation/Foundation.h>
$forwardDeclarations
$enumDeclarations
NS_ASSUME_NONNULL_BEGIN
$docs
CV_EXPORTS @interface $objcName : $base
$methodDeclarations
@end
NS_ASSUME_NONNULL_END
+46
View File
@@ -0,0 +1,46 @@
cmake_minimum_required(VERSION 3.15)
project(OpenCVTest)
enable_testing()
find_package(XCTest REQUIRED)
# Enable C++11
set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
set (OBJC_COMPILE_FLAGS "-fobjc-arc -fobjc-weak -fvisibility=hidden")
set (SUPPRESS_WARNINGS_FLAGS "-Wno-incomplete-umbrella")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OBJC_COMPILE_FLAGS} ${SUPPRESS_WARNINGS_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OBJC_ARC_COMPILE_FLAGS} ${SUPPRESS_WARNINGS_FLAGS}")
# grab the files
file(GLOB_RECURSE test_sources "test/*\.h" "test/*\.m" "test/*\.mm" "test/*\.swift")
add_library(OpenCVTest STATIC dummy/dummy.mm)
enable_language(Swift)
# XCTest for Framework
xctest_add_bundle(OpenCVTestTests OpenCVTest ${test_sources} test/resources ${FRAMEWORK_DIR}/${FRAMEWORK_NAME}.framework)
set_target_properties(OpenCVTestTests PROPERTIES
XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS "${FRAMEWORK_DIR}"
XCODE_ATTRIBUTE_OTHER_SWIFT_FLAGS "-Xcc ${SUPPRESS_WARNINGS_FLAGS}"
XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "${FRAMEWORK_DIR}"
)
# link necessary Frameworks
target_link_libraries(OpenCVTestTests PRIVATE "-framework Accelerate")
target_link_libraries(OpenCVTestTests PRIVATE "-framework AVFoundation")
target_link_libraries(OpenCVTestTests PRIVATE "-framework CoreMedia")
if (NOT DEFINED IOS_ARCH)
target_link_libraries(OpenCVTestTests PRIVATE "-framework OpenCL")
endif()
# its OK to ignore stuff we don't know about since there will be no tests relying on it
set_target_properties(OpenCVTestTests PROPERTIES LINK_FLAGS -Wl,-undefined,dynamic_lookup)
set_source_files_properties(test/resources PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
xctest_add_test(XCTest.OpenCVTest OpenCVTestTests)
+8
View File
@@ -0,0 +1,8 @@
//
// dummy.mm
//
// Created by Giles Payne on 2019/10/13.
//
void dummy() {
}
+226
View File
@@ -0,0 +1,226 @@
//
// OpenCVTestCase.swift
//
// Created by Giles Payne on 2020/01/19.
//
import XCTest
import OpenCV
enum OpenCVTestError: Error {
case unsupportedOperationError(String)
}
open class OpenCVTestCase: XCTestCase {
//change to 'true' to unblock fail on fail("Not yet implemented")
static let passNYI = true
static let isTestCaseEnabled = true
static let XFEATURES2D = "xfeatures2d"
static let DEFAULT_FACTORY = "create"
static let matSize: Int32 = 10
static let EPS = 0.001
static let FEPS:Float = 0.001
static let weakEPS = 0.5
static let weakFEPS:Float = 0.5
var dst: Mat = Mat()
var truth: Mat? = nil
let colorBlack = Scalar(0)
let colorWhite = Scalar(255, 255, 255)
// Naming notation: <channels info>_[depth]_[dimensions]_value
// examples: gray0 - single channel 8U 2d Mat filled with 0
// grayRnd - single channel 8U 2d Mat filled with random numbers
// gray0_32f_1d
let gray0 = Mat(rows:matSize, cols:matSize, type:CvType.CV_8U, scalar:Scalar(0))
let gray1 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(1))
let gray2 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(2))
let gray3 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(3))
let gray9 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(9))
let gray127 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(127))
let gray128 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(128))
let gray255 = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U, scalar: Scalar(255))
let grayRnd = Mat(rows:matSize, cols:matSize, type: CvType.CV_8U)
let gray_16u_256 = Mat(rows: matSize, cols: matSize, type: CvType.CV_16U, scalar: Scalar(256))
let gray_16s_1024 = Mat(rows: matSize, cols: matSize, type: CvType.CV_16S, scalar: Scalar(1024))
let gray0_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F, scalar: Scalar(0.0))
let gray1_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F, scalar: Scalar(1.0))
let gray3_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F, scalar: Scalar(3.0))
let gray9_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F, scalar: Scalar(9.0))
let gray255_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F, scalar: Scalar(255.0))
let grayE_32f = Mat.eye(rows: matSize, cols: matSize, type: CvType.CV_32FC1)
let grayRnd_32f = Mat(rows: matSize, cols: matSize, type: CvType.CV_32F)
let gray0_64f = Mat(rows: matSize, cols: matSize, type: CvType.CV_64F, scalar: Scalar(0.0))
let gray0_32f_1d = Mat(rows: 1, cols: matSize, type: CvType.CV_32F, scalar: Scalar(0.0))
let gray0_64f_1d = Mat(rows: 1, cols: matSize, type: CvType.CV_64F, scalar: Scalar(0.0))
let rgba0 = Mat(rows: matSize, cols: matSize, type: CvType.CV_8UC4, scalar: Scalar.all(0))
let rgba128 = Mat(rows: matSize, cols: matSize, type: CvType.CV_8UC4, scalar: Scalar.all(128))
let rgbLena: Mat = {
return Imgcodecs.imread(filename: Bundle(for: OpenCVTestCase.self).path(forResource:"lena", ofType:"png", inDirectory:"resources")!)
}()
let grayChess: Mat = {
return Imgcodecs.imread(filename: Bundle(for: OpenCVTestCase.self).path(forResource:"chessboard", ofType:"jpg", inDirectory:"resources")!, flags: ImreadModes.IMREAD_GRAYSCALE.rawValue)
}()
let gray255_32f_3d = Mat(sizes: [matSize, matSize, matSize] as [NSNumber], type: CvType.CV_32F, scalar: Scalar(255.0))
let v1 = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
let v2 = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
override open func setUp() {
//Core.setErrorVerbosity(false)
Core.randu(dst: grayRnd, low: 0, high: 255)
Core.randu(dst: grayRnd_32f, low:0, high: 255)
do {
try v1.put(row: 0,col: 0, data: [1.0, 3.0, 2.0])
try v2.put(row: 0,col: 0, data: [2.0, 1.0, 3.0])
} catch {
print("Fatal error in start-up")
}
}
override open func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func assertMatEqual(_ expected:Mat, _ actual:Mat, file: StaticString = #file, line: UInt = #line) throws {
try compareMats(expected, actual, true, file:file, line:line)
}
func assertMatNotEqual(_ expected:Mat, _ actual:Mat, file: StaticString = #file, line: UInt = #line) throws {
try compareMats(expected, actual, false, file:file, line:line)
}
func assertMatEqual(_ expected:Mat, _ actual:Mat, _ eps:Double, file: StaticString = #file, line: UInt = #line) throws {
try compareMats(expected, actual, eps, true, file:file, line:line);
}
func assertMatNotEqual(_ expected:Mat, _ actual:Mat, _ eps:Double, file: StaticString = #file, line: UInt = #line) throws {
try compareMats(expected, actual, eps, false, file:file, line:line);
}
func assertSizeEquals(_ expected:Size,_ actual: Size, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.width, actual.width, msg, file:file, line:line)
XCTAssertEqual(expected.height, actual.height, msg, file:file, line:line)
}
func assertSize2fEquals(_ expected:Size2f,_ actual: Size2f,_ eps: Float, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.width, actual.width, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.height, actual.height, accuracy:eps, msg, file:file, line:line)
}
func assertSize2dEquals(_ expected:Size2d,_ actual: Size2d,_ eps: Double, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.width, actual.width, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.height, actual.height, accuracy:eps, msg, file:file, line:line)
}
func assertPointEquals(_ expected:Point, _ actual: Point, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.x, actual.x, msg, file:file, line:line)
XCTAssertEqual(expected.y, actual.y, msg, file:file, line:line)
}
func assertPoint2dEquals(_ expected:Point2d, _ actual: Point2d, _ eps: Double, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.x, actual.x, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.y, actual.y, accuracy:eps, msg, file:file, line:line)
}
func assertPoint2fEquals(_ expected:Point2f, _ actual: Point2f, _ eps: Float, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.x, actual.x, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.y, actual.y, accuracy:eps, msg, file:file, line:line)
}
func assertScalarEqual(_ expected:Scalar, _ actual:Scalar, _ eps: Double, file: StaticString = #file, line: UInt = #line) {
let msg = "expected:<\(expected)> but was:<\(actual)>"
XCTAssertEqual(expected.val[0] as! Double, actual.val[0] as! Double, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.val[1] as! Double, actual.val[1] as! Double, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.val[2] as! Double, actual.val[2] as! Double, accuracy:eps, msg, file:file, line:line)
XCTAssertEqual(expected.val[3] as! Double, actual.val[3] as! Double, accuracy:eps, msg, file:file, line:line)
}
func assertArrayEquals(_ expected:[Double], _ actual:[Double], _ eps: Double, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(expected.count, actual.count, "Arrays have different sizes.", file:file, line:line)
for i in 0..<expected.count {
XCTAssertEqual(expected[i], actual[i], accuracy:eps, file:file, line:line)
}
}
func compareMats(_ expected:Mat, _ actual:Mat, _ isEqualityMeasured:Bool, file: StaticString = #file, line: UInt = #line) throws {
if expected.type() != actual.type() || !dimensionsEqual(expected, actual) {
throw OpenCVTestError.unsupportedOperationError("Incompatible matrices")
}
if (expected.depth() == CvType.CV_32F || expected.depth() == CvType.CV_64F) {
if isEqualityMeasured {
throw OpenCVTestError.unsupportedOperationError("Floating-point Mats must not be checked for exact match. Use assertMatEqual(expected:Mat, actual:Mat, eps:Double) instead.")
} else {
throw OpenCVTestError.unsupportedOperationError("Floating-point Mats must not be checked for exact match. Use assertMatNotEqual(expected:Mat, actual:Mat, eps:Double) instead.")
}
}
let diff = Mat()
Core.absdiff(src1: expected, src2: actual, dst: diff);
let reshaped = diff.reshape(channels: 1)
let mistakes = Core.countNonZero(src: reshaped)
if isEqualityMeasured {
XCTAssertTrue(mistakes == 0, "Mats are different in \(mistakes) points", file:file, line:line)
} else {
XCTAssertFalse(mistakes == 0, "Mats are equal", file:file, line:line)
}
}
func compareMats(_ expected: Mat, _ actual:Mat, _ eps:Double, _ isEqualityMeasured:Bool, file: StaticString = #file, line: UInt = #line) throws {
if expected.type() != actual.type() || !dimensionsEqual(expected, actual) {
throw OpenCVTestError.unsupportedOperationError("Incompatible matrices")
}
let diff = Mat()
Core.absdiff(src1: expected, src2: actual, dst: diff)
let maxDiff = Core.norm(src1: diff, normType: .NORM_INF)
if isEqualityMeasured {
XCTAssertTrue(maxDiff <= eps, "Max difference between expected and actual Mats is \(maxDiff), that bigger than \(eps)", file:file, line:line)
} else {
XCTAssertFalse(maxDiff <= eps, "Max difference between expected and actual Mats is \(maxDiff), that less than \(eps)", file:file, line:line)
}
}
func dimensionsEqual(_ expected: Mat, _ actual: Mat) -> Bool {
if expected.dims() != actual.dims() {
return false
}
if expected.dims() > 2 {
return (0..<expected.dims()).allSatisfy { expected.size($0) == actual.size($0) }
} else {
return expected.cols() == actual.cols() && expected.rows() == actual.rows();
}
}
func getMat(_ type:Int32, vals:[NSNumber]) -> Mat {
return Mat(rows:OpenCVTestCase.matSize, cols:OpenCVTestCase.matSize, type:type, scalar:Scalar(vals: vals))
}
func makeMask(_ mat:Mat, vals:[Double] = []) -> Mat {
mat.submat(rowStart: 0, rowEnd: mat.rows(), colStart: 0, colEnd: mat.cols() / 2).setTo(scalar: Scalar(vals: vals as [NSNumber]))
return mat
}
}