How to change CIDetector orientation?

孤人 提交于 2019-12-22 08:06:08

问题


So I am trying to make a text detector using CIDetector in Swift. When I point my phone at a piece of text, it doesn't detect it. However, if I turn my phone to the side, it works and detects the text. How can I change it so that it detects text at the correct camera orientation? Here is my code:

Prepare text detector function:

func prepareTextDetector() -> CIDetector {
    let options: [String: AnyObject] = [CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorAspectRatio: 1.0]
    return CIDetector(ofType: CIDetectorTypeText, context: nil, options: options)
}

Text detection function:

func performTextDetection(image: CIImage) -> CIImage? {
    if let detector = detector {
        // Get the detections
        let features = detector.featuresInImage(image)
        for feature in features as! [CITextFeature] {
            resultImage = drawHighlightOverlayForPoints(image, topLeft: feature.topLeft, topRight: feature.topRight,
                                                        bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)                
            imagex = cropBusinessCardForPoints(resultImage!, topLeft: feature.topLeft, topRight: feature.topRight, bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)
        }
    }
    return resultImage
}

It works when oriented like the left one, but not for the right one:


回答1:


You have to use CIDetectorImageOrientation, as Apple stated in its CITextFeature documentation:

[...] use the CIDetectorImageOrientation option to specify the desired orientation for finding upright text.

For example, you need to do

let features = detector.featuresInImage(image, options: [CIDetectorImageOrientation : 1]) 

where 1 is the exif number and depends on the orientation, which can be computed like

func imageOrientationToExif(image: UIImage) -> uint {
    switch image.imageOrientation {
    case UIImageOrientation.Up:
        return 1;
    case UIImageOrientation.Down:
        return 3;
    case UIImageOrientation.Left:
        return 8;
    case UIImageOrientation.Right:
        return 6;
    case UIImageOrientation.UpMirrored:
        return 2;
    case UIImageOrientation.DownMirrored:
        return 4;
    case UIImageOrientation.LeftMirrored:
        return 5;
    case UIImageOrientation.RightMirrored:
        return 7;
    }
}


来源:https://stackoverflow.com/questions/36199572/how-to-change-cidetector-orientation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!