From 339a1e2929a6ddd335511436a68daee104d97981 Mon Sep 17 00:00:00 2001 From: Mxo01 Date: Wed, 18 Nov 2026 18:37:16 +0100 Subject: [PATCH] fix(cutout): read Vision's mask in its own pixel format --- FitCheck/DesignSystem/Theme.swift | 56 +++ .../Features/AddGarment/ProcessingViews.swift | 11 +- FitCheck/Services/CutoutMatte.swift | 104 +++++ FitCheck/Services/GarmentSegmenter.swift | 38 +- FitCheckTests/CutoutMatteTests.swift | 414 ++++++++++++++++++ 5 files changed, 593 insertions(+), 30 deletions(-) diff --git a/FitCheck/DesignSystem/Theme.swift b/FitCheck/DesignSystem/Theme.swift index b5e7be4..041d72d 100644 --- a/FitCheck/DesignSystem/Theme.swift +++ b/FitCheck/DesignSystem/Theme.swift @@ -76,6 +76,17 @@ struct Theme { static let pink = Color(hex: 0xFF375F) static let greenDeep = Color(hex: 0x1B6E31) + /// The two greys of `Checkerboard`, the ground a cut-out is read against. + /// + /// Fixed across schemes on purpose, and mid-tone on purpose: the review + /// preview used to draw the cut-out over `stage`, and in dark mode that + /// near-black made a black garment indistinguishable from a cut-out that + /// had failed. A light ground would fail the same way on a white one, so + /// both extremes have to stay readable and neither scheme can own the + /// answer. + static let checkerLight = Color(hex: 0x9C9CA4) + static let checkerDark = Color(hex: 0x8A8A92) + // MARK: Metrics /// Action buttons always appear in pairs — an accent button with a glass @@ -224,3 +235,48 @@ struct HatchPattern: View { .allowsHitTesting(false) } } + +/// The mid-tone check a cut-out is drawn on. +/// +/// A cut-out carries transparency where the background was, so the ground +/// behind it is what the garment's outline is read against. The review preview +/// used to put it on `stage`, and in dark mode a near-black wash swallowed a +/// black garment whole. One flat light ground would lose a white one the same +/// way, so the ground alternates between two greys and the edge of a garment +/// close to either still shows. Both greys stay fixed across schemes: the +/// whole point is that the garment's own colour is what varies. +/// +/// Decorative and untouchable — nothing in it is sized for text, so the cell +/// stays a fixed measure rather than a scaled one. +struct Checkerboard: View { + var light: Color = Theme.checkerLight + var dark: Color = Theme.checkerDark + var cell: CGFloat = 14 + + var body: some View { + Canvas { context, size in + context.fill( + Path(CGRect(origin: .zero, size: size)), + with: .color(light) + ) + + let columns = Int((size.width / cell).rounded(.up)) + let rows = Int((size.height / cell).rounded(.up)) + var squares = Path() + for row in 0 ..< rows { + for column in 0 ..< columns where (row + column).isMultiple(of: 2) { + squares.addRect( + CGRect( + x: CGFloat(column) * cell, + y: CGFloat(row) * cell, + width: cell, + height: cell + ) + ) + } + } + context.fill(squares, with: .color(dark)) + } + .allowsHitTesting(false) + } +} diff --git a/FitCheck/Features/AddGarment/ProcessingViews.swift b/FitCheck/Features/AddGarment/ProcessingViews.swift index f5eccc4..7492878 100644 --- a/FitCheck/Features/AddGarment/ProcessingViews.swift +++ b/FitCheck/Features/AddGarment/ProcessingViews.swift @@ -325,7 +325,16 @@ struct ReviewView: View { private var preview: some View { ZStack { - theme.stage + // The cut-out has no background of its own, so the ground behind + // it is what the garment is read against: the mid-tone check keeps + // a black garment and a white one both visible, where the dark + // stage hid the first. The original photo brings its own backdrop, + // and the stage still suits it. + if edited.cutout != nil { + Checkerboard() + } else { + theme.stage + } if let image = edited.cutout ?? edited.original { Image(uiImage: image) diff --git a/FitCheck/Services/CutoutMatte.swift b/FitCheck/Services/CutoutMatte.swift index 3aae2b6..731e5b4 100644 --- a/FitCheck/Services/CutoutMatte.swift +++ b/FitCheck/Services/CutoutMatte.swift @@ -1,6 +1,7 @@ import CoreGraphics import CoreImage import CoreImage.CIFilterBuiltins +import CoreVideo import Foundation /// The soft alpha matte behind a cut-out: which pixels of the photo the @@ -67,6 +68,109 @@ enum CutoutMatte { return matte.isWellFormed ? matte : nil } + /// The alpha channel of a mask pulled out of its pixel buffer. + /// + /// The format is a property of the buffer, not of the request: Vision + /// hands back a single-component 32-bit float mask today, and reading that + /// as one byte per pixel turns 1.0 into its low byte — zero — so the matte + /// empties without anything failing. The format decides how the pixels are + /// read instead, and one this doesn't know is refused rather than guessed + /// at. Rows are read at the buffer's own stride, because a row is padded + /// to whatever Core Video chose, not to the image's width. + static func matte(from buffer: CVPixelBuffer) -> Matte? { + CVPixelBufferLockBaseAddress(buffer, .readOnly) + defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) } + + let width = CVPixelBufferGetWidth(buffer) + let height = CVPixelBufferGetHeight(buffer) + let rowBytes = CVPixelBufferGetBytesPerRow(buffer) + + guard let source = AlphaSource(pixelFormat: CVPixelBufferGetPixelFormatType(buffer)), + width > 0, height > 0, rowBytes >= width * source.components, + let base = CVPixelBufferGetBaseAddress(buffer) else { return nil } + + var alpha = [UInt8](repeating: 0, count: width * height) + for row in 0.. 0 else { throw SegmentationError.subjectNotFound } @@ -100,7 +104,9 @@ struct GarmentSegmenter { /// /// The scaled mask covers the whole frame at the photo's own size, so an /// instance's coverage is a straight count of the pixels it keeps — - /// `CutoutMatte.largestIndex` does the counting and picks the garment. + /// `CutoutMatte.largestIndex` does the counting and picks the garment. The + /// mask's pixel format is Vision's to choose, so it is read from the buffer + /// `CutoutMatte.matte(from:)` is handed rather than assumed here. private static func mattes( of observation: VNInstanceMaskObservation, from handler: VNImageRequestHandler @@ -118,7 +124,7 @@ struct GarmentSegmenter { throw SegmentationError.processingFailed(error.localizedDescription) } - guard let instance = matte(from: mask) else { + guard let instance = CutoutMatte.matte(from: mask) else { throw SegmentationError.processingFailed("Couldn't read the garment's outline.") } mattes.append(instance) @@ -127,32 +133,6 @@ struct GarmentSegmenter { return mattes } - /// Copies a one-component mask out of its pixel buffer. - /// - /// Rows are padded to the buffer's stride, so the mask is copied row by - /// row rather than wholesale. - private static func matte(from mask: CVPixelBuffer) -> CutoutMatte.Matte? { - CVPixelBufferLockBaseAddress(mask, .readOnly) - defer { CVPixelBufferUnlockBaseAddress(mask, .readOnly) } - - let width = CVPixelBufferGetWidth(mask) - let height = CVPixelBufferGetHeight(mask) - guard let base = CVPixelBufferGetBaseAddress(mask) else { return nil } - - let rowBytes = CVPixelBufferGetBytesPerRow(mask) - let pixels = base.assumingMemoryBound(to: UInt8.self) - - var alpha = [UInt8](repeating: 0, count: width * height) - for row in 0.. CGImage? { guard let cgImage = image.cgImage else { return nil } diff --git a/FitCheckTests/CutoutMatteTests.swift b/FitCheckTests/CutoutMatteTests.swift index ce12f80..91e9407 100644 --- a/FitCheckTests/CutoutMatteTests.swift +++ b/FitCheckTests/CutoutMatteTests.swift @@ -1,5 +1,6 @@ import CoreGraphics import CoreImage +import CoreVideo import Foundation import Testing @testable import FitCheck @@ -123,6 +124,195 @@ private func render(_ image: CIImage, in rect: CGRect) -> Raster { return Raster(width: width, height: height, bytes: bytes) } +// MARK: - Synthetic pixel buffers + +/// One of the pixel formats a mask arrives in, and how many bytes one pixel of +/// it occupies. +enum MaskFormat: Sendable { + /// One component of a single byte: the value is the alpha. + case grey + /// One component of a 32-bit float, in 0...1. + case intensity + /// Interleaved 32-bit BGRA, with the alpha in the fourth byte. + case bgra + /// Interleaved 32-bit ARGB, with the alpha in the first byte. + case argb + + var pixelFormat: OSType { + switch self { + case .grey: kCVPixelFormatType_OneComponent8 + case .intensity: kCVPixelFormatType_OneComponent32Float + case .bgra: kCVPixelFormatType_32BGRA + case .argb: kCVPixelFormatType_32ARGB + } + } + + /// What a row has to hold, per column. + var components: Int { + switch self { + case .grey: 1 + case .intensity, .bgra, .argb: 4 + } + } +} + +/// One pixel as a buffer carries it, and the alpha the matte must read out of +/// it. The name says which sample the expectation belongs to, so a failure +/// names the value rather than a column. +struct MaskPixel: Sendable, CustomStringConvertible { + let name: String + let bytes: [UInt8] + let alpha: UInt8 + + var description: String { name } + + /// The byte a channel the matte has to ignore carries, distinct from every + /// alpha in the tables so a wrong byte reads as a wrong value. + private static let filler: UInt8 = 0x11 + + /// A single-component 8-bit mask, whose value is its alpha. + static func grey(_ value: UInt8, named name: String) -> MaskPixel { + MaskPixel(name: name, bytes: [value], alpha: value) + } + + /// A 32-bit float sample and the alpha it must become: 0...1 spans the + /// matte, a sample outside it is clamped, and one that is not a number is + /// read as clear rather than trapping the cast. + static func intensity(_ sample: Float, alpha: UInt8, named name: String) -> MaskPixel { + MaskPixel( + name: name, + bytes: withUnsafeBytes(of: sample.bitPattern) { Array($0) }, + alpha: alpha + ) + } + + /// An interleaved pixel whose alpha is one of its bytes. + static func channel(_ alpha: UInt8, at byte: Int, named name: String) -> MaskPixel { + var bytes = [UInt8](repeating: filler, count: 4) + bytes[byte] = alpha + return MaskPixel(name: name, bytes: bytes, alpha: alpha) + } +} + +/// One mask format and the rows a synthetic buffer of it carries, with the +/// alpha each pixel must produce. +struct MaskBufferFixture: Sendable, CustomStringConvertible { + let name: String + let format: MaskFormat + let rows: [[MaskPixel]] + + init(name: String, format: MaskFormat, rows: [[MaskPixel]]) { + self.name = name + self.format = format + self.rows = rows + } + + /// A buffer `columns` wide with one named sample per row, repeated across + /// the row: what a padded stride has to keep apart. + init(name: String, format: MaskFormat, columns: Int, samples: [MaskPixel]) { + self.init( + name: name, + format: format, + rows: samples.map { [MaskPixel](repeating: $0, count: columns) } + ) + } + + var description: String { name } + + var width: Int { rows.first?.count ?? 0 } + var height: Int { rows.count } +} + +/// The byte a synthetic buffer's padding is filled with: one no fixture +/// expects to read, so a reader striding by the width instead of by +/// `bytesPerRow` lands on it and is caught. +private enum StridePadding { + static let byte: UInt8 = 0 + static let alignment = 64 +} + +/// Why a synthetic buffer could not be built: a fixture that disagrees with +/// itself, or Core Video refusing the format. +private enum BufferBuildError: Error { + case raggedRows + case baseAddressUnavailable + case creationFailed(CVReturn) +} + +/// A buffer of any format, with its pixels as Core Video painted them — all +/// the tests that never read a sample need. +private func makeEmptyPixelBuffer( + format: OSType, + width: Int, + height: Int, + alignment: Int? = nil +) throws -> CVPixelBuffer { + var attributes: [CFString: Any] = [:] + if let alignment { + attributes[kCVPixelBufferBytesPerRowAlignmentKey] = alignment + } + + var buffer: CVPixelBuffer? + let status = CVPixelBufferCreate( + kCFAllocatorDefault, + width, + height, + format, + attributes as CFDictionary, + &buffer + ) + guard status == kCVReturnSuccess, let buffer else { + throw BufferBuildError.creationFailed(status) + } + return buffer +} + +/// A buffer of `format` with `rows` written into it, one row at a time through +/// the locked base address, and every byte of each row's padding set to +/// `padding`. +private func makePixelBuffer( + format: MaskFormat, + rows: [[MaskPixel]], + padding: UInt8 = 0, + alignment: Int? = nil +) throws -> CVPixelBuffer { + guard let first = rows.first, + rows.allSatisfy({ row in + row.count == first.count + && row.allSatisfy { $0.bytes.count == format.components } + }) else { throw BufferBuildError.raggedRows } + + let buffer = try makeEmptyPixelBuffer( + format: format.pixelFormat, + width: first.count, + height: rows.count, + alignment: alignment + ) + + CVPixelBufferLockBaseAddress(buffer, []) + defer { CVPixelBufferUnlockBaseAddress(buffer, []) } + guard let base = CVPixelBufferGetBaseAddress(buffer) else { + throw BufferBuildError.baseAddressUnavailable + } + + let rowBytes = CVPixelBufferGetBytesPerRow(buffer) + for (index, row) in rows.enumerated() { + let start = base.assumingMemoryBound(to: UInt8.self) + .advanced(by: index * rowBytes) + start.update(repeating: padding, count: rowBytes) + + var offset = 0 + for pixel in row { + for byte in pixel.bytes { + start[offset] = byte + offset += 1 + } + } + } + + return buffer +} + // MARK: - Fixtures /// One buffer and the size it claims, so acceptance is read as agreement @@ -405,6 +595,230 @@ struct CutoutMatteTests { #expect(largest == fixture.largest, "\(fixture)") } + // MARK: - Reading a pixel buffer + + private static let bufferFixtures: [MaskBufferFixture] = [ + MaskBufferFixture( + name: "An 8-bit mask's bytes are its alpha", + format: .grey, + rows: [ + [ + .grey(255, named: "opaque"), + .grey(0, named: "clear"), + .grey(128, named: "half"), + ], + [ + .grey(1, named: "barely there"), + .grey(254, named: "nearly opaque"), + .grey(64, named: "a quarter"), + ], + ] + ), + MaskBufferFixture( + name: "A float mask's samples span the matte and clamp beyond it", + format: .intensity, + rows: [ + [ + .intensity(1, alpha: Alpha.opaque, named: "1.0 is opaque"), + .intensity(0.5, alpha: 128, named: "0.5 is halfway"), + .intensity(0.25, alpha: 64, named: "0.25 is a quarter"), + .intensity(0, alpha: Alpha.clear, named: "0.0 is clear"), + ], + [ + .intensity(1.5, alpha: Alpha.opaque, named: "1.5 clamps to opaque"), + .intensity(-0.5, alpha: Alpha.clear, named: "-0.5 clamps to clear"), + .intensity(.nan, alpha: Alpha.clear, named: "NaN is clear"), + .intensity(.infinity, alpha: Alpha.clear, named: "+infinity is clear"), + ], + [ + .intensity(-.infinity, alpha: Alpha.clear, named: "-infinity is clear"), + .intensity(1, alpha: Alpha.opaque, named: "1.0 is opaque"), + .intensity(0.75, alpha: 191, named: "0.75 is three quarters"), + .intensity(0.2, alpha: 51, named: "0.2 is a fifth"), + ], + ] + ), + MaskBufferFixture( + name: "A BGRA mask's alpha is its fourth byte", + format: .bgra, + rows: [ + [ + .channel(255, at: 3, named: "opaque"), + .channel(0, at: 3, named: "clear"), + .channel(128, at: 3, named: "half"), + ], + [ + .channel(64, at: 3, named: "a quarter"), + .channel(1, at: 3, named: "barely there"), + .channel(200, at: 3, named: "mostly opaque"), + ], + ] + ), + MaskBufferFixture( + name: "An ARGB mask's alpha is its first byte", + format: .argb, + rows: [ + [ + .channel(255, at: 0, named: "opaque"), + .channel(0, at: 0, named: "clear"), + .channel(128, at: 0, named: "half"), + ], + [ + .channel(64, at: 0, named: "a quarter"), + .channel(1, at: 0, named: "barely there"), + .channel(200, at: 0, named: "mostly opaque"), + ], + ] + ), + ] + + @Test("A mask's alpha lands in the matte for every format the app reads", + arguments: bufferFixtures) + func bufferAlphaLandsInTheMatte(fixture: MaskBufferFixture) throws { + let testSubject = CutoutMatte.self + let buffer = try makePixelBuffer(format: fixture.format, rows: fixture.rows) + + let matte = try #require( + testSubject.matte(from: buffer), + "\(fixture): a format the app reads was refused" + ) + + #expect(matte.width == fixture.width, "\(fixture): wrong width") + #expect(matte.height == fixture.height, "\(fixture): wrong height") + #expect(matte.origin == .zero, "\(fixture): a full-frame mask was moved") + #expect(matte.isWellFormed, "\(fixture): the matte disagrees with its size") + guard matte.width == fixture.width, + matte.height == fixture.height, + matte.isWellFormed else { return } + + for row in 0.. needed else { return } + + let matte = try #require( + testSubject.matte(from: buffer), + "\(fixture): a padded buffer was refused" + ) + + #expect(matte.width == fixture.width, "\(fixture): wrong width") + #expect(matte.height == fixture.height, "\(fixture): wrong height") + guard matte.width == fixture.width, matte.height == fixture.height else { return } + + for row in 0..