Search code examples
iosswiftcidetector

Detecting text orientation


I am able to draw rectangles around text with the CIDetector (Using CIDetectorTypeText), but I can't find a way to detect text orientation. Does anyone know how to detect text orientation with Swift?


Solution

  • This will print out the recognized text orientations.

    guard let image = CIImage(image: imageView.image!) else { return }
    
    let detector = CIDetector(ofType: CIDetectorTypeText, context: nil, options: [
        CIDetectorAccuracy: CIDetectorAccuracyHigh
    ])
    
    let orientations = [Int](1..<9).flatMap {
        detector?.features(in: image, options: [
            CIDetectorImageOrientation: $0
        ]).count ?? 0 > 0 ? $0 : nil
    }
    
    if orientations.filter({ $0 < 5 }).count == 4 {
        print("text has horizontal orientation")
    } else if orientations.filter({ $0 > 4 }).count == 4 {
        print("text has vertical orientation")
    } else {
        print("text has mixed orientation")
    }