Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/QualityAnalyzer.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 CoreVideo44import Foundation4546/// One reason a frame is not good enough to capture yet.47enum QualityIssue: String, CaseIterable, Sendable {48 case noCard, tooFar, tooDark, glare, blurry, unstable4950 /// Short instruction shown under the viewfinder.51 var hint: String {52 switch self {53 case .noCard: "Place the card inside the frame"54 case .tooFar: "Move closer"55 case .tooDark: "More light needed"56 case .glare: "Too much glare — tilt the card"57 case .blurry: "Hold still to focus"58 case .unstable: "Hold steady"59 }60 }61}6263struct QualityReport: Equatable, Sendable {64 /// Variance of the Laplacian of the card area (higher is sharper).65 var sharpness: Double66 /// Fraction of the card area that is blown out to white.67 var glareFraction: Double68 /// Mean luminance of the whole frame, 0…1.69 var luminance: Double70 /// Fraction of the frame covered by the card's bounding box.71 var coverage: Double72 /// Ordered by what the owner should fix first.73 var issues: [QualityIssue]7475 var isAcceptable: Bool { issues.isEmpty }76 var hint: String { issues.first?.hint ?? "Ready" }77}7879/// SP SmartScan quality gates: sharpness, glare, light and distance. Measured on80/// a small in-memory sample of the frame; nothing is kept.81enum QualityAnalyzer {82 struct Thresholds: Sendable {83 var minimumSharpness = 55.084 var maximumGlare = 0.0685 var minimumLuminance = 0.1186 var minimumCoverage = 0.1487 }8889 static func analyze(_ image: CGImage, quad: CardQuad?, thresholds: Thresholds = Thresholds()) -> QualityReport {90 analyze(CIImage(cgImage: image), quad: quad, thresholds: thresholds)91 }9293 static func analyze(_ pixelBuffer: CVPixelBuffer, quad: CardQuad?, thresholds: Thresholds = Thresholds()) -> QualityReport {94 analyze(CIImage(cvPixelBuffer: pixelBuffer), quad: quad, thresholds: thresholds)95 }9697 static func analyze(_ image: CIImage, quad: CardQuad?, thresholds: Thresholds = Thresholds()) -> QualityReport {98 let extent = image.extent99 let frameLuminance: Double = {100 guard let frame = SampledBitmap(image, targetWidth: 96) else { return 0 }101 let luma = frame.luminance102 return Double(luma.reduce(0, +)) / Double(max(luma.count, 1)) / 255103 }()104 guard let quad else {105 var issues: [QualityIssue] = [.noCard]106 if frameLuminance < thresholds.minimumLuminance { issues.insert(.tooDark, at: 0) }107 return QualityReport(sharpness: 0, glareFraction: 0, luminance: frameLuminance, coverage: 0, issues: issues)108 }109 let box = quad.boundingBox110 // Normalised top-left → Core Image (bottom-left, pixels).111 let region = CGRect(x: extent.minX + box.minX * extent.width, y: extent.minY + (1 - box.maxY) * extent.height,112 width: box.width * extent.width, height: box.height * extent.height)113 let coverage = Double(box.width * box.height)114 var sharpness = 0.0, glare = 0.0115 if let sample = SampledBitmap(image, region: region, targetWidth: 480) {116 sharpness = laplacianVariance(sample)117 glare = saturatedFraction(sample)118 }119 var issues: [QualityIssue] = []120 if frameLuminance < thresholds.minimumLuminance { issues.append(.tooDark) }121 if coverage < thresholds.minimumCoverage { issues.append(.tooFar) }122 if glare > thresholds.maximumGlare { issues.append(.glare) }123 if sharpness < thresholds.minimumSharpness { issues.append(.blurry) }124 return QualityReport(sharpness: sharpness, glareFraction: glare, luminance: frameLuminance, coverage: coverage, issues: issues)125 }126127 /// Variance of a 4-neighbour Laplacian over the luminance.128 static func laplacianVariance(_ bitmap: SampledBitmap) -> Double {129 let w = bitmap.width, h = bitmap.height130 guard w > 2, h > 2 else { return 0 }131 let luma = bitmap.luminance132 var sum = 0.0, sumSquares = 0.0133 var count = 0134 for y in 1..<(h - 1) {135 for x in 1..<(w - 1) {136 let i = y * w + x137 let value = Double(luma[i - 1] + luma[i + 1] + luma[i - w] + luma[i + w] - 4 * luma[i])138 sum += value139 sumSquares += value * value140 count += 1141 }142 }143 let mean = sum / Double(count)144 return sumSquares / Double(count) - mean * mean145 }146147 /// Fraction of pixels whose three channels are all clipped.148 static func saturatedFraction(_ bitmap: SampledBitmap) -> Double {149 var clipped = 0150 let total = bitmap.width * bitmap.height151 for i in 0..<total where bitmap.rgba[i * 4] >= 250 && bitmap.rgba[i * 4 + 1] >= 250 && bitmap.rgba[i * 4 + 2] >= 250 {152 clipped += 1153 }154 return Double(clipped) / Double(max(total, 1))155 }156}157