Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/CardDetector.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 CoreVideo43import ImageIO44import Vision4546/// Finds the outline of a card with Vision's rectangle detector, constrained to47/// the proportions of real cards and documents. Runs entirely on the device.48enum CardDetector {49 /// Short side / long side accepted: from long loyalty tags to near-square50 /// badges. ID-1 is 0.631, ID-3 is 0.704.51 static let aspectRange: ClosedRange<Float> = 0.45...0.9552 /// Smallest card, as a fraction of the shorter image side.53 static let minimumSize: Float = 0.25455 private static func makeRequest() -> VNDetectRectanglesRequest {56 let request = VNDetectRectanglesRequest()57 request.minimumAspectRatio = aspectRange.lowerBound58 request.maximumAspectRatio = aspectRange.upperBound59 request.minimumSize = minimumSize60 request.quadratureTolerance = 2561 request.minimumConfidence = 0.562 request.maximumObservations = 663 return request64 }6566 private static func best(_ observations: [VNRectangleObservation]?) -> DetectedCard? {67 let cards = (observations ?? []).map { observation -> DetectedCard in68 // Vision: origin bottom-left. Ours: origin top-left.69 func flip(_ p: CGPoint) -> CGPoint { CGPoint(x: p.x, y: 1 - p.y) }70 let quad = CardQuad(unordered: [flip(observation.topLeft), flip(observation.topRight),71 flip(observation.bottomRight), flip(observation.bottomLeft)])72 return DetectedCard(quad: quad, confidence: observation.confidence)73 }.filter { $0.quad.isConvex }74 // The card is the largest plausible rectangle in the frame.75 return cards.max { $0.quad.area * CGFloat($0.confidence) < $1.quad.area * CGFloat($1.confidence) }76 }7778 static func detect(in image: CGImage) -> DetectedCard? {79 let request = makeRequest()80 let handler = VNImageRequestHandler(cgImage: image, options: [:])81 guard (try? handler.perform([request])) != nil else { return nil }82 return best(request.results)83 }8485 /// Detection for stills, in three passes: find the card, look again inside a86 /// crop around it (Vision works at a fixed internal resolution, so a card87 /// that fills only part of the photograph is located more precisely the88 /// second time), then pull each side onto the true border (`EdgeRefiner`).89 static func detectRefined(in image: CGImage) -> DetectedCard? {90 guard var card = detectZoomed(in: image) else { return nil }91 card.quad = EdgeRefiner.refine(card.quad, in: image)92 return card93 }9495 private static func detectZoomed(in image: CGImage) -> DetectedCard? {96 guard let coarse = detect(in: image) else { return nil }97 let w = CGFloat(image.width), h = CGFloat(image.height)98 let box = coarse.quad.boundingBox99 let margin = max(box.width, box.height) * 0.12100 let region = box.insetBy(dx: -margin, dy: -margin).intersection(CGRect(x: 0, y: 0, width: 1, height: 1))101 let pixels = CGRect(x: region.minX * w, y: region.minY * h, width: region.width * w, height: region.height * h).integral102 // Nothing to gain when the card already fills the frame.103 guard pixels.width < w * 0.85 || pixels.height < h * 0.85, let crop = image.cropping(to: pixels),104 let fine = detect(in: crop) else { return coarse }105 func lift(_ p: CGPoint) -> CGPoint {106 CGPoint(x: (pixels.minX + p.x * pixels.width) / w, y: (pixels.minY + p.y * pixels.height) / h)107 }108 let refined = CardQuad(topLeft: lift(fine.quad.topLeft), topRight: lift(fine.quad.topRight),109 bottomRight: lift(fine.quad.bottomRight), bottomLeft: lift(fine.quad.bottomLeft))110 // The second pass must be looking at the same object.111 guard refined.maxCornerDistance(to: coarse.quad) < 0.06, refined.area > coarse.quad.area * 0.8 else { return coarse }112 return DetectedCard(quad: refined, confidence: max(coarse.confidence, fine.confidence))113 }114115 /// Live video frame. The buffer must already be upright (the camera sets the116 /// connection rotation), otherwise pass its orientation.117 static func detect(in pixelBuffer: CVPixelBuffer, orientation: CGImagePropertyOrientation = .up) -> DetectedCard? {118 let request = makeRequest()119 let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: orientation, options: [:])120 guard (try? handler.perform([request])) != nil else { return nil }121 return best(request.results)122 }123}124