Trikot-Erkennung verbessert: OCR auf ganzer Person + ganzem Bild, kleinere Nummern (Brust/Hose), Nummern in Text ('HUTH 10'), Teamfarbe direkt um die Nummer; erkannte Nummern ohne Team/Code sichtbar, gemessene Farbe angezeigt; Cache neu

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-04 01:26:42 +00:00
1 parent 3aa5bdef0e
commit 43405abd67
4 files changed
+121 -63

No files matched your search

+8 -1
View File
@@ -993,6 +993,12 @@ final class AppState: ObservableObject {
// MARK: - Jersey number recognition // MARK: - Jersey number recognition
/// Everything that was read for an image, including numbers without team/code (IPTC window).
func allOpenSuggestions(for id: String) -> [JerseySuggestion] {
let done = jerseyDone[id] ?? []
return (jerseySuggestions[id] ?? []).filter { !done.contains($0.id) }
}
func openSuggestions(for id: String) -> [JerseySuggestion] { func openSuggestions(for id: String) -> [JerseySuggestion] {
let done = jerseyDone[id] ?? [] let done = jerseyDone[id] ?? []
return (jerseySuggestions[id] ?? []).filter { !done.contains($0.id) && $0.replacement != nil } return (jerseySuggestions[id] ?? []).filter { !done.contains($0.id) && $0.replacement != nil }
@@ -1009,7 +1015,8 @@ final class AppState: ObservableObject {
guard let f = folder else { return nil } guard let f = folder else { return nil }
var h: UInt64 = 0xcbf29ce484222325 var h: UInt64 = 0xcbf29ce484222325
for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 } for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
return MetadataCache.directory.appendingPathComponent("jersey-" + String(h, radix: 16) + ".json") // "jersey2": results of the improved recognizer (older caches are ignored → recognized again)
return MetadataCache.directory.appendingPathComponent("jersey2-" + String(h, radix: 16) + ".json")
} }
private struct JerseyCache: Codable { var suggestions: [String: [JerseySuggestion]]; var done: [String: Set<String>] } private struct JerseyCache: Codable { var suggestions: [String: [JerseySuggestion]]; var done: [String: Set<String>] }
@@ -23,75 +23,100 @@ struct JerseyRecognizer: Sendable {
func recognize(url: URL) -> [JerseySuggestion] { func recognize(url: URL) -> [JerseySuggestion] {
guard let cg = Self.loadImage(url) else { return [] } guard let cg = Self.loadImage(url) else { return [] }
let W = Double(cg.width), H = Double(cg.height) let W = Double(cg.width), H = Double(cg.height)
let full = CGRect(x: 0, y: 0, width: W, height: H)
// 1. people // 1. people
let humans = VNDetectHumanRectanglesRequest() let humans = VNDetectHumanRectanglesRequest()
humans.upperBodyOnly = false humans.upperBodyOnly = false
let handler = VNImageRequestHandler(cgImage: cg, options: [:]) try? VNImageRequestHandler(cgImage: cg, options: [:]).perform([humans])
try? handler.perform([humans]) var people = (humans.results ?? []).map(\.boundingBox).filter { $0.height > 0.06 }
var people = (humans.results ?? []).map(\.boundingBox).filter { $0.height > 0.08 }
people.sort { $0.width * $0.height > $1.width * $1.height } people.sort { $0.width * $0.height > $1.width * $1.height }
people = Array(people.prefix(8)) 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 raw: [JerseySuggestion] = []
for p in people { var hitBoxes: [CGRect] = [] // to skip duplicates from the full-frame pass
// 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) // 2. OCR on each whole person (padded, upscaled) – the number can be anywhere on shirt or shorts
let upperOnly = px.height / max(px.width, 1) < 1.3 for (pi, pr) in personRects.enumerated() {
var regions: [(JerseyRegion, CGRect)] = [] let padded = pr.insetBy(dx: -pr.width * 0.06, dy: -pr.height * 0.03).intersection(full).integral
if useShirt { guard padded.width > 16, padded.height > 16, let crop = cg.cropping(to: padded) else { continue }
let top = upperOnly ? 0.25 : 0.12, bottom = upperOnly ? 1.0 : 0.56 for hit in Self.readNumbers(crop, minTextHeight: 0.025, upscaleTo: 1400) {
regions.append((.shirt, CGRect(x: px.minX + px.width * 0.08, y: px.minY + px.height * top, let nb = Self.toPixels(hit.box, in: padded) // number box in image pixels
width: px.width * 0.84, height: px.height * (bottom - top)))) // where on the body? (relative to the person box, 0 = head, 1 = feet)
} let yRel = (nb.midY - pr.minY) / max(pr.height, 1)
if useShorts && !upperOnly { let upperOnly = pr.height / max(pr.width, 1) < 1.3
regions.append((.shorts, CGRect(x: px.minX + px.width * 0.10, y: px.minY + px.height * 0.48, let region: JerseyRegion = upperOnly || yRel < 0.52 ? .shirt : .shorts
width: px.width * 0.80, height: px.height * 0.30))) if region == .shirt && !useShirt { continue }
} if region == .shorts && !useShorts { continue }
for (region, rect) in regions { if !upperOnly && (yRel < 0.08 || yRel > 0.9) { continue } // head / socks: ads, boards
let r = rect.intersection(CGRect(x: 0, y: 0, width: W, height: H)).integral guard hit.confidence >= minConfidence else { continue }
guard r.width > 12, r.height > 12, let crop = cg.cropping(to: r) else { continue } let color = Self.kitColor(around: nb, in: cg)
let color = Self.dominantColor(crop)
let team = color.flatMap { JerseyLogic.matchTeam(color: $0, region: region, teams: teams) } let team = color.flatMap { JerseyLogic.matchTeam(color: $0, region: region, teams: teams) }
for hit in Self.readNumbers(crop) where hit.confidence >= minConfidence { hitBoxes.append(nb)
// number box back to whole-image coordinates (top-left origin, normalized) raw += suggestions(number: hit.number, team: team, confidence: hit.confidence, region: region,
let bx = (Double(r.minX) + Double(hit.box.minX) * Double(r.width)) / W box: Self.normalized(nb, W, H), personArea: Double(people[pi].width * people[pi].height),
let by = (Double(r.minY) + Double(1 - hit.box.maxY) * Double(r.height)) / H color: color)
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 { // 3. whole frame (people not detected: tight crops, motion blur, partly hidden)
for hit in Self.readNumbers(cg, minTextHeight: 0.04) where hit.confidence >= minConfidence + 0.1 { for hit in Self.readNumbers(cg, minTextHeight: 0.012, upscaleTo: 0) 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)] let nb = Self.toPixels(hit.box, in: full)
raw += suggestions(number: hit.number, team: nil, confidence: hit.confidence * 0.8, if hitBoxes.contains(where: { $0.intersects(nb) }) { continue }
region: .image, box: box, personArea: 0) // 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) 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). /// 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, private func suggestions(number: Int, team: JerseyTeam?, confidence: Double, region: JerseyRegion,
box: [Double], personArea: Double) -> [JerseySuggestion] { box: [Double], personArea: Double, color: KitColor?) -> [JerseySuggestion] {
let candidates = team.map { [$0] } ?? teams let candidates = team.map { [$0] } ?? teams
var out: [JerseySuggestion] = [] var out: [JerseySuggestion] = []
for t in candidates { for t in candidates {
let code = t.prefix + String(number) let code = t.prefix + String(number)
let rep = codes.lookup(code) let rep = codes.lookup(code)
if team == nil && rep == nil { continue } // unknown team: only real players if team == nil && rep == nil { continue }
out.append(JerseySuggestion(number: number, teamID: t.id, code: code, replacement: rep, var s = JerseySuggestion(number: number, teamID: t.id, code: code, replacement: rep,
confidence: team == nil ? confidence * 0.6 : confidence, confidence: team == nil ? confidence * 0.6 : confidence,
regions: [region], box: box, personArea: personArea)) regions: [region], box: box, personArea: personArea)
s.measuredColor = color
s.teamCertain = team != nil
out.append(s)
} }
if out.isEmpty { if out.isEmpty {
out.append(JerseySuggestion(number: number, teamID: nil, code: nil, replacement: nil, confidence: confidence * 0.5, // number read, but no team/code → still shown (as "#10 – kein Code"), so you see it was found
regions: [region], box: box, personArea: personArea)) 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 return out
} }
@@ -100,24 +125,33 @@ struct JerseyRecognizer: Sendable {
struct NumberHit { let number: Int; let confidence: Double; let box: CGRect } struct NumberHit { let number: Int; let confidence: Double; let box: CGRect }
static func readNumbers(_ image: CGImage, minTextHeight: Float = 0.12) -> [NumberHit] { /// OCR for 1–2 digit numbers. `upscaleTo`: small crops are enlarged to this long edge (Vision reads
// Small crops (front numbers, far away players) are upscaled – Vision reads them much better. /// small numbers much better), 0 = no upscaling.
static func readNumbers(_ image: CGImage, minTextHeight: Float, upscaleTo: Int) -> [NumberHit] {
var img = image var img = image
let longEdge = max(image.width, image.height) let longEdge = max(image.width, image.height)
if longEdge < 420, let up = upscale(image, factor: min(4, 420.0 / Double(longEdge))) { img = up } if upscaleTo > 0, longEdge < upscaleTo, let up = upscale(image, factor: min(4, Double(upscaleTo) / Double(longEdge))) { img = up }
let req = VNRecognizeTextRequest() let req = VNRecognizeTextRequest()
req.recognitionLevel = .accurate req.recognitionLevel = .accurate
req.usesLanguageCorrection = false req.usesLanguageCorrection = false
req.recognitionLanguages = ["en-US"] req.recognitionLanguages = ["en-US"]
req.minimumTextHeight = minTextHeight req.minimumTextHeight = minTextHeight
let handler = VNImageRequestHandler(cgImage: img, options: [:]) try? VNImageRequestHandler(cgImage: img, options: [:]).perform([req])
try? handler.perform([req])
var hits: [NumberHit] = [] var hits: [NumberHit] = []
for obs in req.results ?? [] { for obs in req.results ?? [] {
for cand in obs.topCandidates(3) { var found = false
if let n = JerseyLogic.parseNumber(cand.string) { for cand in obs.topCandidates(3) where !found {
hits.append(NumberHit(number: n, confidence: Double(cand.confidence), box: obs.boundingBox)) // 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 break
} }
} }
@@ -139,7 +173,7 @@ struct JerseyRecognizer: Sendable {
/// Dominant color of the kit area: 24×24 thumbnail, simple k-means (k = 3), largest cluster /// Dominant color of the kit area: 24×24 thumbnail, simple k-means (k = 3), largest cluster
/// that is not grass green or skin-ish. /// that is not grass green or skin-ish.
static func dominantColor(_ img: CGImage) -> KitColor? { static func dominantColor(_ img: CGImage, centerOnly: Bool = true) -> KitColor? {
let n = 24 let n = 24
var pixels = [UInt8](repeating: 0, count: n * n * 4) var pixels = [UInt8](repeating: 0, count: n * n * 4)
guard let ctx = CGContext(data: &pixels, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n * 4, guard let ctx = CGContext(data: &pixels, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n * 4,
@@ -147,7 +181,8 @@ struct JerseyRecognizer: Sendable {
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
// central part only (less background) // central part only (less background)
let w = Double(img.width), h = Double(img.height) 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 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 } guard let center = img.cropping(to: inner) else { return nil }
ctx.interpolationQuality = .medium ctx.interpolationQuality = .medium
ctx.draw(center, in: CGRect(x: 0, y: 0, width: n, height: n)) ctx.draw(center, in: CGRect(x: 0, y: 0, width: n, height: n))
+18 -6
View File
@@ -87,7 +87,8 @@ struct IPTCInfoWindow: View {
// MARK: Jersey suggestions // MARK: Jersey suggestions
private var openSuggestions: [JerseySuggestion] { item.map { state.openSuggestions(for: $0.id) } ?? [] } private var openSuggestions: [JerseySuggestion] { item.map { state.allOpenSuggestions(for: $0.id) } ?? [] }
private var acceptable: [JerseySuggestion] { openSuggestions.filter { $0.replacement != nil } }
@ViewBuilder @ViewBuilder
private var suggestionBar: some View { private var suggestionBar: some View {
@@ -98,20 +99,31 @@ struct IPTCInfoWindow: View {
Image(systemName: "person.text.rectangle").foregroundStyle(Color.accentColor) Image(systemName: "person.text.rectangle").foregroundStyle(Color.accentColor)
Text("Erkannt:").bold() Text("Erkannt:").bold()
Spacer() Spacer()
if open.count > 1 { if acceptable.count > 1 {
Button("Alle annehmen") { accept(open) } Button("Alle annehmen") { accept(acceptable) }
} }
Button("Neu erkennen") { state.recognizeJerseys([item], onlyNew: false) } Button("Neu erkennen") { state.recognizeJerseys([item], onlyNew: false) }
.controlSize(.small) .controlSize(.small)
} }
ForEach(Array(open.enumerated()), id: \.element.id) { idx, s in ForEach(Array(open.enumerated()), id: \.element.id) { idx, s in
HStack(spacing: 8) { HStack(spacing: 8) {
if let c = s.measuredColor {
RoundedRectangle(cornerRadius: 3)
.fill(Color(red: c.r, green: c.g, blue: c.b))
.frame(width: 14, height: 14)
.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.secondary))
.help("Gemessene Trikotfarbe um die Nummer – passt sie nicht zum Team, Farbe in „Trikot-Erkennung einrichten“ anpassen")
}
Text(s.code ?? "#\(s.number)").font(.system(.body, design: .monospaced)).bold() Text(s.code ?? "#\(s.number)").font(.system(.body, design: .monospaced)).bold()
Text(s.replacement ?? "–").lineLimit(1) Text(s.replacement ?? "Nummer erkannt – kein Team/Code gefunden").lineLimit(1)
Text(s.regions.map(\.rawValue).joined(separator: "+") + " · \(Int(s.confidence * 100)) %") .foregroundStyle(s.replacement == nil ? .secondary : .primary)
Text(s.regions.map(\.rawValue).joined(separator: "+") + " · \(Int(s.confidence * 100)) %"
+ (s.teamCertain == false ? " · Team unsicher" : ""))
.font(.caption).foregroundStyle(.secondary) .font(.caption).foregroundStyle(.secondary)
Spacer() Spacer()
if idx == 0 { if s.replacement == nil {
EmptyView()
} else if s.id == acceptable.first?.id {
Button("Annehmen (⌘J)") { accept([s]) } Button("Annehmen (⌘J)") { accept([s]) }
.keyboardShortcut("j", modifiers: .command) .keyboardShortcut("j", modifiers: .command)
.buttonStyle(.borderedProminent) .buttonStyle(.borderedProminent)
@@ -44,6 +44,10 @@ public struct JerseySuggestion: Codable, Hashable, Identifiable, Sendable {
public var box: [Double] // x, y, w, h public var box: [Double] // x, y, w, h
/// Person size in the frame (main subject first) /// Person size in the frame (main subject first)
public var personArea: Double public var personArea: Double
/// Kit color measured around the number (shown in the IPTC window to calibrate the team colors)
public var measuredColor: KitColor?
/// false = team guessed (color matched no team clearly) – both teams' players are suggested
public var teamCertain: Bool?
public init(number: Int, teamID: UUID?, code: String?, replacement: String?, confidence: Double, public init(number: Int, teamID: UUID?, code: String?, replacement: String?, confidence: Double,
regions: [JerseyRegion], box: [Double], personArea: Double) { regions: [JerseyRegion], box: [Double], personArea: Double) {