OGeek|极客世界-中国程序员成长平台

标题: ios - 是否可以在 IOS swift 中从更大的图像中检测出矩形图像? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:30
标题: ios - 是否可以在 IOS swift 中从更大的图像中检测出矩形图像?

例如,我有一张名片放在 table 上,我只想扫描名片。类似于二维码扫描仪,我想将名片图像扫描到应用程序中。

我听说过 OpenCV,但不确定如何将它与 swift 3 一起使用。有什么建议可以引导我朝着正确的方向前进吗?



Best Answer-推荐答案


是的!使用 CoreImageCIDetector 你可以检测到 rectangle 。这是您最有可能正在寻找的代码(Swift 3)!

func performRectangleDetection(image: CIImage) -> CIImage? {
        var resultImage: CIImage?
        resultImage = image
        let detector = CIDetector(ofType: CIDetectorTypeRectangle, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorAspectRatio: 1.6, CIDetectorMaxFeatureCount: 10] )!

        // Get the detections
        var halfPerimiterValue = 0.0 as Float;
        let features = detector.features(in: image)
        print("feature \(features.count)")
        for feature in features as! [CIRectangleFeature] {

            let p1 = feature.topLeft
            let p2 = feature.topRight
            let width = hypotf(Float(p1.x - p2.x), Float(p1.y - p2.y));
            //NSLog(@"xaxis    %@", @(p1.x));
            //NSLog(@"yaxis    %@", @(p1.y));
            let p3 = feature.topLeft
            let p4 = feature.bottomLeft
            let height = hypotf(Float(p3.x - p4.x), Float(p3.y - p4.y));
            let currentHalfPerimiterValue = height+width;
            if (halfPerimiterValue < currentHalfPerimiterValue)
            {
                halfPerimiterValue = currentHalfPerimiterValue
                resultImage = cropBusinessCardForPoints(image: image, topLeft: feature.topLeft, topRight: feature.topRight,
                                                        bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)
                print("perimmeter   \(halfPerimiterValue)")
            }

        }

        return resultImage
    }

    func cropBusinessCardForPoints(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {

        var businessCard: CIImage
        businessCard = image.applyingFilter(
            "CIPerspectiveTransformWithExtent",
            withInputParameters: [
                "inputExtent": CIVector(cgRect: image.extent),
                "inputTopLeft": CIVector(cgPoint: topLeft),
                "inputTopRight": CIVector(cgPoint: topRight),
                "inputBottomLeft": CIVector(cgPoint: bottomLeft),
                "inputBottomRight": CIVector(cgPoint: bottomRight)])
        businessCard = image.cropping(to: businessCard.extent)

        return businessCard
    }

调用函数performRectangleDetection,这里cropBusinessCardForPoints是助手。

UIImage/CIImage Conversion .

祝你好运!

仅供引用:使用 CoreML 是最佳选择之一。

关于ios - 是否可以在 IOS swift 中从更大的图像中检测出矩形图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45115145/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4