SPB Git

Repository Public License

ComputationalTests.swift 13.8 KB 288 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : Packages/ORIXCameraKit/Tests/ORIXImagingTests/ComputationalTests.swift10// Description      : Multi-frame engines: accumulation (long exposure, light11//                    trails), motion-aware noise stacking, registration and12//                    exposure fusion, each against a measurable expectation.13// Module           : ORIXImagingTests14// Repository       : https://git.spboucher.ai/orix-camera15// Project Website  : https://www.orixlab.dev16// Created          : 2026-11-2117// Last Modified    : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import CoreGraphics93import CoreVideo94import Foundation95import Testing96@testable import ORIXImaging9798@Suite struct FrameAccumulatorTests {99    @Test func meanOfConstantFramesIsTheirAverage() {100        let accumulator = FrameAccumulator(width: 32, height: 16, mode: .mean)101        accumulator.add(Fixture.solid(100, 0, 40, width: 32, height: 16))102        accumulator.add(Fixture.solid(200, 50, 40, width: 32, height: 16))103        let result = accumulator.result()104        #expect(accumulator.frameCount == 2)105        #expect(abs(result.r[100] - 150.0 / 255) < 1e-5)106        #expect(abs(result.g[100] - 25.0 / 255) < 1e-5)107        #expect(abs(result.b[100] - 40.0 / 255) < 1e-5)108    }109110    @Test func lightenKeepsTheBrightestSample() {111        let accumulator = FrameAccumulator(width: 32, height: 16, mode: .lighten)112        accumulator.add(Fixture.solid(10, 200, 30, width: 32, height: 16))113        accumulator.add(Fixture.solid(90, 20, 30, width: 32, height: 16))114        let result = accumulator.result()115        #expect(abs(result.r[0] - 90.0 / 255) < 1e-5 && abs(result.g[0] - 200.0 / 255) < 1e-5)116    }117118    @Test func rejectsFramesOfAnotherSize() {119        let accumulator = FrameAccumulator(width: 32, height: 16, mode: .mean)120        #expect(!accumulator.add(Fixture.solid(1, 1, 1, width: 16, height: 16)))121        #expect(accumulator.frameCount == 0)122    }123124    @Test func lightTrailsRecordTheWholePathOfAMovingLight() throws {125        let scene = try #require(SyntheticScene(width: 480, height: 270))126        let trails = FrameAccumulator(width: 480, height: 270, mode: .lighten)127        let single = try #require(FloatImage(pixelBuffer: scene.render(time: 0)!))128        for i in 0..<60 { trails.add(try #require(scene.render(time: Double(i) / 15))) }129        let result = trails.result()130        // The lantern orbits (0.25 w, 0.62 h in CoreGraphics coordinates → 0.38 h from the top): after one full turn the131        // lighten stack holds a ring of bright pixels where a single frame holds one dot.132        func bright(_ image: FloatImage) -> Int {133            var n = 0134            for y in 60..<150 { for x in 70..<170 where image.g[y * 480 + x] > 0.8 && image.b[y * 480 + x] > 0.8 { n += 1 } }135            return n136        }137        #expect(bright(result) > bright(single) * 8)138        // Lighten never darkens: every pixel is at least the first frame's value.139        var darker = 0140        for i in 0..<single.count where result.g[i] + 1e-4 < single.g[i] { darker += 1 }141        #expect(darker == 0)142    }143144    @Test func meanStackBlursMotionAndPreservesStaticAreas() throws {145        let scene = try #require(SyntheticScene(width: 480, height: 270))146        let long = FrameAccumulator(width: 480, height: 270, mode: .mean)147        for i in 0..<40 { long.add(try #require(scene.render(time: Double(i) / 10))) }148        let result = long.result()149        let single = try #require(FloatImage(pixelBuffer: scene.render(time: 0)!))150        // Static region (grey step wedge, bottom centre) is unchanged.151        let index = 232 * 480 + 240152        #expect(abs(result.g[index] - single.g[index]) < 0.01)153        // The moving lantern is spread out: its peak in the averaged image is far below the single-frame peak.154        var peakSingle: Float = 0, peakLong: Float = 0155        for y in 60..<150 { for x in 70..<170 { peakSingle = max(peakSingle, single.b[y * 480 + x]); peakLong = max(peakLong, result.b[y * 480 + x]) } }156        #expect(peakSingle > 0.9)157        #expect(peakLong < peakSingle - 0.15)158    }159160    @Test func sixteenBitOutputKeepsSubCodeValuePrecision() throws {161        let accumulator = FrameAccumulator(width: 8, height: 8, mode: .mean)162        accumulator.add(Fixture.solid(100, 100, 100, width: 8, height: 8))163        accumulator.add(Fixture.solid(101, 101, 101, width: 8, height: 8))164        let image = try #require(accumulator.result().cgImage16())165        #expect(image.bitsPerComponent == 16)166        let data = try #require(image.dataProvider?.data as Data?)167        let value = data.withUnsafeBytes { $0.load(as: UInt16.self) }168        // 100.5 / 255 × 65535 = 25828.5: between the 8-bit steps 25700 and 25957.169        #expect(abs(Int(value) - 25828) <= 1)170    }171}172173@Suite struct StackDenoiserTests {174    @Test func stackingStaticFramesRaisesPSNR() throws {175        let clean = Fixture.textured()176        let reference = try #require(FloatImage(pixelBuffer: clean))177        let first = Fixture.noisy(clean, sigma: 10, seed: 1)178        let denoiser = try #require(StackDenoiser(reference: first, tau: 0.12))179        for seed in 2...8 { denoiser.add(Fixture.noisy(clean, sigma: 10, seed: UInt64(seed))) }180        let before = try #require(FloatImage(pixelBuffer: first)).psnr(reference)181        let after = denoiser.result().psnr(reference)182        #expect(denoiser.frameCount == 8)183        // Ideal averaging of 8 frames gains 9 dB; robust weights give slightly less.184        #expect(after - before > 6.5)185    }186187    @Test func movingObjectsDoNotGhost() throws {188        let width = 128, height = 64189        func frame(squareAt x0: Int) -> CVPixelBuffer {190            let buffer = PixelBuffers.makeBGRA(width: width, height: height)!191            PixelBuffers.fill(buffer) { x, y in (x >= x0 && x < x0 + 16 && y >= 24 && y < 40) ? (250, 250, 250) : (40, 40, 40) }192            return buffer193        }194        let denoiser = try #require(StackDenoiser(reference: frame(squareAt: 20)))195        for x in [40, 60, 80, 100] { denoiser.add(frame(squareAt: x)) }196        let result = denoiser.result()197        // Where the square was in later frames only, the result must stay near the reference background (40/255 = 0.157).198        let ghost = result.g[32 * width + 66]199        #expect(abs(ghost - 40.0 / 255) < 0.02)200        // And the reference position keeps the square.201        #expect(result.g[32 * width + 28] > 0.9)202        // A plain mean would have produced (40·4 + 250)/5 = 82 → 0.32 at the ghost position.203    }204205    @Test func shiftedFramesAreMergedInPlace() throws {206        let clean = Fixture.textured()207        let shifted = Fixture.textured(shiftX: 5, shiftY: -3)   // content moved 5 px right, 3 px up208        let denoiser = try #require(StackDenoiser(reference: clean))209        denoiser.add(shifted, shift: (dx: -5, dy: 3))210        let reference = try #require(FloatImage(pixelBuffer: clean))211        #expect(denoiser.result().psnr(reference) > 45)212    }213}214215@Suite struct ImageAlignerTests {216    @Test func recoversAKnownTranslation() throws {217        let reference = Fixture.natural()218        for (sx, sy) in [(7, -4), (-6, 5), (0, 0), (12, 9)] {219            let moving = Fixture.natural(shiftX: sx, shiftY: sy)220            let shift = try #require(ImageAligner.shift(moving: moving, reference: reference))221            // The correction is the opposite of the displacement.222            #expect(abs(shift.dx + sx) <= 1, "dx \(shift.dx) for displacement \(sx)")223            #expect(abs(shift.dy + sy) <= 1, "dy \(shift.dy) for displacement \(sy)")224        }225    }226}227228extension ImageAlignerTests {229    @Test func implausibleShiftsAreRejected() {230        #expect(ImageAligner.plausible(10, -8, width: 1920, height: 1080))231        #expect(!ImageAligner.plausible(0, -131, width: 256, height: 192))232        // Unrelated images: whatever Vision returns, a large jump is never applied.233        let shift = ImageAligner.shift(moving: Fixture.natural(shiftX: 150, shiftY: 100), reference: Fixture.natural())234        if let shift { #expect(abs(shift.dx) <= 26 && abs(shift.dy) <= 20) }235    }236}237238@Suite struct ExposureFusionTests {239    @Test func pyramidReconstructsItsInput() {240        var random = SeededRandom(7)241        let plane = ExposureFusion.Plane(width: 97, height: 61, data: (0..<(97 * 61)).map { _ in Float(random.next()) })242        let rebuilt = ExposureFusion.collapse(ExposureFusion.laplacianPyramid(plane, levels: ExposureFusion.levelCount(width: 97, height: 61)))243        let worst = zip(plane.data, rebuilt.data).map { abs($0 - $1) }.max() ?? 1244        #expect(worst < 1e-4)245    }246247    @Test func fusingIdenticalImagesReturnsTheImage() throws {248        let image = try #require(FloatImage(pixelBuffer: Fixture.textured()))249        let fused = try ExposureFusion.fuse([image, image, image])250        #expect(fused.psnr(image) > 50)251    }252253    @Test func bracketFusionRecoversBothEndsOfTheRange() throws {254        // A scene with a dark half and a bright half. Under: bright half fine, dark half black. Over: the reverse.255        let width = 256, height = 128256        func exposure(gain: Double) -> FloatImage {257            let buffer = PixelBuffers.makeBGRA(width: width, height: height)!258            PixelBuffers.fill(buffer) { x, y in259                let texture = 0.75 + 0.25 * sin(Double(x) * 0.4) * sin(Double(y) * 0.4)260                let radiance = (x < width / 2 ? 0.04 : 1.6) * texture261                let v = UInt8(min(max(radiance * gain * 255, 0), 255))262                return (v, v, v)263            }264            return FloatImage(pixelBuffer: buffer)!265        }266        let under = exposure(gain: 0.3), over = exposure(gain: 8)267        let fused = try ExposureFusion.fuse([under, over])268        func contrast(_ image: FloatImage, xRange: Range<Int>) -> Float {269            var lo: Float = 1, hi: Float = 0270            for y in 20..<108 { for x in xRange { lo = min(lo, image.g[y * width + x]); hi = max(hi, image.g[y * width + x]) } }271            return hi - lo272        }273        // Texture is visible in both halves of the fused image, while each source shows it in one half only.274        #expect(contrast(under, xRange: 20..<100) < 0.02)275        #expect(contrast(over, xRange: 150..<236) < 0.02)276        #expect(contrast(fused, xRange: 20..<100) > 0.08)277        #expect(contrast(fused, xRange: 150..<236) > 0.08)278        #expect(fused.g.allSatisfy { $0 >= 0 && $0 <= 1 })279    }280281    @Test func errorsAreReported() {282        #expect(throws: ExposureFusion.FusionError.noImages) { try ExposureFusion.fuse([FloatImage]()) }283        #expect(throws: ExposureFusion.FusionError.sizeMismatch) {284            try ExposureFusion.fuse([FloatImage(width: 8, height: 8), FloatImage(width: 9, height: 8)])285        }286    }287}288
Files main
Menu

Theme