Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
242 lines
12 KiB
Swift
242 lines
12 KiB
Swift
import AppKit
|
||
import CoreImage
|
||
import ImageIO
|
||
import Vision
|
||
import LichtkastenCore
|
||
|
||
/// On-device jersey number recognition (Apple Vision, runs on the Neural Engine):
|
||
/// 1. find people · 2. OCR on the shirt and shorts area of each person · 3. team by kit color
|
||
/// · 4. team prefix + number → code from the code library ("w10" → "Svenja Huth (VfL Wolfsburg, 10)").
|
||
struct JerseyRecognizer: Sendable {
|
||
let teams: [JerseyTeam]
|
||
let codes: CodeReplacements
|
||
/// code → all columns (for "Persons shown" name)
|
||
let columns: [String: [String]]
|
||
var useShirt = true
|
||
var useShorts = true
|
||
var minConfidence = 0.35
|
||
|
||
private static let ciContext = CIContext(options: [.useSoftwareRenderer: false])
|
||
|
||
// MARK: Entry
|
||
|
||
func recognize(url: URL) -> [JerseySuggestion] {
|
||
guard let cg = Self.loadImage(url) else { return [] }
|
||
let W = Double(cg.width), H = Double(cg.height)
|
||
let full = CGRect(x: 0, y: 0, width: W, height: H)
|
||
|
||
// 1. people
|
||
let humans = VNDetectHumanRectanglesRequest()
|
||
humans.upperBodyOnly = false
|
||
try? VNImageRequestHandler(cgImage: cg, options: [:]).perform([humans])
|
||
var people = (humans.results ?? []).map(\.boundingBox).filter { $0.height > 0.06 }
|
||
people.sort { $0.width * $0.height > $1.width * $1.height }
|
||
people = Array(people.prefix(10))
|
||
// pixel rects, top-left origin
|
||
let personRects: [CGRect] = people.map { p in
|
||
CGRect(x: p.minX * W, y: (1 - p.maxY) * H, width: p.width * W, height: p.height * H)
|
||
}
|
||
|
||
var raw: [JerseySuggestion] = []
|
||
var hitBoxes: [CGRect] = [] // to skip duplicates from the full-frame pass
|
||
|
||
// 2. OCR on each whole person (padded, upscaled) – the number can be anywhere on shirt or shorts
|
||
for (pi, pr) in personRects.enumerated() {
|
||
let padded = pr.insetBy(dx: -pr.width * 0.06, dy: -pr.height * 0.03).intersection(full).integral
|
||
guard padded.width > 16, padded.height > 16, let crop = cg.cropping(to: padded) else { continue }
|
||
for hit in Self.readNumbers(crop, minTextHeight: 0.025, upscaleTo: 1400) {
|
||
let nb = Self.toPixels(hit.box, in: padded) // number box in image pixels
|
||
// where on the body? (relative to the person box, 0 = head, 1 = feet)
|
||
let yRel = (nb.midY - pr.minY) / max(pr.height, 1)
|
||
let upperOnly = pr.height / max(pr.width, 1) < 1.3
|
||
let region: JerseyRegion = upperOnly || yRel < 0.52 ? .shirt : .shorts
|
||
if region == .shirt && !useShirt { continue }
|
||
if region == .shorts && !useShorts { continue }
|
||
if !upperOnly && (yRel < 0.08 || yRel > 0.9) { continue } // head / socks: ads, boards
|
||
guard hit.confidence >= minConfidence else { continue }
|
||
let color = Self.kitColor(around: nb, in: cg)
|
||
let team = color.flatMap { JerseyLogic.matchTeam(color: $0, region: region, teams: teams) }
|
||
hitBoxes.append(nb)
|
||
raw += suggestions(number: hit.number, team: team, confidence: hit.confidence, region: region,
|
||
box: Self.normalized(nb, W, H), personArea: Double(people[pi].width * people[pi].height),
|
||
color: color)
|
||
}
|
||
}
|
||
|
||
// 3. whole frame (people not detected: tight crops, motion blur, partly hidden)
|
||
for hit in Self.readNumbers(cg, minTextHeight: 0.012, upscaleTo: 0) where hit.confidence >= minConfidence + 0.1 {
|
||
let nb = Self.toPixels(hit.box, in: full)
|
||
if hitBoxes.contains(where: { $0.intersects(nb) }) { continue }
|
||
// a number lying inside a person counts as jersey number, otherwise lower confidence (could be a board)
|
||
let insidePerson = personRects.firstIndex { $0.contains(CGPoint(x: nb.midX, y: nb.midY)) }
|
||
let color = Self.kitColor(around: nb, in: cg)
|
||
let team = color.flatMap { JerseyLogic.matchTeam(color: $0, region: .shirt, teams: teams) }
|
||
raw += suggestions(number: hit.number, team: team, confidence: hit.confidence * (insidePerson == nil ? 0.6 : 0.9),
|
||
region: insidePerson == nil ? .image : .shirt, box: Self.normalized(nb, W, H),
|
||
personArea: insidePerson.map { Double(people[$0].width * people[$0].height) } ?? 0, color: color)
|
||
}
|
||
return JerseyLogic.merge(raw)
|
||
}
|
||
|
||
static func toPixels(_ visionBox: CGRect, in rect: CGRect) -> CGRect {
|
||
CGRect(x: rect.minX + visionBox.minX * rect.width, y: rect.minY + (1 - visionBox.maxY) * rect.height,
|
||
width: visionBox.width * rect.width, height: visionBox.height * rect.height)
|
||
}
|
||
|
||
static func normalized(_ r: CGRect, _ W: Double, _ H: Double) -> [Double] {
|
||
[Double(r.minX) / W, Double(r.minY) / H, Double(r.width) / W, Double(r.height) / H]
|
||
}
|
||
|
||
/// Kit color right around the number: a box ~3× the number, the number's own pixels are the minority cluster.
|
||
static func kitColor(around nb: CGRect, in cg: CGImage) -> KitColor? {
|
||
let full = CGRect(x: 0, y: 0, width: cg.width, height: cg.height)
|
||
let area = nb.insetBy(dx: -nb.width * 1.0, dy: -nb.height * 0.6).intersection(full).integral
|
||
guard area.width > 6, area.height > 6, let crop = cg.cropping(to: area) else { return nil }
|
||
return dominantColor(crop, centerOnly: false)
|
||
}
|
||
|
||
/// Team known → one suggestion; unknown → one per team that has this number (you pick the right one).
|
||
private func suggestions(number: Int, team: JerseyTeam?, confidence: Double, region: JerseyRegion,
|
||
box: [Double], personArea: Double, color: KitColor?) -> [JerseySuggestion] {
|
||
let candidates = team.map { [$0] } ?? teams
|
||
var out: [JerseySuggestion] = []
|
||
for t in candidates {
|
||
let code = t.prefix + String(number)
|
||
let rep = codes.lookup(code)
|
||
if team == nil && rep == nil { continue }
|
||
var s = JerseySuggestion(number: number, teamID: t.id, code: code, replacement: rep,
|
||
confidence: team == nil ? confidence * 0.6 : confidence,
|
||
regions: [region], box: box, personArea: personArea)
|
||
s.measuredColor = color
|
||
s.teamCertain = team != nil
|
||
out.append(s)
|
||
}
|
||
if out.isEmpty {
|
||
// number read, but no team/code → still shown (as "#10 – kein Code"), so you see it was found
|
||
var s = JerseySuggestion(number: number, teamID: nil, code: nil, replacement: nil, confidence: confidence * 0.5,
|
||
regions: [region], box: box, personArea: personArea)
|
||
s.measuredColor = color
|
||
out.append(s)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// MARK: OCR
|
||
|
||
struct NumberHit { let number: Int; let confidence: Double; let box: CGRect }
|
||
|
||
/// OCR for 1–2 digit numbers. `upscaleTo`: small crops are enlarged to this long edge (Vision reads
|
||
/// small numbers much better), 0 = no upscaling.
|
||
static func readNumbers(_ image: CGImage, minTextHeight: Float, upscaleTo: Int) -> [NumberHit] {
|
||
var img = image
|
||
let longEdge = max(image.width, image.height)
|
||
if upscaleTo > 0, longEdge < upscaleTo, let up = upscale(image, factor: min(4, Double(upscaleTo) / Double(longEdge))) { img = up }
|
||
|
||
let req = VNRecognizeTextRequest()
|
||
req.recognitionLevel = .accurate
|
||
req.usesLanguageCorrection = false
|
||
req.recognitionLanguages = ["en-US"]
|
||
req.minimumTextHeight = minTextHeight
|
||
try? VNImageRequestHandler(cgImage: img, options: [:]).perform([req])
|
||
var hits: [NumberHit] = []
|
||
for obs in req.results ?? [] {
|
||
var found = false
|
||
for cand in obs.topCandidates(3) where !found {
|
||
// whole string ("10") or a number token inside ("HUTH 10", "10.")
|
||
let tokens = [cand.string] + cand.string.split(whereSeparator: { !$0.isNumber && !"OoIl|".contains($0) }).map(String.init)
|
||
for t in tokens {
|
||
guard let n = JerseyLogic.parseNumber(t) else { continue }
|
||
var box = obs.boundingBox
|
||
if t != cand.string, let range = cand.string.range(of: t), let b = try? cand.boundingBox(for: range)?.boundingBox {
|
||
box = b
|
||
}
|
||
hits.append(NumberHit(number: n, confidence: Double(cand.confidence), box: box))
|
||
found = true
|
||
break
|
||
}
|
||
}
|
||
}
|
||
return hits
|
||
}
|
||
|
||
static func upscale(_ img: CGImage, factor: Double) -> CGImage? {
|
||
let ci = CIImage(cgImage: img)
|
||
guard let f = CIFilter(name: "CILanczosScaleTransform") else { return nil }
|
||
f.setValue(ci, forKey: kCIInputImageKey)
|
||
f.setValue(factor, forKey: kCIInputScaleKey)
|
||
f.setValue(1.0, forKey: kCIInputAspectRatioKey)
|
||
guard let out = f.outputImage else { return nil }
|
||
return ciContext.createCGImage(out, from: out.extent)
|
||
}
|
||
|
||
// MARK: Kit color
|
||
|
||
/// Dominant color of the kit area: 24×24 thumbnail, simple k-means (k = 3), largest cluster
|
||
/// that is not grass green or skin-ish.
|
||
static func dominantColor(_ img: CGImage, centerOnly: Bool = true) -> KitColor? {
|
||
let n = 24
|
||
var pixels = [UInt8](repeating: 0, count: n * n * 4)
|
||
guard let ctx = CGContext(data: &pixels, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n * 4,
|
||
space: CGColorSpaceCreateDeviceRGB(),
|
||
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
|
||
// central part only (less background)
|
||
let w = Double(img.width), h = Double(img.height)
|
||
let inner = centerOnly ? CGRect(x: w * 0.2, y: h * 0.15, width: w * 0.6, height: h * 0.7).integral
|
||
: CGRect(x: 0, y: 0, width: w, height: h)
|
||
guard let center = img.cropping(to: inner) else { return nil }
|
||
ctx.interpolationQuality = .medium
|
||
ctx.draw(center, in: CGRect(x: 0, y: 0, width: n, height: n))
|
||
var pts: [KitColor] = []
|
||
for i in 0..<(n * n) {
|
||
pts.append(KitColor(r: Double(pixels[i * 4]) / 255, g: Double(pixels[i * 4 + 1]) / 255, b: Double(pixels[i * 4 + 2]) / 255))
|
||
}
|
||
var centers = [pts[0], pts[pts.count / 2], pts[pts.count - 1]]
|
||
var assign = [Int](repeating: 0, count: pts.count)
|
||
for _ in 0..<8 {
|
||
for (i, p) in pts.enumerated() {
|
||
var best = 0
|
||
var bestD = Double.greatestFiniteMagnitude
|
||
for (ci, c) in centers.enumerated() {
|
||
let d = p.distance(to: c)
|
||
if d < bestD { bestD = d; best = ci }
|
||
}
|
||
assign[i] = best
|
||
}
|
||
for c in centers.indices {
|
||
var sr = 0.0, sg = 0.0, sb = 0.0, count = 0
|
||
for i in pts.indices where assign[i] == c {
|
||
sr += pts[i].r; sg += pts[i].g; sb += pts[i].b; count += 1
|
||
}
|
||
guard count > 0 else { continue }
|
||
let k = Double(count)
|
||
centers[c] = KitColor(r: sr / k, g: sg / k, b: sb / k)
|
||
}
|
||
}
|
||
var sizes = [Int](repeating: 0, count: centers.count)
|
||
for a in assign { sizes[a] += 1 }
|
||
let ranked: [Int] = centers.indices.sorted { sizes[$0] > sizes[$1] }
|
||
for idx in ranked where !isGrass(centers[idx]) { return centers[idx] }
|
||
return centers[ranked[0]]
|
||
}
|
||
|
||
static func isGrass(_ c: KitColor) -> Bool {
|
||
let greenish = c.g > c.r * 1.25 && c.g > c.b * 1.25
|
||
return greenish && c.g > 0.25 && c.g < 0.75 && c.r < 0.45
|
||
}
|
||
|
||
// MARK: Image
|
||
|
||
static func loadImage(_ url: URL) -> CGImage? {
|
||
guard let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
|
||
let opts: [CFString: Any] = [
|
||
kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
|
||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||
kCGImageSourceThumbnailMaxPixelSize: 3000,
|
||
]
|
||
if let cg = CGImageSourceCreateThumbnailAtIndex(src, 0, opts as CFDictionary), max(cg.width, cg.height) >= 1500 { return cg }
|
||
var o2 = opts
|
||
o2[kCGImageSourceCreateThumbnailFromImageAlways] = true
|
||
return CGImageSourceCreateThumbnailAtIndex(src, 0, o2 as CFDictionary)
|
||
}
|
||
}
|