SPB Git

Repository Public

ImageAdjustments.swift 5.9 KB 129 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Engines/ImageProcessing/ImageAdjustments.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/// Shared Core Image context. `CIContext` is documented as thread-safe.46enum ImagePipeline {47    static let context = CIContext(options: [.cacheIntermediates: false])48    static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!4950    static func render(_ image: CIImage) -> CGImage? {51        let extent = image.extent.integral52        guard !extent.isInfinite, extent.width >= 1, extent.height >= 1 else { return nil }53        return context.createCGImage(image, from: extent, format: .RGBA8, colorSpace: sRGB)54    }55}5657/// Small RGBA bitmap sampled from an image, for measurements (sharpness,58/// glare, light). Never stored.59struct SampledBitmap: Sendable {60    var width: Int61    var height: Int62    var rgba: [UInt8]6364    /// Renders `region` (Core Image coordinates) of `image` scaled so its width is `targetWidth`.65    init?(_ image: CIImage, region: CGRect? = nil, targetWidth: Int = 320) {66        let source = (region ?? image.extent).intersection(image.extent)67        guard source.width >= 2, source.height >= 2, !source.isInfinite else { return nil }68        let scale = CGFloat(targetWidth) / source.width69        let w = targetWidth, h = max(2, Int((source.height * scale).rounded()))70        let scaled = image.cropped(to: source)71            .transformed(by: CGAffineTransform(translationX: -source.minX, y: -source.minY))72            .transformed(by: CGAffineTransform(scaleX: scale, y: CGFloat(h) / source.height))73        var bytes = [UInt8](repeating: 0, count: w * h * 4)74        ImagePipeline.context.render(scaled, toBitmap: &bytes, rowBytes: w * 4, bounds: CGRect(x: 0, y: 0, width: w, height: h),75                                     format: .RGBA8, colorSpace: ImagePipeline.sRGB)76        width = w77        height = h78        rgba = bytes79    }8081    /// Rec. 709 luma of every pixel, 0…255.82    var luminance: [Float] {83        var out = [Float](repeating: 0, count: width * height)84        for i in 0..<(width * height) {85            out[i] = 0.2126 * Float(rgba[i * 4]) + 0.7152 * Float(rgba[i * 4 + 1]) + 0.0722 * Float(rgba[i * 4 + 2])86        }87        return out88    }89}9091enum ImageAdjustments {92    /// Restrained colour correction: Core Image's auto-adjust (no red-eye, no93    /// crop, no level/rotation) mixed back with the original, so colours and94    /// logos stay recognisably those of the card. Off by default in the scanner.95    static func enhanced(_ image: CGImage, amount: Double = 0.5) -> CGImage {96        let input = CIImage(cgImage: image)97        var adjusted = input98        let options: [CIImageAutoAdjustmentOption: Any] = [.redEye: false, .crop: false, .level: false]99        for filter in input.autoAdjustmentFilters(options: options) {100            filter.setValue(adjusted, forKey: kCIInputImageKey)101            adjusted = filter.outputImage ?? adjusted102        }103        let mixed = adjusted.cropped(to: input.extent).applyingFilter("CIDissolveTransition", parameters: [104            kCIInputTargetImageKey: input, kCIInputTimeKey: 1 - min(max(amount, 0), 1)])105        return ImagePipeline.render(mixed.cropped(to: input.extent)) ?? image106    }107108    /// Rotates by quarter turns clockwise.109    static func rotated(_ image: CGImage, quarterTurnsClockwise turns: Int) -> CGImage {110        let n = ((turns % 4) + 4) % 4111        guard n != 0 else { return image }112        let orientation: CGImagePropertyOrientation = [.up, .right, .down, .left][n]113        let rotated = CIImage(cgImage: image).oriented(orientation)114        return ImagePipeline.render(rotated.transformed(by: CGAffineTransform(translationX: -rotated.extent.minX, y: -rotated.extent.minY))) ?? image115    }116117    /// Applies an EXIF orientation so the pixels are upright.118    static func upright(_ image: CGImage, orientation: CGImagePropertyOrientation) -> CGImage {119        guard orientation != .up else { return image }120        let oriented = CIImage(cgImage: image).oriented(orientation)121        return ImagePipeline.render(oriented.transformed(by: CGAffineTransform(translationX: -oriented.extent.minX, y: -oriented.extent.minY))) ?? image122    }123124    /// Scales down so the long edge is at most `longEdge` (never up).125    static func limited(_ image: CGImage, longEdge: Int) -> CGImage {126        CardImageCodec.resized(image, longEdge: longEdge)127    }128}129
Files main
Menu

Theme