Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions FitCheck/DesignSystem/Theme.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
11 changes: 10 additions & 1 deletion FitCheck/Features/AddGarment/ProcessingViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
104 changes: 104 additions & 0 deletions FitCheck/Services/CutoutMatte.swift
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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..<height {
source.read(
base.advanced(by: row * rowBytes),
count: width,
into: &alpha,
at: row * width
)
}

return matte(alpha: alpha, width: width, height: height)
}

/// Where in a pixel the alpha value sits, for each mask format the app
/// accepts.
private enum AlphaSource {
/// One component, one byte: the value is the alpha.
case grey
/// One component, a 32-bit float in 0...1.
case intensity
/// An interleaved 32-bit pixel whose alpha is one of its bytes.
case channel(byte: Int)

init?(pixelFormat: OSType) {
switch pixelFormat {
case kCVPixelFormatType_OneComponent8: self = .grey
case kCVPixelFormatType_OneComponent32Float: self = .intensity
case kCVPixelFormatType_32BGRA: self = .channel(byte: 3)
case kCVPixelFormatType_32ARGB: self = .channel(byte: 0)
default: return nil
}
}

/// How many bytes one pixel occupies in the buffer, which is what the
/// row stride has to hold.
var components: Int {
switch self {
case .grey: 1
case .intensity, .channel: 4
}
}

/// Writes the alpha of `count` pixels from the row starting at `start`
/// into `alpha`, beginning at `offset`. The float sample is read
/// unaligned, so a stride that doesn't land on the pixel's own
/// alignment still reads correctly.
func read(
_ start: UnsafeRawPointer,
count: Int,
into alpha: inout [UInt8],
at offset: Int
) {
switch self {
case .grey:
for column in 0..<count {
alpha[offset + column] = start.load(
fromByteOffset: column,
as: UInt8.self
)
}
case .intensity:
for column in 0..<count {
let sample = start.loadUnaligned(
fromByteOffset: column * 4,
as: Float.self
)
// A NaN or infinite sample is a corrupt buffer, not a pixel:
// it reads as transparent instead of trapping the cast.
let value = sample.isFinite ? min(max(sample, 0), 1) : 0
alpha[offset + column] = UInt8((value * 255).rounded())
}
case .channel(let byte):
for column in 0..<count {
alpha[offset + column] = start.load(
fromByteOffset: column * 4 + byte,
as: UInt8.self
)
}
}
}
}

/// How much of the frame the matte keeps. Vision reports one instance per
/// subject; this is the number that decides which one is the garment, and
/// a matte with a hole punched in it is measured by what it keeps.
Expand Down
38 changes: 9 additions & 29 deletions FitCheck/Services/GarmentSegmenter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ struct GarmentSegmenter {

let mattes = try mattes(of: observation, from: handler)
guard let largest = CutoutMatte.largestIndex(among: mattes),
let refined = CutoutMatte.refined(mattes[largest]) else {
let refined = CutoutMatte.refined(mattes[largest]),
// Feathered away to nothing is not a cut-out: the review screen
// would show an empty frame it cannot dress, so this reads as the
// photo having no subject at all.
CutoutMatte.area(of: refined) > 0 else {
throw SegmentationError.subjectNotFound
}

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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..<height {
alpha.replaceSubrange(
row * width..<((row + 1) * width),
with: UnsafeBufferPointer(start: pixels + row * rowBytes, count: width)
)
}

return CutoutMatte.matte(alpha: alpha, width: width, height: height)
}

/// The photo as pixels with no orientation left to apply.
private static func uprightCGImage(_ image: UIImage) -> CGImage? {
guard let cgImage = image.cgImage else { return nil }
Expand Down
Loading
Loading