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) // 1. people let humans = VNDetectHumanRectanglesRequest() humans.upperBodyOnly = false let handler = VNImageRequestHandler(cgImage: cg, options: [:]) try? handler.perform([humans]) var people = (humans.results ?? []).map(\.boundingBox).filter { $0.height > 0.08 } people.sort { $0.width * $0.height > $1.width * $1.height } people = Array(people.prefix(8)) var raw: [JerseySuggestion] = [] for p in people { // Vision: normalized, origin bottom-left → pixel rect, origin top-left let px = CGRect(x: p.minX * W, y: (1 - p.maxY) * H, width: p.width * W, height: p.height * H) let upperOnly = px.height / max(px.width, 1) < 1.3 var regions: [(JerseyRegion, CGRect)] = [] if useShirt { let top = upperOnly ? 0.25 : 0.12, bottom = upperOnly ? 1.0 : 0.56 regions.append((.shirt, CGRect(x: px.minX + px.width * 0.08, y: px.minY + px.height * top, width: px.width * 0.84, height: px.height * (bottom - top)))) } if useShorts && !upperOnly { regions.append((.shorts, CGRect(x: px.minX + px.width * 0.10, y: px.minY + px.height * 0.48, width: px.width * 0.80, height: px.height * 0.30))) } for (region, rect) in regions { let r = rect.intersection(CGRect(x: 0, y: 0, width: W, height: H)).integral guard r.width > 12, r.height > 12, let crop = cg.cropping(to: r) else { continue } let color = Self.dominantColor(crop) let team = color.flatMap { JerseyLogic.matchTeam(color: $0, region: region, teams: teams) } for hit in Self.readNumbers(crop) where hit.confidence >= minConfidence { // number box back to whole-image coordinates (top-left origin, normalized) let bx = (Double(r.minX) + Double(hit.box.minX) * Double(r.width)) / W let by = (Double(r.minY) + Double(1 - hit.box.maxY) * Double(r.height)) / H let bw = Double(hit.box.width) * Double(r.width) / W let bh = Double(hit.box.height) * Double(r.height) / H let box: [Double] = [bx, by, bw, bh] raw += suggestions(number: hit.number, team: team, confidence: hit.confidence, region: region, box: box, personArea: Double(p.width * p.height)) } } } // No person found (tight crop, blur): big numbers anywhere in the frame if people.isEmpty { for hit in Self.readNumbers(cg, minTextHeight: 0.04) where hit.confidence >= minConfidence + 0.1 { let box: [Double] = [Double(hit.box.minX), Double(1 - hit.box.maxY), Double(hit.box.width), Double(hit.box.height)] raw += suggestions(number: hit.number, team: nil, confidence: hit.confidence * 0.8, region: .image, box: box, personArea: 0) } } return JerseyLogic.merge(raw) } /// 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) -> [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 } // unknown team: only real players out.append(JerseySuggestion(number: number, teamID: t.id, code: code, replacement: rep, confidence: team == nil ? confidence * 0.6 : confidence, regions: [region], box: box, personArea: personArea)) } if out.isEmpty { out.append(JerseySuggestion(number: number, teamID: nil, code: nil, replacement: nil, confidence: confidence * 0.5, regions: [region], box: box, personArea: personArea)) } return out } // MARK: OCR struct NumberHit { let number: Int; let confidence: Double; let box: CGRect } static func readNumbers(_ image: CGImage, minTextHeight: Float = 0.12) -> [NumberHit] { // Small crops (front numbers, far away players) are upscaled – Vision reads them much better. var img = image let longEdge = max(image.width, image.height) if longEdge < 420, let up = upscale(image, factor: min(4, 420.0 / Double(longEdge))) { img = up } let req = VNRecognizeTextRequest() req.recognitionLevel = .accurate req.usesLanguageCorrection = false req.recognitionLanguages = ["en-US"] req.minimumTextHeight = minTextHeight let handler = VNImageRequestHandler(cgImage: img, options: [:]) try? handler.perform([req]) var hits: [NumberHit] = [] for obs in req.results ?? [] { for cand in obs.topCandidates(3) { if let n = JerseyLogic.parseNumber(cand.string) { hits.append(NumberHit(number: n, confidence: Double(cand.confidence), box: obs.boundingBox)) 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) -> 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 = CGRect(x: w * 0.2, y: h * 0.15, width: w * 0.6, height: h * 0.7).integral 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) } }