Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/EdgeRefiner.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 Foundation4445/// Sharpens a detected card outline. Vision's rectangle detector returns corners46/// that sit about one percent outside the real edge; this pass looks, along each47/// side, for the strongest light/dark transition near the proposed edge, fits a48/// straight line through those points and intersects the four lines. The crop49/// then follows the true border of the card instead of a strip of table.50enum EdgeRefiner {51 /// Search distance on each side of the proposed edge, as a fraction of the52 /// longer image side.53 static let searchFraction = 0.02254 static let samplesPerEdge = 3655 /// Smallest luminance step (0…255) accepted as an edge.56 static let minimumContrast: Float = 55758 static func refine(_ quad: CardQuad, in image: CGImage) -> CardQuad {59 let ci = CIImage(cgImage: image)60 let targetWidth = min(image.width, image.width >= image.height ? 1600 : max(2, 1600 * image.width / max(image.height, 1)))61 guard let bitmap = SampledBitmap(ci, targetWidth: targetWidth) else { return quad }62 return refine(quad, luminance: bitmap.luminance, width: bitmap.width, height: bitmap.height)63 }6465 /// - Parameter luminance: row-major luma, first row at the top of the image66 /// (the order `SampledBitmap` produces).67 static func refine(_ quad: CardQuad, luminance: [Float], width: Int, height: Int) -> CardQuad {68 let w = Double(width), h = Double(height)69 func sample(_ x: Double, _ y: Double) -> Float {70 let cx = min(max(x, 0), w - 1.001), cy = min(max(y, 0), h - 1.001)71 let x0 = Int(cx), y0 = Int(cy)72 let fx = Float(cx - Double(x0)), fy = Float(cy - Double(y0))73 let i = y0 * width + x074 let top = luminance[i] * (1 - fx) + luminance[i + 1] * fx75 let bottom = luminance[i + width] * (1 - fx) + luminance[i + width + 1] * fx76 return top * (1 - fy) + bottom * fy77 }78 let points = quad.corners.map { SIMD2(Double($0.x) * w, Double($0.y) * h) }79 let centre = points.reduce(SIMD2<Double>(0, 0), +) / 480 let range = max(w, h) * searchFraction8182 struct Line { var a: SIMD2<Double>; var b: SIMD2<Double> }83 var lines: [Line] = []84 for index in 0..<4 {85 let a = points[index], b = points[(index + 1) % 4]86 let along = b - a87 let length = (along * along).sum().squareRoot()88 guard length > 8 else { return quad }89 let direction = along / length90 var normal = SIMD2(-direction.y, direction.x)91 if ((a + b) / 2 - centre).dot(normal) < 0 { normal = -normal } // outward9293 var ts: [Double] = [], offsets: [Double] = []94 for step in 0..<samplesPerEdge {95 // Stay clear of the corners: real cards have rounded ones.96 let t = 0.14 + 0.72 * Double(step) / Double(samplesPerEdge - 1)97 let p = a + along * t98 var best: Float = 0, bestOffset = 0.099 var s = -range100 while s <= range {101 var outer: Float = 0, inner: Float = 0102 for k in [-2.0, 0.0, 2.0] { // average a little along the edge against noise103 let q = p + direction * k104 outer += sample(q.x + normal.x * (s + 1.5), q.y + normal.y * (s + 1.5))105 inner += sample(q.x + normal.x * (s - 1.5), q.y + normal.y * (s - 1.5))106 }107 let step = abs(outer - inner) / 3108 if step > best { best = step; bestOffset = s }109 s += 0.5110 }111 if best >= minimumContrast, abs(bestOffset) < range - 0.5 {112 ts.append(t)113 offsets.append(bestOffset)114 }115 }116 guard ts.count >= samplesPerEdge / 3, let fit = robustLine(ts, offsets) else {117 lines.append(Line(a: a, b: b)) // no clear edge here: keep the proposal118 continue119 }120 lines.append(Line(a: a + normal * fit.intercept, b: b + normal * (fit.intercept + fit.slope)))121 }122123 func intersection(_ l1: Line, _ l2: Line) -> SIMD2<Double>? {124 let d1 = l1.b - l1.a, d2 = l2.b - l2.a125 let denominator = d1.x * d2.y - d1.y * d2.x126 guard abs(denominator) > 1e-9 else { return nil }127 let t = ((l2.a.x - l1.a.x) * d2.y - (l2.a.y - l1.a.y) * d2.x) / denominator128 return l1.a + d1 * t129 }130 // Corner i is where edge i-1 meets edge i.131 var refined: [CGPoint] = []132 for index in 0..<4 {133 guard let corner = intersection(lines[(index + 3) % 4], lines[index]) else { return quad }134 let moved = corner - points[index]135 guard (moved * moved).sum().squareRoot() <= range * 1.6 else { return quad }136 refined.append(CGPoint(x: corner.x / w, y: corner.y / h))137 }138 let result = CardQuad(topLeft: refined[0], topRight: refined[1], bottomRight: refined[2], bottomLeft: refined[3]).clamped()139 return result.isConvex ? result : quad140 }141142 /// Least-squares line `offset = intercept + slope · t`, refitted once without143 /// the points that sit far from the first fit (text or a logo near the border).144 private static func robustLine(_ ts: [Double], _ offsets: [Double]) -> (intercept: Double, slope: Double)? {145 func fit(_ indices: [Int]) -> (Double, Double)? {146 let n = Double(indices.count)147 guard n >= 4 else { return nil }148 let st = indices.reduce(0) { $0 + ts[$1] }, so = indices.reduce(0) { $0 + offsets[$1] }149 let stt = indices.reduce(0) { $0 + ts[$1] * ts[$1] }, sto = indices.reduce(0) { $0 + ts[$1] * offsets[$1] }150 let denominator = n * stt - st * st151 guard abs(denominator) > 1e-9 else { return nil }152 let slope = (n * sto - st * so) / denominator153 return ((so - slope * st) / n, slope)154 }155 // Start from the median offset: robust against a minority of outliers.156 let sorted = offsets.sorted()157 let median = sorted[sorted.count / 2]158 var inliers = offsets.indices.filter { abs(offsets[$0] - median) <= 6 }159 guard var current = fit(inliers) else { return nil }160 for _ in 0..<2 {161 inliers = offsets.indices.filter { abs(offsets[$0] - (current.0 + current.1 * ts[$0])) <= 1.75 }162 guard let next = fit(inliers) else { break }163 current = next164 }165 guard inliers.count >= max(6, ts.count / 2) else { return nil }166 return (current.0, current.1)167 }168}169170private extension SIMD2 where Scalar == Double {171 func dot(_ other: SIMD2<Double>) -> Double { x * other.x + y * other.y }172}173