Open1

OpenCVのSwiftWrapper記法メモ

izmizm

最新のOpenCVをiOSアプリで使いたい! opencv2.xcframework を自分でビルドする
https://dev.classmethod.jp/articles/build-opencv2-xcframework-manually/

を参考に opencv2.xcframework を作った後、Swiftから使う時のチートシート

https://github.com/CH3COOH/Samples/blob/master/SampleOpenCVManual/OpenCVSample/ImageProcessor.swift

UIImage↔︎cv.Matの相互変換

 static func grayscale(image: UIImage?) -> UIImage? {
        guard let image = image else {
            return nil
        }

        let mat = Mat(uiImage: image)
        Imgproc.cvtColor(
            src: mat,
            dst: mat,
            code: ColorConversionCodes.COLOR_RGB2GRAY
        )
        return mat.toUIImage()
    }

Matにfloatを詰めるやつ

 func prepareObjectPoints(boardSize: CGSize, squareSize: CGFloat) -> Mat {
        var objectPoints: [Float] = []
        
        // Generate 3D points for the checkerboard corners
        for i in 0..<Int(boardSize.height) {
            for j in 0..<Int(boardSize.width) {
                objectPoints.append(Float(j) * Float(squareSize))
                objectPoints.append(Float(i) * Float(squareSize))
                objectPoints.append(0.0)  // Z-coordinate is always 0 for a flat checkerboard
            }
        }
        
        
        // Convert [Float] to Data
        let data = Data(buffer: UnsafeBufferPointer(start: &objectPoints, count: objectPoints.count))
        
        // Initialize Mat object with rows, cols, type, and NSData
        let matObjectPoints = Mat(rows: Int32(objectPoints.count / 3), cols: 3, type: CvType.CV_32FC1, data: data)
        
        return matObjectPoints
    }

Matの中身をstringで取り出すやつ( 単純にdebug目的なら mat.dump()でlog出力できます )

    func matToString(mat: Mat) -> String {
        var description = "Mat: \(mat.rows())x\(mat.cols()), Type: \(mat.type())\n"

        for row in 0..<Int(mat.rows()) {
            for col in 0..<Int(mat.cols()) {
                // Float型のデータを取得する場合
                let element: Float = mat.at(row: Int32(row), col: Int32(col)).v
                description += "\(element) "
            }
            description += "\n"
        }
        return description
    }