SPB Git

Repository Public License

FloatImage.swift 10.7 KB 239 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/Support/FloatImage.swift10// Description      : Planar 32-bit float RGB image (values 0…1 on the11//                    gamma-encoded signal) with conversions from and to CGImage12//                    and BGRA pixel buffers. The working type of the13//                    multi-frame engines.14// Module           : ORIXImaging15// Repository       : https://git.spboucher.ai/orix-camera16// Project Website  : https://www.orixlab.dev17// Created          : 2026-11-2118// Last Modified    : 2026-11-2119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Accelerate94import CoreGraphics95import CoreVideo96import Foundation9798public struct FloatImage: Sendable {99    public let width: Int100    public let height: Int101    public var r: [Float]102    public var g: [Float]103    public var b: [Float]104105    public var count: Int { width * height }106107    public init(width: Int, height: Int, fill: Float = 0) {108        self.width = width; self.height = height109        r = [Float](repeating: fill, count: width * height); g = r; b = r110    }111112    /// Decodes an image to 8-bit sRGB bytes (RGBA, row-major). `offset` shifts the drawing by whole pixels (x right, y down).113    public static func rgba8(_ image: CGImage, offset: (dx: Int, dy: Int) = (0, 0)) -> [UInt8]? {114        let w = image.width, h = image.height115        var bytes = [UInt8](repeating: 0, count: w * h * 4)116        let ok = bytes.withUnsafeMutableBytes { raw -> Bool in117            guard let context = CGContext(data: raw.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,118                                          space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return false }119            context.interpolationQuality = .none120            if offset.dx != 0 || offset.dy != 0 {121                // Fill with the unshifted image first so uncovered borders hold plausible pixels rather than black.122                context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))123            }124            context.draw(image, in: CGRect(x: offset.dx, y: -offset.dy, width: w, height: h))125            return true126        }127        return ok ? bytes : nil128    }129130    public init?(cgImage: CGImage, offset: (dx: Int, dy: Int) = (0, 0)) {131        guard let bytes = FloatImage.rgba8(cgImage, offset: offset) else { return nil }132        self.init(rgba8: bytes, width: cgImage.width, height: cgImage.height)133    }134135    public init(rgba8 bytes: [UInt8], width: Int, height: Int) {136        self.init(width: width, height: height)137        let n = vDSP_Length(width * height)138        var scale: Float = 1 / 255139        bytes.withUnsafeBufferPointer { p in140            vDSP_vfltu8(p.baseAddress!, 4, &r, 1, n)141            vDSP_vfltu8(p.baseAddress! + 1, 4, &g, 1, n)142            vDSP_vfltu8(p.baseAddress! + 2, 4, &b, 1, n)143        }144        vDSP_vsmul(r, 1, &scale, &r, 1, n); vDSP_vsmul(g, 1, &scale, &g, 1, n); vDSP_vsmul(b, 1, &scale, &b, 1, n)145    }146147    public init?(pixelBuffer: CVPixelBuffer) {148        guard PixelBuffers.isBGRA(pixelBuffer) else { return nil }149        let w = CVPixelBufferGetWidth(pixelBuffer), h = CVPixelBufferGetHeight(pixelBuffer)150        self.init(width: w, height: h)151        var scale: Float = 1 / 255152        let ok: Bool? = PixelBuffers.withLocked(pixelBuffer) { base, rowBytes, _, _ in153            for y in 0..<h {154                let row = base.advanced(by: y * rowBytes).assumingMemoryBound(to: UInt8.self)155                r.withUnsafeMutableBufferPointer { vDSP_vfltu8(row + 2, 4, $0.baseAddress! + y * w, 1, vDSP_Length(w)) }156                g.withUnsafeMutableBufferPointer { vDSP_vfltu8(row + 1, 4, $0.baseAddress! + y * w, 1, vDSP_Length(w)) }157                b.withUnsafeMutableBufferPointer { vDSP_vfltu8(row, 4, $0.baseAddress! + y * w, 1, vDSP_Length(w)) }158            }159            return true160        }161        guard ok == true else { return nil }162        let n = vDSP_Length(w * h)163        vDSP_vsmul(r, 1, &scale, &r, 1, n); vDSP_vsmul(g, 1, &scale, &g, 1, n); vDSP_vsmul(b, 1, &scale, &b, 1, n)164    }165166    /// Rec. 709 luma plane.167    public func luma() -> [Float] {168        var out = [Float](repeating: 0, count: count)169        var kr: Float = 0.2126, kg: Float = 0.7152, kb: Float = 0.0722170        let n = vDSP_Length(count)171        vDSP_vsmul(r, 1, &kr, &out, 1, n)172        vDSP_vsma(g, 1, &kg, out, 1, &out, 1, n)173        vDSP_vsma(b, 1, &kb, out, 1, &out, 1, n)174        return out175    }176177    /// 16-bit-per-channel sRGB CGImage (values clipped to 0…1).178    public func cgImage16() -> CGImage? {179        var data = [UInt16](repeating: 65535, count: count * 4)180        let n = vDSP_Length(count)181        var lo: Float = 0, hi: Float = 65535, scale: Float = 65535182        var temp = [Float](repeating: 0, count: count)183        data.withUnsafeMutableBufferPointer { p in184            for (c, plane) in [r, g, b].enumerated() {185                vDSP_vsmul(plane, 1, &scale, &temp, 1, n)186                vDSP_vclip(temp, 1, &lo, &hi, &temp, 1, n)187                vDSP_vfixru16(temp, 1, p.baseAddress! + c, 4, n)188            }189        }190        let bytes = data.withUnsafeBufferPointer { Data(buffer: $0) }191        guard let provider = CGDataProvider(data: bytes as CFData) else { return nil }192        let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue | CGBitmapInfo.byteOrder16Little.rawValue)193        return CGImage(width: width, height: height, bitsPerComponent: 16, bitsPerPixel: 64, bytesPerRow: width * 8,194                       space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info, provider: provider, decode: nil,195                       shouldInterpolate: true, intent: .defaultIntent)196    }197198    /// 8-bit BGRA pixel buffer (values clipped to 0…1).199    public func pixelBuffer() -> CVPixelBuffer? {200        guard let buffer = PixelBuffers.makeBGRA(width: width, height: height) else { return nil }201        var lo: Float = 0, hi: Float = 255, scale: Float = 255202        var temp = [Float](repeating: 0, count: width)203        PixelBuffers.withLocked(buffer, readOnly: false) { base, rowBytes, w, h in204            for y in 0..<h {205                let row = base.advanced(by: y * rowBytes).assumingMemoryBound(to: UInt8.self)206                memset(row, 255, w * 4)207                for (offset, plane) in [(2, r), (1, g), (0, b)] {208                    plane.withUnsafeBufferPointer { p in209                        vDSP_vsmul(p.baseAddress! + y * w, 1, &scale, &temp, 1, vDSP_Length(w))210                    }211                    vDSP_vclip(temp, 1, &lo, &hi, &temp, 1, vDSP_Length(w))212                    vDSP_vfixru8(temp, 1, row + offset, 4, vDSP_Length(w))213                }214            }215        }216        return buffer217    }218219    /// Mean squared error against another image of the same size (all channels).220    public func mse(_ other: FloatImage) -> Double {221        guard other.count == count, count > 0 else { return .infinity }222        var total = 0.0223        var diff = [Float](repeating: 0, count: count)224        for (a, c) in [(r, other.r), (g, other.g), (b, other.b)] {225            vDSP_vsub(c, 1, a, 1, &diff, 1, vDSP_Length(count))226            var ms: Float = 0227            vDSP_measqv(diff, 1, &ms, vDSP_Length(count))228            total += Double(ms)229        }230        return total / 3231    }232233    /// Peak signal-to-noise ratio in dB (peak = 1).234    public func psnr(_ other: FloatImage) -> Double {235        let e = mse(other)236        return e <= 0 ? .infinity : 10 * log10(1 / e)237    }238}239
Files main
Menu

Theme