Swift native in/out array handling
authorGiles Payne <gilespayne@gmail.com>
Thu, 3 Sep 2020 12:31:11 +0000 (21:31 +0900)
committerGiles Payne <gilespayne@gmail.com>
Thu, 3 Sep 2020 12:31:11 +0000 (21:31 +0900)
13 files changed:
modules/calib3d/misc/objc/test/Calib3dTest.swift
modules/core/misc/objc/common/ByteVectorExt.swift
modules/core/misc/objc/gen_dict.json
modules/core/misc/objc/test/CoreTest.swift
modules/dnn/misc/objc/gen_dict.json
modules/imgcodecs/misc/objc/test/ImgcodecsTest.swift
modules/imgproc/misc/objc/gen_dict.json
modules/imgproc/misc/objc/test/ImgprocTest.swift
modules/imgproc/misc/objc/test/Subdiv2DTest.swift
modules/objc/generator/gen_objc.py
modules/objc/test/test/OpenCVTestCase.swift
samples/swift/ios/ColorBlobDetection/ColorBlobDetection/ColorBlobDetector.swift
samples/swift/ios/FaceDetection/FaceDetection/ViewController.swift

index 85786e2..3fe4cb8 100644 (file)
@@ -378,15 +378,15 @@ class Calib3dTest: OpenCVTestCase {
             try points3d.put(row: i, col: 0, data: [0, y, x]) // add(Point3(0, y, x))
         }
 
-        let rvecs = NSMutableArray()
-        let tvecs = NSMutableArray()
+        var rvecs = [Mat]()
+        var tvecs = [Mat]()
 
         let rvec = Mat()
         let tvec = Mat()
 
         let reprojectionError = Mat(rows: 2, cols: 1, type: CvType.CV_64FC1)
 
-        Calib3d.solvePnPGeneric(objectPoints: points3d, imagePoints: points2d, cameraMatrix: intrinsics, distCoeffs: MatOfDouble(), rvecs: rvecs, tvecs: tvecs, useExtrinsicGuess: false, flags: .SOLVEPNP_IPPE, rvec: rvec, tvec: tvec, reprojectionError: reprojectionError)
+        Calib3d.solvePnPGeneric(objectPoints: points3d, imagePoints: points2d, cameraMatrix: intrinsics, distCoeffs: MatOfDouble(), rvecs: &rvecs, tvecs: &tvecs, useExtrinsicGuess: false, flags: .SOLVEPNP_IPPE, rvec: rvec, tvec: tvec, reprojectionError: reprojectionError)
 
         let truth_rvec = Mat(rows: 3, cols: 1, type: CvType.CV_64F)
         try truth_rvec.put(row: 0, col: 0, data: [0, .pi / 2, 0] as [Double])
@@ -394,8 +394,8 @@ class Calib3dTest: OpenCVTestCase {
         let truth_tvec = Mat(rows: 3, cols: 1, type: CvType.CV_64F)
         try truth_tvec.put(row: 0, col: 0, data: [-320, -240, 400] as [Double])
 
-        try assertMatEqual(truth_rvec, rvecs[0] as! Mat, 10 * OpenCVTestCase.EPS)
-        try assertMatEqual(truth_tvec, tvecs[0] as! Mat, 1000 * OpenCVTestCase.EPS)
+        try assertMatEqual(truth_rvec, rvecs[0], 10 * OpenCVTestCase.EPS)
+        try assertMatEqual(truth_tvec, tvecs[0], 1000 * OpenCVTestCase.EPS)
     }
 
     func testGetDefaultNewCameraMatrixMat() {
index e553de0..05b7d9d 100644 (file)
@@ -12,6 +12,11 @@ public extension ByteVector {
         self.init(data:data);
     }
 
+    convenience init(_ array:[UInt8]) {
+        let data = array.withUnsafeBufferPointer { Data(buffer: $0) }
+        self.init(data:data);
+    }
+
     subscript(index: Int) -> Int8 {
         get {
             return self.get(index)
@@ -25,6 +30,14 @@ public extension ByteVector {
             return ret
         }
     }
+
+    var unsignedArray: [UInt8] {
+        get {
+            var ret = Array<UInt8>(repeating: 0, count: data.count/MemoryLayout<UInt8>.stride)
+            _ = ret.withUnsafeMutableBytes { data.copyBytes(to: $0) }
+            return ret
+        }
+    }
 }
 
 extension ByteVector : Sequence {
index 1d7d5d6..4cb8133 100644 (file)
         "Point": {
             "objc_type": "Point2i*",
             "to_cpp": "%(n)s.nativeRef",
-            "from_cpp": "[Point2i fromNative:%(n)s]"
+            "from_cpp": "[Point2i fromNative:%(n)s]",
+            "swift_type": "Point"
+        },
+        "Point2i": {
+            "objc_type": "Point2i*",
+            "to_cpp": "%(n)s.nativeRef",
+            "from_cpp": "[Point2i fromNative:%(n)s]",
+            "swift_type": "Point"
         },
         "Point2f": {
             "objc_type": "Point2f*",
         "Rect": {
             "objc_type": "Rect2i*",
             "to_cpp": "%(n)s.nativeRef",
-            "from_cpp": "[Rect2i fromNative:%(n)s]"
+            "from_cpp": "[Rect2i fromNative:%(n)s]",
+            "swift_type": "Rect"
         },
         "Rect2i": {
             "objc_type": "Rect2i*",
             "to_cpp": "%(n)s.nativeRef",
-            "from_cpp": "[Rect2i fromNative:%(n)s]"
+            "from_cpp": "[Rect2i fromNative:%(n)s]",
+            "swift_type": "Rect"
         },
         "Rect2f": {
             "objc_type": "Rect2f*",
         "Size": {
             "objc_type": "Size2i*",
             "to_cpp": "%(n)s.nativeRef",
-            "from_cpp": "[Size2i fromNative:%(n)s]"
+            "from_cpp": "[Size2i fromNative:%(n)s]",
+            "swift_type": "Size"
+        },
+        "Size2i": {
+            "objc_type": "Size2i*",
+            "to_cpp": "%(n)s.nativeRef",
+            "from_cpp": "[Size2i fromNative:%(n)s]",
+            "swift_type": "Size"
         },
         "Size2f": {
             "objc_type": "Size2f*",
         "String": {
             "objc_type": "NSString*",
             "to_cpp": "cv::String(%(n)s.UTF8String)",
-            "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]"
+            "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]",
+            "swift_type": "String"
         },
         "std::string": {
             "objc_type": "NSString*",
             "to_cpp": "std::string(%(n)s.UTF8String)",
-            "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]"
+            "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]",
+            "swift_type": "String"
         },
         "TermCriteria": {
             "objc_type": "TermCriteria*",
         "c_string": {
             "objc_type": "NSString*",
             "to_cpp": "%(n)s.UTF8String",
-            "from_cpp": "[NSString stringWithUTF8String:%(n)s]"
+            "from_cpp": "[NSString stringWithUTF8String:%(n)s]",
+            "swift_type": "String"
         },
         "vector_DMatch": {
             "objc_type": "DMatch*",
         },
         "vector_Point": {
             "objc_type": "Point2i*",
-            "v_type": "Point"
+            "v_type": "Point2i",
+            "swift_type": "[Point]"
         },
         "vector_Point2f": {
             "objc_type": "Point2f*",
         },
         "vector_Rect": {
             "objc_type": "Rect2i*",
-            "v_type": "Rect2i"
+            "v_type": "Rect2i",
+            "swift_type": "[Rect]"
         },
         "vector_Rect2d": {
             "objc_type": "Rect2d*",
         },
         "vector_String": {
             "objc_type": "NSString*",
-            "v_type": "String"
+            "v_type": "String",
+            "swift_type": "[String]"
         },
         "vector_string": {
             "objc_type": "NSString*",
-            "v_type": "std::string"
+            "v_type": "std::string",
+            "swift_type": "[String]"
         },
         "vector_Vec4f": {
             "objc_type": "Float4*",
             "objc_type": "ByteVector*",
             "to_cpp": "%(n)s.nativeRef",
             "from_cpp": "[ByteVector fromNative:%(n)s]",
-            "cast_to": "std::vector<char>"
+            "cast_to": "std::vector<char>",
+            "primitive_vector": true,
+            "swift_type": "[Int8]"
         },
         "vector_double": {
             "objc_type": "DoubleVector*",
             "to_cpp": "%(n)s.nativeRef",
             "from_cpp": "[DoubleVector fromNative:%(n)s]",
-            "cast_to": "std::vector<double>"
+            "cast_to": "std::vector<double>",
+            "primitive_vector": true,
+            "swift_type": "[Double]"
         },
         "vector_float": {
             "objc_type": "FloatVector*",
             "to_cpp": "%(n)s.nativeRef",
             "from_cpp": "[FloatVector fromNative:%(n)s]",
-            "cast_to": "std::vector<float>"
+            "cast_to": "std::vector<float>",
+            "primitive_vector": true,
+            "swift_type": "[Float]"
         },
         "vector_int": {
             "objc_type": "IntVector*",
             "to_cpp": "%(n)s.nativeRef",
             "from_cpp": "[IntVector fromNative:%(n)s]",
-            "cast_to": "std::vector<int>"
+            "cast_to": "std::vector<int>",
+            "primitive_vector": true,
+            "swift_type": "[Int32]"
         },
         "vector_uchar": {
             "objc_type": "ByteVector*",
             "to_cpp": "(std::vector<uchar>&)%(n)s.nativeRef",
             "from_cpp": "[ByteVector fromNative:(std::vector<char>&)%(n)s]",
-            "cast_to": "std::vector<uchar>"
+            "cast_to": "std::vector<uchar>",
+            "primitive_vector": true,
+            "swift_type": "[UInt8]",
+            "unsigned": true
         },
         "vector_vector_Mat": {
             "objc_type": "Mat*",
         },
         "vector_vector_Point": {
             "objc_type": "Point2i*",
-            "v_v_type": "Point"
+            "v_v_type": "Point2i",
+            "swift_type": "[[Point]]"
         },
         "vector_vector_Point2f": {
             "objc_type": "Point2f*",
         },
         "vector_vector_char": {
             "objc_type": "ByteVector*",
-            "v_type": "ByteVector"
+            "v_type": "ByteVector",
+            "primitive_vector_vector": true,
+            "swift_type": "[[Int8]]"
         },
         "vector_vector_int": {
             "objc_type": "IntVector*",
-            "v_type": "IntVector"
+            "v_type": "IntVector",
+            "primitive_vector_vector": true,
+            "swift_type": "[[Int32]]"
         },
         "vector_vector_float": {
             "objc_type": "FloatVector*",
-            "v_type": "FloatVector"
+            "v_type": "FloatVector",
+            "primitive_vector_vector": true,
+            "swift_type": "[[Float]]"
         },
         "vector_vector_double": {
             "objc_type": "DoubleVector*",
-            "v_type": "DoubleVector"
+            "v_type": "DoubleVector",
+            "primitive_vector_vector": true,
+            "swift_type": "[[Double]]"
         },
         "ByteVector": {
             "objc_type": "ByteVector*",
index efa18bb..535675a 100644 (file)
@@ -854,15 +854,15 @@ class CoreTest: OpenCVTestCase {
     }
 
     func testMeanStdDevMatMatMat() {
-        let mean = DoubleVector()
-        let stddev = DoubleVector()
-        Core.meanStdDev(src: rgbLena, mean: mean, stddev: stddev)
+        var mean = [Double]()
+        var stddev = [Double]()
+        Core.meanStdDev(src: rgbLena, mean: &mean, stddev: &stddev)
 
         let expectedMean = [105.3989906311035, 99.56269836425781, 179.7303047180176]
         let expectedDev = [33.74205485167219, 52.8734582803278, 49.01569488056406]
 
-        assertArrayEquals(expectedMean as [NSNumber], mean.array as [NSNumber], OpenCVTestCase.EPS)
-        assertArrayEquals(expectedDev as [NSNumber], stddev.array as [NSNumber], OpenCVTestCase.EPS)
+        assertArrayEquals(expectedMean, mean, OpenCVTestCase.EPS)
+        assertArrayEquals(expectedDev, stddev, OpenCVTestCase.EPS)
     }
 
     func testMeanStdDevMatMatMatMat() {
@@ -871,16 +871,16 @@ class CoreTest: OpenCVTestCase {
         let mask = gray0.clone()
         submat = mask.submat(rowStart: 0, rowEnd: mask.rows() / 2, colStart: 0, colEnd: mask.cols() / 2)
         submat.setTo(scalar: Scalar(1))
-        let mean = DoubleVector()
-        let stddev = DoubleVector()
+        var mean = [Double]()
+        var stddev = [Double]()
 
-        Core.meanStdDev(src: grayRnd, mean: mean, stddev: stddev, mask: mask)
+        Core.meanStdDev(src: grayRnd, mean: &mean, stddev: &stddev, mask: mask)
 
-        let expectedMean = [33]
-        let expectedDev = [0]
+        let expectedMean = [33.0]
+        let expectedDev = [0.0]
 
-        assertArrayEquals(expectedMean as [NSNumber], mean.array as [NSNumber], OpenCVTestCase.EPS)
-        assertArrayEquals(expectedDev as [NSNumber], stddev.array as [NSNumber], OpenCVTestCase.EPS)
+        assertArrayEquals(expectedMean, mean, OpenCVTestCase.EPS)
+        assertArrayEquals(expectedDev, stddev, OpenCVTestCase.EPS)
     }
 
     func testMerge() throws {
@@ -940,14 +940,14 @@ class CoreTest: OpenCVTestCase {
         rgba0Copy.setTo(scalar: Scalar(10, 20, 30, 40))
         let src = [rgba0Copy]
         let dst = [gray3, gray2, gray1, gray0, getMat(CvType.CV_8UC3, vals: [0, 0, 0])]
-        let fromTo = IntVector([
+        let fromTo:[Int32] = [
                 3, 0,
                 3, 1,
                 2, 2,
                 0, 3,
                 2, 4,
                 1, 5,
-                0, 6])
+                0, 6]
 
         Core.mixChannels(src: src, dst: dst, fromTo: fromTo)
 
@@ -1530,13 +1530,13 @@ class CoreTest: OpenCVTestCase {
 
     func testSplit() throws {
         let m = getMat(CvType.CV_8UC3, vals: [1, 2, 3])
-        let cois = NSMutableArray()
+        var cois = [Mat]()
 
-        Core.split(m: m, mv: cois)
+        Core.split(m: m, mv: &cois)
 
-        try assertMatEqual(gray1, cois[0] as! Mat)
-        try assertMatEqual(gray2, cois[1] as! Mat)
-        try assertMatEqual(gray3, cois[2] as! Mat)
+        try assertMatEqual(gray1, cois[0])
+        try assertMatEqual(gray2, cois[1])
+        try assertMatEqual(gray3, cois[2])
     }
 
     func testSqrt() throws {
index 869183f..e6d561f 100644 (file)
@@ -13,6 +13,7 @@
         "Net": {
             "(void)forward:(NSMutableArray<Mat*>*)outputBlobs outputName:(NSString*)outputName" : { "forward" : {"name" : "forwardOutputBlobs"} },
             "(void)forward:(NSMutableArray<Mat*>*)outputBlobs outBlobNames:(NSArray<NSString*>*)outBlobNames" : { "forward" : {"name" : "forwardOutputBlobs"} },
+            "(void)forwardAndRetrieve:(NSMutableArray<NSMutableArray<Mat*>*>*)outputBlobs outBlobNames:(NSArray<NSString*>*)outBlobNames" : { "forward" : {"swift_name" : "forwardAndRetrieve"} },
             "(long)getFLOPS:(IntVector*)netInputShape" : { "getFLOPS" : {"name" : "getFLOPSWithNetInputShape"} },
             "(long)getFLOPS:(NSArray<IntVector*>*)netInputShapes" : { "getFLOPS" : {"name" : "getFLOPSWithNetInputShapes"} },
             "(long)getFLOPS:(int)layerId netInputShape:(IntVector*)netInputShape" : { "getFLOPS" : {"name" : "getFLOPSWithLayerId"} },
index 857c95e..92d507e 100644 (file)
@@ -12,23 +12,23 @@ class ImgcodecsTest: OpenCVTestCase {
     let LENA_PATH = Bundle(for: ImgcodecsTest.self).path(forResource:"lena", ofType:"png", inDirectory:"resources")!
 
     func testImencodeStringMatListOfByte() {
-        let buff = ByteVector()
-        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: gray127, buf: buff))
-        XCTAssertFalse(0 == buff.length)
+        var buff = [UInt8]()
+        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: gray127, buf: &buff))
+        XCTAssertFalse(0 == buff.count)
     }
 
     func testImencodeStringMatListOfByteListOfInteger() {
-        let params40 = IntVector([ImwriteFlags.IMWRITE_JPEG_QUALITY.rawValue, 40])
-        let params90 = IntVector([ImwriteFlags.IMWRITE_JPEG_QUALITY.rawValue, 90])
+        let params40:[Int32] = [ImwriteFlags.IMWRITE_JPEG_QUALITY.rawValue, 40]
+        let params90:[Int32] = [ImwriteFlags.IMWRITE_JPEG_QUALITY.rawValue, 90]
 
-        let buff40 = ByteVector()
-        let buff90 = ByteVector()
+        var buff40 = [UInt8]()
+        var buff90 = [UInt8]()
 
-        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: rgbLena, buf: buff40, params: params40))
-        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: rgbLena, buf: buff90, params: params90))
+        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: rgbLena, buf: &buff40, params: params40))
+        XCTAssert(Imgcodecs.imencode(ext: ".jpg", img: rgbLena, buf: &buff90, params: params90))
 
-        XCTAssert(buff40.length > 0)
-        XCTAssert(buff40.length < buff90.length)
+        XCTAssert(buff40.count > 0)
+        XCTAssert(buff40.count < buff90.count)
     }
 
     func testImreadString() {
index 1bb2d54..043baa5 100644 (file)
@@ -1,4 +1,8 @@
 {
+    "enum_ignore_list" : [
+        "MorphShapes_c",
+        "SmoothMethod_c"
+    ],
     "module_imports": ["Size2i"],
     "const_ignore_list": [
         "CV_TM_.+",
index c766883..72432ce 100644 (file)
@@ -125,13 +125,13 @@ class ImgprocTest: OpenCVTestCase {
     func testApproxPolyDP() {
         let curve = [Point2f(x: 1, y: 3), Point2f(x: 2, y: 4), Point2f(x: 3, y: 5), Point2f(x: 4, y: 4), Point2f(x: 5, y: 3)]
 
-        let approxCurve = NSMutableArray()
+        var approxCurve = [Point2f]()
 
-        Imgproc.approxPolyDP(curve: curve, approxCurve: approxCurve, epsilon: OpenCVTestCase.EPS, closed: true)
+        Imgproc.approxPolyDP(curve: curve, approxCurve: &approxCurve, epsilon: OpenCVTestCase.EPS, closed: true)
 
         let approxCurveGold = [Point2f(x: 1, y: 3), Point2f(x: 3, y: 5), Point2f(x: 5, y: 3)]
 
-        XCTAssert(approxCurve as! [Point2f] == approxCurveGold)
+        XCTAssert(approxCurve == approxCurveGold)
     }
 
     func testArcLength() {
@@ -201,9 +201,9 @@ class ImgprocTest: OpenCVTestCase {
 
     func testCalcBackProject() {
         let images = [grayChess]
-        let channels = IntVector([0])
-        let histSize = IntVector([10])
-        let ranges = FloatVector([0, 256])
+        let channels:[Int32] = [0]
+        let histSize:[Int32] = [10]
+        let ranges:[Float] = [0, 256]
 
         let hist = Mat()
         Imgproc.calcHist(images: images, channels: channels, mask: Mat(), hist: hist, histSize: histSize, ranges: ranges)
@@ -218,9 +218,9 @@ class ImgprocTest: OpenCVTestCase {
 
     func testCalcHistListOfMatListOfIntegerMatMatListOfIntegerListOfFloat() throws {
         let images = [gray128]
-        let channels = IntVector([0])
-        let histSize = IntVector([10])
-        let ranges = FloatVector([0, 256])
+        let channels:[Int32] = [0]
+        let histSize:[Int32] = [10]
+        let ranges:[Float] = [0, 256]
         let hist = Mat()
 
         Imgproc.calcHist(images: images, channels: channels, mask: Mat(), hist: hist, histSize: histSize, ranges: ranges)
@@ -232,9 +232,9 @@ class ImgprocTest: OpenCVTestCase {
 
     func testCalcHistListOfMatListOfIntegerMatMatListOfIntegerListOfFloat2D() throws {
         let images = [gray255, gray128]
-        let channels = IntVector([0, 1])
-        let histSize = IntVector([10, 10])
-        let ranges = FloatVector([0, 256, 0, 256])
+        let channels:[Int32] = [0, 1]
+        let histSize:[Int32] = [10, 10]
+        let ranges:[Float] = [0, 256, 0, 256]
         let hist = Mat()
 
         Imgproc.calcHist(images: images, channels: channels, mask: Mat(), hist: hist, histSize: histSize, ranges: ranges)
@@ -250,11 +250,11 @@ class ImgprocTest: OpenCVTestCase {
         let hist3D = Mat()
         let histList = [Mat(), Mat(), Mat()]
 
-        let histSize = IntVector([10])
-        let ranges = FloatVector([0, 256])
+        let histSize: [Int32] = [10]
+        let ranges: [Float] = [0, 256]
 
         for i:Int in 0..<Int(rgbLena.channels()) {
-            Imgproc.calcHist(images: images, channels: IntVector([Int32(i)]), mask: Mat(), hist: histList[i], histSize: histSize, ranges: ranges)
+            Imgproc.calcHist(images: images, channels: [Int32(i)], mask: Mat(), hist: histList[i], histSize: histSize, ranges: ranges)
 
             XCTAssertEqual(10, histList[i].checkVector(elemChannels: 1))
         }
@@ -282,9 +282,9 @@ class ImgprocTest: OpenCVTestCase {
 
     func testCalcHistListOfMatListOfIntegerMatMatListOfIntegerListOfFloatBoolean() throws {
         let images = [gray255, gray128]
-        let channels = IntVector([0, 1])
-        let histSize = IntVector([10, 10])
-        let ranges = FloatVector([0, 256, 0, 256])
+        let channels:[Int32] = [0, 1]
+        let histSize:[Int32] = [10, 10]
+        let ranges:[Float] = [0, 256, 0, 256]
         let hist = Mat()
 
         Imgproc.calcHist(images: images, channels: channels, mask: Mat(), hist: hist, histSize: histSize, ranges: ranges, accumulate: true)
@@ -372,12 +372,11 @@ class ImgprocTest: OpenCVTestCase {
                     Point(x: 20, y: 10),
                     Point(x: 30, y: 10)]
 
-        let hull = IntVector()
+        var hull = [Int32]()
 
-        Imgproc.convexHull(points: points, hull: hull)
+        Imgproc.convexHull(points: points, hull: &hull)
 
-        let expHull = IntVector([0, 1, 2, 3])
-        XCTAssert(expHull.array == hull.array)
+        XCTAssert([0, 1, 2, 3] == hull)
     }
 
     func testConvexHullMatMatBooleanBoolean() {
@@ -388,12 +387,11 @@ class ImgprocTest: OpenCVTestCase {
                       Point(x: 2, y: 1),
                       Point(x: 3, y: 1)]
 
-        let hull = IntVector()
+        var hull = [Int32]()
 
-        Imgproc.convexHull(points: points, hull: hull, clockwise: true)
+        Imgproc.convexHull(points: points, hull: &hull, clockwise: true)
 
-        let expHull = IntVector([3, 2, 1, 0])
-        XCTAssert(expHull.array == hull.array)
+        XCTAssert([3, 2, 1, 0] == hull)
     }
 
     func testConvexityDefects() throws {
@@ -404,13 +402,13 @@ class ImgprocTest: OpenCVTestCase {
                       Point(x: 20, y: 10),
                       Point(x: 30, y: 10)]
 
-        let hull = IntVector()
-        Imgproc.convexHull(points: points, hull: hull)
+        var hull = [Int32]()
+        Imgproc.convexHull(points: points, hull: &hull)
 
-        let convexityDefects = NSMutableArray()
-        Imgproc.convexityDefects(contour: points, convexhull: hull, convexityDefects: convexityDefects)
+        var convexityDefects = [Int4]()
+        Imgproc.convexityDefects(contour: points, convexhull: hull, convexityDefects: &convexityDefects)
 
-        XCTAssertTrue(Int4(v0: 3, v1: 0, v2: 5, v3: 3620) == (convexityDefects[0] as! Int4))
+        XCTAssertTrue(Int4(v0: 3, v1: 0, v2: 5, v3: 3620) == convexityDefects[0])
     }
 
     func testCornerEigenValsAndVecsMatMatIntInt() throws {
@@ -543,10 +541,10 @@ class ImgprocTest: OpenCVTestCase {
     func testDrawContoursMatListOfMatIntScalar() {
         let gray0clone = gray0.clone()
         Imgproc.rectangle(img: gray0clone, pt1: Point(x: 1, y: 2), pt2: Point(x: 7, y: 8), color: Scalar(100))
-        let contours = NSMutableArray()
-        Imgproc.findContours(image: gray0clone, contours: contours, hierarchy: Mat(), mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        var contours = [[Point]]()
+        Imgproc.findContours(image: gray0clone, contours: &contours, hierarchy: Mat(), mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
 
-        Imgproc.drawContours(image: gray0clone, contours: contours as! [[Point]], contourIdx: -1, color: Scalar(0))
+        Imgproc.drawContours(image: gray0clone, contours: contours, contourIdx: -1, color: Scalar(0))
 
         XCTAssertEqual(0, Core.countNonZero(src: gray0clone))
     }
@@ -554,10 +552,10 @@ class ImgprocTest: OpenCVTestCase {
     func testDrawContoursMatListOfMatIntScalarInt() {
         let gray0clone = gray0.clone()
         Imgproc.rectangle(img: gray0clone, pt1: Point(x: 1, y: 2), pt2: Point(x: 7, y: 8), color: Scalar(100))
-        let contours = NSMutableArray()
-        Imgproc.findContours(image: gray0clone, contours: contours, hierarchy: Mat(), mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        var contours = [[Point]]()
+        Imgproc.findContours(image: gray0clone, contours: &contours, hierarchy: Mat(), mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
 
-        Imgproc.drawContours(image: gray0clone, contours: contours as! [[Point]], contourIdx: -1, color: Scalar(0), thickness: Core.FILLED)
+        Imgproc.drawContours(image: gray0clone, contours: contours, contourIdx: -1, color: Scalar(0), thickness: Core.FILLED)
 
         XCTAssertEqual(0, Core.countNonZero(src: gray0clone))
     }
@@ -631,10 +629,10 @@ class ImgprocTest: OpenCVTestCase {
 
     func testFindContoursMatListOfMatMatIntInt() {
         let img = Mat(rows: 50, cols: 50, type: CvType.CV_8UC1, scalar: Scalar(0))
-        let contours = NSMutableArray()
+        var contours = [[Point]]()
         let hierarchy = Mat()
 
-        Imgproc.findContours(image: img, contours: contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        Imgproc.findContours(image: img, contours: &contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
 
         // no contours on empty image
         XCTAssertEqual(contours.count, 0)
@@ -643,7 +641,7 @@ class ImgprocTest: OpenCVTestCase {
         Imgproc.rectangle(img: img, pt1: Point(x: 10, y: 20), pt2: Point(x: 20, y: 30), color: Scalar(100), thickness: 3, lineType: .LINE_AA, shift: 0)
         Imgproc.rectangle(img: img, pt1: Point(x: 30, y: 35), pt2: Point(x: 40, y: 45), color: Scalar(200))
 
-        Imgproc.findContours(image: img, contours: contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        Imgproc.findContours(image: img, contours: &contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
 
         // two contours of two rectangles
         XCTAssertEqual(contours.count, 2)
@@ -653,18 +651,18 @@ class ImgprocTest: OpenCVTestCase {
     func testFindContoursMatListOfMatMatIntIntPoint() throws {
         let img = Mat(rows: 50, cols: 50, type: CvType.CV_8UC1, scalar: Scalar(0))
         let img2 = img.submat(rowStart: 5, rowEnd: 50, colStart: 3, colEnd: 50)
-        let contours = NSMutableArray()
-        let contours2 = NSMutableArray()
+        var contours = [[Point]]()
+        var contours2 = [[Point]]()
         let hierarchy = Mat()
 
         Imgproc.rectangle(img: img, pt1: Point(x: 10, y: 20), pt2: Point(x: 20, y: 30), color: Scalar(100), thickness: 3, lineType: .LINE_AA, shift: 0)
         Imgproc.rectangle(img: img, pt1: Point(x: 30, y: 35), pt2: Point(x: 40, y: 45), color: Scalar(200))
 
-        Imgproc.findContours(image: img, contours: contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
-        Imgproc.findContours(image: img2, contours: contours2, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE, offset: Point(x: 3, y: 5))
+        Imgproc.findContours(image: img, contours: &contours, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        Imgproc.findContours(image: img2, contours: &contours2, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE, offset: Point(x: 3, y: 5))
 
         XCTAssertEqual(contours.count, contours2.count)
-        XCTAssert(contours[0] as! [Point] == contours2[0] as! [Point])
+        XCTAssert(contours[0] == contours2[0])
     }
 
     func testFitEllipse() {
@@ -853,9 +851,9 @@ class ImgprocTest: OpenCVTestCase {
     func testGoodFeaturesToTrackMatListOfPointIntDoubleDouble() {
         let src = gray0
         Imgproc.rectangle(img: src, pt1: Point(x: 2, y: 2), pt2: Point(x: 8, y: 8), color: Scalar(100), thickness: -1)
-        let lp = NSMutableArray()
+        var lp = [Point]()
 
-        Imgproc.goodFeaturesToTrack(image: src, corners: lp, maxCorners: 100, qualityLevel: 0.01, minDistance: 3)
+        Imgproc.goodFeaturesToTrack(image: src, corners: &lp, maxCorners: 100, qualityLevel: 0.01, minDistance: 3)
 
         XCTAssertEqual(4, lp.count)
     }
@@ -863,9 +861,9 @@ class ImgprocTest: OpenCVTestCase {
     func testGoodFeaturesToTrackMatListOfPointIntDoubleDoubleMatIntBooleanDouble() {
         let src = gray0
         Imgproc.rectangle(img: src, pt1: Point(x: 2, y: 2), pt2: Point(x: 8, y: 8), color: Scalar(100), thickness: -1)
-        let lp = NSMutableArray()
+        var lp = [Point]()
 
-        Imgproc.goodFeaturesToTrack(image: src, corners: lp, maxCorners: 100, qualityLevel: 0.01, minDistance: 3, mask: gray1, blockSize: 4, gradientSize: 3, useHarrisDetector: true, k: 0)
+        Imgproc.goodFeaturesToTrack(image: src, corners: &lp, maxCorners: 100, qualityLevel: 0.01, minDistance: 3, mask: gray1, blockSize: 4, gradientSize: 3, useHarrisDetector: true, k: 0)
 
         XCTAssertEqual(4, lp.count)
     }
@@ -1569,12 +1567,12 @@ class ImgprocTest: OpenCVTestCase {
         let arcStart:Int32 = 30
         let arcEnd:Int32 = 60
         let delta:Int32 = 2
-        let pts = NSMutableArray()
+        var pts = [Point]()
 
-        Imgproc.ellipse2Poly(center: center, axes: axes, angle: angle, arcStart: arcStart, arcEnd: arcEnd, delta: delta, pts: pts)
+        Imgproc.ellipse2Poly(center: center, axes: axes, angle: angle, arcStart: arcStart, arcEnd: arcEnd, delta: delta, pts: &pts)
 
         let truth = [Point(x: 5, y: 6), Point(x: 4, y: 6)]
-        XCTAssert(truth == pts as! [Point])
+        XCTAssert(truth == pts)
     }
 
     func testEllipseMatPointSizeDoubleDoubleDoubleScalar() {
index 0a57fa3..b8c7538 100644 (file)
@@ -15,8 +15,8 @@ class Subdiv2DTest: OpenCVTestCase {
         s2d.insert(pt: Point2f(x: 20, y: 10))
         s2d.insert(pt: Point2f(x: 20, y: 20))
         s2d.insert(pt: Point2f(x: 10, y: 20))
-        let triangles = NSMutableArray()
-        s2d.getTriangleList(triangleList: triangles)
+        var triangles = [Float6]()
+        s2d.getTriangleList(triangleList: &triangles)
         XCTAssertEqual(2, triangles.count)
     }
 
index a67326d..1ae00ab 100755 (executable)
@@ -34,6 +34,10 @@ module_imports = []
 # the list is loaded from misc/objc/gen_dict.json defined for the module and its dependencies
 class_ignore_list = []
 
+
+# list of enum names, which should be skipped by wrapper generator
+enum_ignore_list = []
+
 # list of constant names, which should be skipped by wrapper generator
 # ignored constants can be defined using regular expressions
 const_ignore_list = []
@@ -46,16 +50,16 @@ missing_consts = {}
 
 type_dict = {
     ""        : {"objc_type" : ""}, # c-tor ret_type
-    "void"    : {"objc_type" : "void", "is_primitive" : True},
-    "bool"    : {"objc_type" : "BOOL", "is_primitive" : True, "to_cpp": "(bool)%(n)s"},
-    "char"    : {"objc_type" : "char", "is_primitive" : True},
-    "int"     : {"objc_type" : "int", "is_primitive" : True, "out_type" : "int*", "out_type_ptr": "%(n)s", "out_type_ref": "*(int*)(%(n)s)"},
-    "long"    : {"objc_type" : "long", "is_primitive" : True},
-    "float"   : {"objc_type" : "float", "is_primitive" : True, "out_type" : "float*", "out_type_ptr": "%(n)s", "out_type_ref": "*(float*)(%(n)s)"},
-    "double"  : {"objc_type" : "double", "is_primitive" : True, "out_type" : "double*", "out_type_ptr": "%(n)s", "out_type_ref": "*(double*)(%(n)s)"},
+    "void"    : {"objc_type" : "void", "is_primitive" : True, "swift_type": "Void"},
+    "bool"    : {"objc_type" : "BOOL", "is_primitive" : True, "to_cpp": "(bool)%(n)s", "swift_type": "Bool"},
+    "char"    : {"objc_type" : "char", "is_primitive" : True, "swift_type": "Int8"},
+    "int"     : {"objc_type" : "int", "is_primitive" : True, "out_type" : "int*", "out_type_ptr": "%(n)s", "out_type_ref": "*(int*)(%(n)s)", "swift_type": "Int32"},
+    "long"    : {"objc_type" : "long", "is_primitive" : True, "swift_type": "Int"},
+    "float"   : {"objc_type" : "float", "is_primitive" : True, "out_type" : "float*", "out_type_ptr": "%(n)s", "out_type_ref": "*(float*)(%(n)s)", "swift_type": "Float"},
+    "double"  : {"objc_type" : "double", "is_primitive" : True, "out_type" : "double*", "out_type_ptr": "%(n)s", "out_type_ref": "*(double*)(%(n)s)", "swift_type": "Double"},
     "size_t"  : {"objc_type" : "size_t", "is_primitive" : True},
-    "int64"   : {"objc_type" : "long", "is_primitive" : True},
-    "string"  : {"objc_type" : "NSString*", "is_primitive" : True, "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]", "cast_to": "std::string"}
+    "int64"   : {"objc_type" : "long", "is_primitive" : True, "swift_type": "Int"},
+    "string"  : {"objc_type" : "NSString*", "is_primitive" : True, "from_cpp": "[NSString stringWithUTF8String:%(n)s.c_str()]", "cast_to": "std::string", "swift_type": "String"}
 }
 
 # Defines a rule to add extra prefixes for names from specific namespaces.
@@ -458,6 +462,7 @@ class FuncInfo(GeneralInfo):
             func_fix_map = func_arg_fix.get(self.classname or module, {}).get(self.signature(self.args), {})
             name_fix_map = func_fix_map.get(self.name, {})
             self.objc_name = name_fix_map.get('name', self.objc_name)
+            self.swift_name = name_fix_map.get('swift_name', self.swift_name)
             for arg in self.args:
                 arg_fix_map = func_fix_map.get(arg.name, {})
                 arg.ctype = arg_fix_map.get('ctype', arg.ctype) #fixing arg type
@@ -529,6 +534,62 @@ def build_objc_method_name(args):
         objc_method_name += a.name + ":"
     return objc_method_name
 
+def get_swift_type(ctype):
+    has_swift_type = "swift_type" in type_dict[ctype]
+    swift_type = type_dict[ctype]["swift_type"] if has_swift_type else type_dict[ctype]["objc_type"]
+    if swift_type[-1:] == "*":
+        swift_type = swift_type[:-1]
+    if not has_swift_type:
+        if "v_type" in type_dict[ctype]:
+            swift_type = "[" + swift_type + "]"
+        elif "v_v_type" in type_dict[ctype]:
+            swift_type = "[[" + swift_type + "]]"
+    return swift_type
+
+def build_swift_extension_decl(name, args, constructor, static, ret_type):
+    extension_decl = ("class " if static else "") + (("func " + name) if not constructor else "convenience init") + "("
+    swift_args = []
+    for a in args:
+        if a.ctype not in type_dict:
+            if not a.defval and a.ctype.endswith("*"):
+                a.defval = 0
+            if a.defval:
+                a.ctype = ''
+                continue
+        if not a.ctype:  # hidden
+            continue
+        swift_type = get_swift_type(a.ctype)
+
+        if "O" in a.out:
+            if type_dict[a.ctype].get("primitive_type", False):
+                swift_type = "UnsafeMutablePointer<" + swift_type + ">"
+            elif "v_type" in type_dict[a.ctype] or "v_v_type" in type_dict[a.ctype] or type_dict[a.ctype].get("primitive_vector", False) or type_dict[a.ctype].get("primitive_vector_vector", False):
+                swift_type = "inout " + swift_type
+
+        swift_args.append(a.name + ': ' + swift_type)
+
+    extension_decl += ", ".join(swift_args) + ")"
+    if ret_type:
+        extension_decl += " -> " + get_swift_type(ret_type)
+    return extension_decl
+
+def extension_arg(a):
+    return a.ctype in type_dict and (type_dict[a.ctype].get("primitive_vector", False) or type_dict[a.ctype].get("primitive_vector_vector", False) or (("v_type" in type_dict[a.ctype] or "v_v_type" in type_dict[a.ctype]) and "O" in a.out))
+
+def extension_tmp_arg(a):
+    if a.ctype in type_dict:
+        if type_dict[a.ctype].get("primitive_vector", False) or type_dict[a.ctype].get("primitive_vector_vector", False):
+            return a.name + "Vector"
+        elif ("v_type" in type_dict[a.ctype] or "v_v_type" in type_dict[a.ctype]) and "O" in a.out:
+            return a.name + "Array"
+    return a.name
+
+def make_swift_extension(args):
+    for a in args:
+        if extension_arg(a):
+            return True
+    return False
+
 def build_swift_signature(args):
     swift_signature = ""
     for a in args:
@@ -543,6 +604,55 @@ def build_swift_signature(args):
         swift_signature += a.name + ":"
     return swift_signature
 
+def build_unrefined_call(name, args, constructor, static, classname, has_ret):
+    swift_refine_call = ("let ret = " if has_ret and not constructor else "") + ((classname + ".") if static else "") + (name if not constructor else "self.init")
+    call_args = []
+    for a in args:
+        if a.ctype not in type_dict:
+            if not a.defval and a.ctype.endswith("*"):
+                a.defval = 0
+            if a.defval:
+                a.ctype = ''
+                continue
+        if not a.ctype:  # hidden
+            continue
+        call_args.append(a.name + ": " + extension_tmp_arg(a))
+    swift_refine_call += "(" + ", ".join(call_args) + ")"
+    return swift_refine_call
+
+def build_swift_logues(args):
+    prologue = []
+    epilogue = []
+    for a in args:
+        if a.ctype not in type_dict:
+            if not a.defval and a.ctype.endswith("*"):
+                a.defval = 0
+            if a.defval:
+                a.ctype = ''
+                continue
+        if not a.ctype:  # hidden
+            continue
+        if a.ctype in type_dict:
+            if type_dict[a.ctype].get("primitive_vector", False):
+                prologue.append("let " + extension_tmp_arg(a) + " = " + type_dict[a.ctype]["objc_type"][:-1] + "(" + a.name + ")")
+                if "O" in a.out:
+                    unsigned = type_dict[a.ctype].get("unsigned", False)
+                    array_prop = "array" if not unsigned else "unsignedArray"
+                    epilogue.append(a.name + ".removeAll()")
+                    epilogue.append(a.name + ".append(contentsOf: " +  extension_tmp_arg(a) + "." + array_prop + ")")
+            elif type_dict[a.ctype].get("primitive_vector_vector", False):
+                if not "O" in a.out:
+                    prologue.append("let " + extension_tmp_arg(a) + " = " + a.name + ".map {" + type_dict[a.ctype]["objc_type"][:-1] + "($0) }")
+                else:
+                    prologue.append("let " + extension_tmp_arg(a) + " = NSMutableArray(array: " + a.name + ".map {" + type_dict[a.ctype]["objc_type"][:-1] + "($0) })")
+                    epilogue.append(a.name + ".removeAll()")
+                    epilogue.append(a.name + ".append(contentsOf: " + extension_tmp_arg(a) + ".map { ($.0 as! " + type_dict[a.ctype]["objc_type"][:-1] + ").array  })")
+            elif ("v_type" in type_dict[a.ctype] or "v_v_type" in type_dict[a.ctype]) and "O" in a.out:
+                prologue.append("let " +  extension_tmp_arg(a) + " = NSMutableArray(array: " + a.name + ")")
+                epilogue.append(a.name + ".removeAll()")
+                epilogue.append(a.name + ".append(contentsOf: " +  extension_tmp_arg(a) + " as! " + get_swift_type(a.ctype) + ")")
+    return prologue, epilogue
+
 def add_method_to_dict(class_name, fi):
     static = fi.static if fi.classname else True
     if not method_dict.has_key((class_name, fi.objc_name)):
@@ -576,6 +686,7 @@ class ObjectiveCWrapperGenerator(object):
         self.classes["Mat"].namespace = "cv"
         self.module = ""
         self.Module = ""
+        self.extension_implementations = None # Swift extensions implementations stream
         self.ported_func_list = []
         self.skipped_func_list = []
         self.def_args_hist = {} # { def_args_cnt : funcs_cnt }
@@ -661,6 +772,8 @@ class ObjectiveCWrapperGenerator(object):
             ctype = normalize_class_name(enumType)
             constinfo = ConstInfo(decl[3][0], namespaces=self.namespaces, enumType=enumType)
             objc_type = enumType.rsplit(".", 1)[-1]
+            if objc_type in enum_ignore_list:
+                return
             if enum_fix.has_key(constinfo.classname):
                 objc_type = enum_fix[constinfo.classname].get(objc_type, objc_type)
             import_module = constinfo.classname if constinfo.classname and constinfo.classname != objc_type else self.Module
@@ -702,6 +815,8 @@ class ObjectiveCWrapperGenerator(object):
 
     def save(self, path, buf):
         global total_files, updated_files
+        if len(buf) == 0:
+            return
         total_files += 1
         if os.path.exists(path):
             with open(path, "rt") as f:
@@ -720,6 +835,9 @@ class ObjectiveCWrapperGenerator(object):
         self.clear()
         self.module = module
         self.Module = module.capitalize()
+        extension_implementations = StringIO() # Swift extensions implementations stream
+        extension_signatures = []
+
         # TODO: support UMat versions of declarations (implement UMat-wrapper for Java)
         parser = hdr_parser.CppHeaderParser(generate_umat_decls=False)
 
@@ -756,11 +874,13 @@ class ObjectiveCWrapperGenerator(object):
         logging.info("\n\n===== Generating... =====")
         package_path = os.path.join(output_objc_path, module)
         mkdir_p(package_path)
+        extension_file = "%s/%s/%sExt.swift" % (output_objc_path, module, self.Module)
+
         for ci in self.classes.values():
             if ci.name == "Mat":
                 continue
             ci.initCodeStreams(self.Module)
-            self.gen_class(ci, self.module)
+            self.gen_class(ci, self.module, extension_implementations, extension_signatures)
             classObjcHeaderCode = ci.generateObjcHeaderCode(self.module, self.Module, ci.objc_name)
             header_file = "%s/%s/%s.h" % (output_objc_path, module, ci.objc_name)
             self.save(header_file, classObjcHeaderCode)
@@ -768,6 +888,8 @@ class ObjectiveCWrapperGenerator(object):
             classObjcBodyCode = ci.generateObjcBodyCode(self.module, self.Module)
             self.save("%s/%s/%s.mm" % (output_objc_path, module, ci.objc_name), classObjcBodyCode)
             ci.cleanupCodeStreams()
+        self.save(extension_file, extension_implementations.getvalue())
+        extension_implementations.close()
         self.save(os.path.join(output_path, module+".txt"), self.makeReport())
 
     def makeReport(self):
@@ -812,7 +934,7 @@ class ObjectiveCWrapperGenerator(object):
             epilogue.append("CV2OBJC_CUSTOM(" + vector_full_type + ", " + objc_type[:-1] + ", " + vector_name + ", " + array_name + ", " + unconv_macro + ");")
             epilogue.append("#undef " + unconv_macro)
 
-    def gen_func(self, ci, fi):
+    def gen_func(self, ci, fi, extension_implementations, extension_signatures):
         logging.info("%s", fi)
         method_declarations = ci.method_declarations
         method_implementations = ci.method_implementations
@@ -904,6 +1026,7 @@ class ObjectiveCWrapperGenerator(object):
             # calculate method signature to check for uniqueness
             objc_args = build_objc_args(args)
             objc_signature = fi.signature(args)
+            swift_ext = make_swift_extension(args)
             logging.info("Objective-C: " + objc_signature)
 
             if objc_signature in objc_signatures:
@@ -1034,6 +1157,32 @@ class ObjectiveCWrapperGenerator(object):
                     tail = tail
                 )
             )
+
+            if swift_ext:
+                prototype = build_swift_extension_decl(fi.swift_name, args, constructor, static, ret_type)
+                if not (ci.name, prototype) in extension_signatures and not (ci.base, prototype) in extension_signatures:
+                    (pro, epi) = build_swift_logues(args)
+                    extension_implementations.write( Template(
+"""public extension $classname {
+    $deprecation_decl$prototype {
+$prologue
+$unrefined_call$epilogue$ret
+    }
+}
+
+"""
+                        ).substitute(
+                            classname = ci.name,
+                            deprecation_decl = "@available(*, deprecated)\n    " if fi.deprecated else "",
+                            prototype = prototype,
+                            prologue = "        " + "\n        ".join(pro),
+                            unrefined_call = "        " + build_unrefined_call(fi.swift_name, args, constructor, static, ci.name, ret_type is not None and ret_type != "void"),
+                            epilogue = "\n        " + "\n        ".join(epi) if len(epi) > 0 else "",
+                            ret = "\n        return ret" if ret_type is not None and ret_type != "void" and not constructor else ""
+                        )
+                    )
+                extension_signatures.append((ci.name, prototype))
+
             # adding method signature to dictionary
             objc_signatures.append(objc_signature)
 
@@ -1043,7 +1192,7 @@ class ObjectiveCWrapperGenerator(object):
             else:
                 break
 
-    def gen_class(self, ci, module):
+    def gen_class(self, ci, module, extension_implementations, extension_signatures):
         logging.info("%s", ci)
         if module in AdditionalImports and (ci.name in AdditionalImports[module] or "*" in AdditionalImports[module]):
             additional_imports = []
@@ -1100,7 +1249,7 @@ typedef NS_ENUM(int, {2}) {{
 
         # methods
         for fi in ci.getAllMethods():
-            self.gen_func(ci, fi)
+            self.gen_func(ci, fi, extension_implementations, extension_signatures)
         # props
         for pi in ci.props:
             ci.method_declarations.write("\n    //\n    // C++: %s %s::%s\n    //\n\n" % (pi.ctype, ci.fullName(isCPP=True), pi.name))
@@ -1412,6 +1561,7 @@ if __name__ == "__main__":
             with open(gendict_fname) as f:
                 gen_type_dict = json.load(f)
             class_ignore_list += gen_type_dict.get("class_ignore_list", [])
+            enum_ignore_list += gen_type_dict.get("enum_ignore_list", [])
             const_ignore_list += gen_type_dict.get("const_ignore_list", [])
             const_private_list += gen_type_dict.get("const_private_list", [])
             missing_consts.update(gen_type_dict.get("missing_consts", {}))
index 8712fd1..71c383e 100644 (file)
@@ -155,11 +155,11 @@ open class OpenCVTestCase: XCTestCase {
         XCTAssertEqual(expected.val[3] as! Double, actual.val[3] as! Double, accuracy:eps, msg, file:file, line:line)
     }
 
-    func assertArrayEquals(_ expected:[NSNumber], _ actual:[NSNumber], _ eps: Double, file: StaticString = #file, line: UInt = #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] as! Double, actual[i] as! Double, accuracy:eps, file:file, line:line)
+            XCTAssertEqual(expected[i], actual[i], accuracy:eps, file:file, line:line)
         }
     }
 
index 82c34ab..216b2b1 100644 (file)
@@ -15,7 +15,7 @@ public class ColorBlobDetector {
     // Color radius for range checking in HSV color space
     var colorRadius = Scalar(25.0, 50.0, 50.0, 0.0)
     let spectrum = Mat()
-    let contours = NSMutableArray()
+    var contours = [[Point]]()
 
     // Cache
     let pyrDownMat = Mat()
@@ -50,25 +50,25 @@ public class ColorBlobDetector {
         Core.inRange(src: hsvMat, lowerb: lowerBound, upperb: upperBound, dst: mask)
         Imgproc.dilate(src: mask, dst: dilatedMask, kernel: Mat())
 
-        let contoursTmp = NSMutableArray()
+        var contoursTmp = [[Point]]()
 
-        Imgproc.findContours(image: dilatedMask, contours: contoursTmp, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
+        Imgproc.findContours(image: dilatedMask, contours: &contoursTmp, hierarchy: hierarchy, mode: .RETR_EXTERNAL, method: .CHAIN_APPROX_SIMPLE)
 
         // Find max contour area
         var maxArea = 0.0
         for contour in contoursTmp {
-            let contourMat = MatOfPoint(array: (contour as! NSMutableArray) as! [Point])
+            let contourMat = MatOfPoint(array: contour)
             let area = Imgproc.contourArea(contour: contourMat)
             maxArea = max(area, maxArea)
         }
 
         // Filter contours by area and resize to fit the original image size
-        contours.removeAllObjects()
+        contours.removeAll()
         for contour in contoursTmp {
-            let contourMat = MatOfPoint(array: (contour as! NSMutableArray) as! [Point])
+            let contourMat = MatOfPoint(array: contour)
             if (Imgproc.contourArea(contour: contourMat) > ColorBlobDetector.minContourArea * maxArea) {
                 Core.multiply(src1: contourMat, srcScalar: Scalar(4.0,4.0), dst: contourMat)
-                contours.add(NSMutableArray(array: contourMat.toArray()))
+                contours.append(contourMat.toArray())
             }
         }
     }
index 2fc6415..d33e9e5 100644 (file)
@@ -62,12 +62,14 @@ class ViewController: UIViewController, CvVideoCameraDelegate2 {
             }
         }
 
-        let faces = NSMutableArray()
+        var faces = [Rect]()
 
-        swiftDetector.detectMultiScale(image: gray, objects: faces, scaleFactor: 1.1, minNeighbors: Int32(2), flags: Int32(2), minSize: Size(width: absoluteFaceSize, height: absoluteFaceSize), maxSize: Size())
-        //nativeDetector!.detect(gray, faces: faces)
+        swiftDetector.detectMultiScale(image: gray, objects: &faces, scaleFactor: 1.1, minNeighbors: Int32(2), flags: Int32(2), minSize: Size(width: absoluteFaceSize, height: absoluteFaceSize), maxSize: Size())
+        //let facesArray = NSMutableArray()
+        //nativeDetector!.detect(gray, faces: facesArray)
+        //faces.append(contentsOf: facesArray)
 
-        for face in faces as! [Rect] {
+        for face in faces {
             if orientation == .landscapeLeft {
                 face.rotateClockwise(parentHeight: gray.rows())
             } else if orientation == .landscapeRight {