Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change CIDetector orientation?

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:

enter image description here

like image 551
Henry P. Avatar asked Mar 13 '23 19:03

Henry P.


1 Answers

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;
    }
}
like image 174
Michael Dorner Avatar answered Mar 28 '23 05:03

Michael Dorner