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:
1 parent
3aa5bdef0e
commit
43405abd67
4 files changed
+121
-63
No files matched your search
@@ -993,6 +993,12 @@ final class AppState: ObservableObject {
|
||||
|
||||
// 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] {
|
||||
let done = jerseyDone[id] ?? []
|
||||
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 }
|
||||
var h: UInt64 = 0xcbf29ce484222325
|
||||
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>] }
|
||||
|
||||
@@ -23,75 +23,100 @@ struct JerseyRecognizer: Sendable {
|
||||
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
|
||||
let handler = VNImageRequestHandler(cgImage: cg, options: [:])
|
||||
try? handler.perform([humans])
|
||||
var people = (humans.results ?? []).map(\.boundingBox).filter { $0.height > 0.08 }
|
||||
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(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] = []
|
||||
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)
|
||||
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) }
|
||||
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))
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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) -> [JerseySuggestion] {
|
||||
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 } // 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 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 {
|
||||
out.append(JerseySuggestion(number: number, teamID: nil, code: nil, replacement: nil, confidence: confidence * 0.5,
|
||||
regions: [region], box: box, personArea: personArea))
|
||||
// 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
|
||||
}
|
||||
@@ -100,24 +125,33 @@ struct JerseyRecognizer: Sendable {
|
||||
|
||||
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.
|
||||
/// 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 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()
|
||||
req.recognitionLevel = .accurate
|
||||
req.usesLanguageCorrection = false
|
||||
req.recognitionLanguages = ["en-US"]
|
||||
req.minimumTextHeight = minTextHeight
|
||||
let handler = VNImageRequestHandler(cgImage: img, options: [:])
|
||||
try? handler.perform([req])
|
||||
try? VNImageRequestHandler(cgImage: img, options: [:]).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))
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -139,7 +173,7 @@ struct JerseyRecognizer: Sendable {
|
||||
|
||||
/// 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? {
|
||||
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,
|
||||
@@ -147,7 +181,8 @@ struct JerseyRecognizer: Sendable {
|
||||
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
|
||||
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))
|
||||
|
||||
@@ -87,7 +87,8 @@ struct IPTCInfoWindow: View {
|
||||
|
||||
// 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
|
||||
private var suggestionBar: some View {
|
||||
@@ -98,20 +99,31 @@ struct IPTCInfoWindow: View {
|
||||
Image(systemName: "person.text.rectangle").foregroundStyle(Color.accentColor)
|
||||
Text("Erkannt:").bold()
|
||||
Spacer()
|
||||
if open.count > 1 {
|
||||
Button("Alle annehmen") { accept(open) }
|
||||
if acceptable.count > 1 {
|
||||
Button("Alle annehmen") { accept(acceptable) }
|
||||
}
|
||||
Button("Neu erkennen") { state.recognizeJerseys([item], onlyNew: false) }
|
||||
.controlSize(.small)
|
||||
}
|
||||
ForEach(Array(open.enumerated()), id: \.element.id) { idx, s in
|
||||
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.replacement ?? "–").lineLimit(1)
|
||||
Text(s.regions.map(\.rawValue).joined(separator: "+") + " · \(Int(s.confidence * 100)) %")
|
||||
Text(s.replacement ?? "Nummer erkannt – kein Team/Code gefunden").lineLimit(1)
|
||||
.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)
|
||||
Spacer()
|
||||
if idx == 0 {
|
||||
if s.replacement == nil {
|
||||
EmptyView()
|
||||
} else if s.id == acceptable.first?.id {
|
||||
Button("Annehmen (⌘J)") { accept([s]) }
|
||||
.keyboardShortcut("j", modifiers: .command)
|
||||
.buttonStyle(.borderedProminent)
|
||||
|
||||
@@ -44,6 +44,10 @@ public struct JerseySuggestion: Codable, Hashable, Identifiable, Sendable {
|
||||
public var box: [Double] // x, y, w, h
|
||||
/// Person size in the frame (main subject first)
|
||||
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,
|
||||
regions: [JerseyRegion], box: [Double], personArea: Double) {
|
||||
|
||||
Reference in new issue
Block a user