SPB Git

Repository Public License

FocusAnalysis.swift 7.9 KB 172 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Sources/ORIXImaging/Monitoring/FocusAnalysis.swift10// Description      : CPU focus analysis: Laplacian response of the luma plane.11//                    Gives a sharpness score (variance of the Laplacian) and12//                    the peaking mask used as the reference for the Metal13//                    overlay. An estimate of local detail, not a guarantee of14//                    focus.15// Module           : ORIXImaging16// Repository       : https://git.spboucher.ai/orix-camera17// Project Website  : https://www.orixlab.dev18// Created          : 2026-11-2119// Last Modified    : 2026-11-2120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : Proprietary, all rights reserved (see license file)86// License File     : LICENSE87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Accelerate95import CoreVideo96import Foundation9798public struct FocusMetrics: Sendable, Equatable {99    /// Variance of the Laplacian on the analysis plane (8-bit code values squared). Higher = more fine detail.100    public var sharpness: Double101    /// Fraction of pixels whose gradient magnitude exceeds the peaking threshold.102    public var peakingCoverage: Double103    public init(sharpness: Double, peakingCoverage: Double) {104        self.sharpness = sharpness; self.peakingCoverage = peakingCoverage105    }106}107108public enum FocusAnalyzer {109    /// Peaking threshold on the gradient magnitude (0…1 of full scale) for a sensitivity in 0…1.110    /// Sensitivity 0 marks only very strong edges (0.30); sensitivity 1 marks fine texture (0.04).111    public static func threshold(sensitivity: Double) -> Float {112        let s = Float(min(max(sensitivity, 0), 1))113        return 0.30 - s * 0.26114    }115116    /// Sobel gradient magnitude per pixel, normalized to 0…1 (|gx| + |gy|) / (4 · 255), borders set to 0.117    public static func gradientMagnitude(_ plane: LumaPlane) -> [Float] {118        let w = plane.width, h = plane.height119        var out = [Float](repeating: 0, count: w * h)120        guard w > 2, h > 2 else { return out }121        plane.pixels.withUnsafeBufferPointer { p in122            for y in 1..<(h - 1) {123                let a = (y - 1) * w, b = y * w, c = (y + 1) * w124                for x in 1..<(w - 1) {125                    let tl = Float(p[a + x - 1]), tc = Float(p[a + x]), tr = Float(p[a + x + 1])126                    let ml = Float(p[b + x - 1]), mr = Float(p[b + x + 1])127                    let bl = Float(p[c + x - 1]), bc = Float(p[c + x]), br = Float(p[c + x + 1])128                    let gx = (tr + 2 * mr + br) - (tl + 2 * ml + bl)129                    let gy = (bl + 2 * bc + br) - (tl + 2 * tc + tr)130                    out[b + x] = min(1, (abs(gx) + abs(gy)) / (4 * 255))131                }132            }133        }134        return out135    }136137    /// Boolean peaking mask: true where the gradient magnitude exceeds the threshold for `sensitivity`.138    public static func peakingMask(_ plane: LumaPlane, sensitivity: Double) -> [Bool] {139        let t = threshold(sensitivity: sensitivity)140        return gradientMagnitude(plane).map { $0 > t }141    }142143    public static func analyze(_ plane: LumaPlane, sensitivity: Double = 0.5) -> FocusMetrics {144        let w = plane.width, h = plane.height145        guard w > 2, h > 2 else { return FocusMetrics(sharpness: 0, peakingCoverage: 0) }146        var source = [Float](repeating: 0, count: w * h)147        vDSP_vfltu8(plane.pixels, 1, &source, 1, vDSP_Length(w * h))148        var laplacian = [Float](repeating: 0, count: w * h)149        let kernel: [Float] = [0, 1, 0, 1, -4, 1, 0, 1, 0]150        source.withUnsafeMutableBytes { src in151            laplacian.withUnsafeMutableBytes { dst in152                var s = vImage_Buffer(data: src.baseAddress, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: w * 4)153                var d = vImage_Buffer(data: dst.baseAddress, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: w * 4)154                vImageConvolve_PlanarF(&s, &d, nil, 0, 0, kernel, 3, 3, 0, vImage_Flags(kvImageEdgeExtend))155            }156        }157        var mean: Float = 0, meanSquare: Float = 0158        vDSP_meanv(laplacian, 1, &mean, vDSP_Length(laplacian.count))159        vDSP_measqv(laplacian, 1, &meanSquare, vDSP_Length(laplacian.count))160        let variance = Double(meanSquare - mean * mean)161        let t = threshold(sensitivity: sensitivity)162        let magnitude = gradientMagnitude(plane)163        let covered = magnitude.reduce(0) { $0 + ($1 > t ? 1 : 0) }164        return FocusMetrics(sharpness: max(0, variance), peakingCoverage: Double(covered) / Double(w * h))165    }166167    public static func analyze(_ pixelBuffer: CVPixelBuffer, sensitivity: Double = 0.5, maxDimension: Int = 640) -> FocusMetrics? {168        guard let plane = LumaPlane(pixelBuffer: pixelBuffer, maxDimension: maxDimension) else { return nil }169        return analyze(plane, sensitivity: sensitivity)170    }171}172
Files main
Menu

Theme