SPB Git

Repository Public

PerspectiveCorrector.swift 7.8 KB 149 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Engines/ImageProcessing/PerspectiveCorrector.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CoreGraphics42import CoreImage43import Foundation44import simd4546struct CorrectedCard: @unchecked Sendable {47    /// Flattened, deskewed card cropped to its edges.48    var image: CGImage49    var format: CardFormat50    /// Width / height of the physical card as estimated from the photograph,51    /// before any snap to a standard format.52    var measuredAspect: Double53}5455/// Perspective correction, deskew and crop in one step (`CIPerspectiveCorrection`).56enum PerspectiveCorrector {57    static let maximumLongEdge = 240058    /// A measured ratio this close to the format the owner announced (by choosing59    /// the kind of card) is taken to be that format.60    static let expectedFormatTolerance = 0.0861    /// Focal length assumed when the photograph does not reveal it, in units of62    /// the longer image side (iPhone main camera, uncropped).63    static let defaultFocal = 0.756465    /// True width / height of a rectangle seen in perspective.66    ///67    /// Opposite edges of a tilted card have different apparent lengths, so68    /// averaging them is biased. This recovers the ratio from the projective69    /// geometry of the four corners, assuming a pinhole camera with square70    /// pixels and its principal point at the image centre (Zhang & He,71    /// "Whiteboard scanning and image enhancement", 2007). Seen straight on,72    /// the result reduces to the ratio of the edge lengths.73    static func estimatedAspect(of quad: CardQuad, imageSize: CGSize) -> Double {74        let fallback = quad.apparentAspect(imageSize: imageSize)75        let width = Double(imageSize.width), height = Double(imageSize.height)76        let scale = max(width, height)77        guard scale > 0 else { return fallback }78        // Homogeneous corners, centred on the principal point and scaled to ~1.79        func h(_ p: CGPoint) -> SIMD3<Double> {80            SIMD3((Double(p.x) * width - width / 2) / scale, (Double(p.y) * height - height / 2) / scale, 1)81        }82        let m1 = h(quad.topLeft), m2 = h(quad.topRight), m3 = h(quad.bottomLeft), m4 = h(quad.bottomRight)83        let d2 = simd_dot(simd_cross(m2, m4), m3), d3 = simd_dot(simd_cross(m3, m4), m2)84        guard abs(d2) > 1e-12, abs(d3) > 1e-12 else { return fallback }85        let k2 = simd_dot(simd_cross(m1, m4), m3) / d2, k3 = simd_dot(simd_cross(m1, m4), m2) / d386        let n2 = k2 * m2 - m1, n3 = k3 * m3 - m187        // Two vanishing points give the focal length. When a pair of edges is88        // (nearly) parallel in the image, n.z of that pair is ~0 and the focal89        // length is not observable: the field of view of an iPhone main camera90        // (26 mm equivalent, f ≈ 0.75 × the long side) is assumed instead.91        var f2 = defaultFocal * defaultFocal92        if abs(n2.z) > 0.03, abs(n3.z) > 0.03 {93            let estimate = -(n2.x * n3.x + n2.y * n3.y) / (n2.z * n3.z)94            if estimate.isFinite, estimate > 0.45 * 0.45, estimate < 3 * 3 { f2 = estimate }95        }96        let ratio = sqrt(((n2.x * n2.x + n2.y * n2.y) / f2 + n2.z * n2.z) / ((n3.x * n3.x + n3.y * n3.y) / f2 + n3.z * n3.z))97        guard ratio.isFinite, ratio > 0.2, ratio < 5, abs(ratio - fallback) / fallback < 0.35 else { return fallback }98        return ratio99    }100101    /// Format decision: a standard format when the measured ratio is within 4 %102    /// of it (`CardFormat.matching`), else the announced format when the ratio is103    /// within `expectedFormatTolerance` of it, else the measured ratio as is.104    static func format(forMeasuredAspect measured: Double, expected: CardFormat?) -> CardFormat {105        let matched = CardFormat.matching(aspect: measured)106        guard case .custom = matched, let expected else { return matched }107        if case .custom = expected { return matched }108        return abs(expected.aspectRatio - measured) / expected.aspectRatio <= expectedFormatTolerance ? expected : matched109    }110111    /// - Parameters:112    ///   - quad: card corners, normalised, origin top-left.113    ///   - expectedFormat: the format of the kind of card being scanned, if known.114    /// The card is rendered at its estimated true proportions; it is resized to115    /// an exact standard ratio only under the rule of `format(forMeasuredAspect:expected:)`.116    static func correct(_ image: CGImage, quad: CardQuad, expectedFormat: CardFormat? = nil,117                        maximumLongEdge: Int = maximumLongEdge) -> CorrectedCard? {118        let input = CIImage(cgImage: image)119        let w = CGFloat(image.width), h = CGFloat(image.height)120        func point(_ p: CGPoint) -> CIVector { CIVector(x: p.x * w, y: (1 - p.y) * h) }121        let quad = quad.clamped()122        guard quad.isConvex, quad.area > 0.0005 else { return nil }123        let corrected = input.applyingFilter("CIPerspectiveCorrection", parameters: [124            "inputTopLeft": point(quad.topLeft), "inputTopRight": point(quad.topRight),125            "inputBottomRight": point(quad.bottomRight), "inputBottomLeft": point(quad.bottomLeft)])126        let extent = corrected.extent127        guard !extent.isInfinite, extent.width >= 8, extent.height >= 8 else { return nil }128        let measured = estimatedAspect(of: quad, imageSize: CGSize(width: w, height: h))129        let format = format(forMeasuredAspect: measured, expected: expectedFormat)130        let targetAspect: Double = { if case .custom = format { return measured } else { return format.aspectRatio } }()131132        let longEdge = min(CGFloat(maximumLongEdge), max(extent.width, extent.height))133        let targetWidth: CGFloat, targetHeight: CGFloat134        if targetAspect >= 1 {135            targetWidth = longEdge.rounded()136            targetHeight = (longEdge / CGFloat(targetAspect)).rounded()137        } else {138            targetHeight = longEdge.rounded()139            targetWidth = (longEdge * CGFloat(targetAspect)).rounded()140        }141        let scaled = corrected142            .transformed(by: CGAffineTransform(translationX: -extent.minX, y: -extent.minY))143            .transformed(by: CGAffineTransform(scaleX: targetWidth / extent.width, y: targetHeight / extent.height))144            .cropped(to: CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight))145        guard let output = ImagePipeline.render(scaled) else { return nil }146        return CorrectedCard(image: output, format: format, measuredAspect: measured)147    }148}149
Files main
Menu

Theme