Full Bomba

This commit is contained in:
Basiek committed 2026-12-03 03:15:02 +01:00
commit 773f5dd5c3
33 files changed
+968

No files matched your search

+239
View File
@@ -0,0 +1,239 @@
"""Narzedzie deweloperskie: buduje wzorce rang i kolorow w katalogu templates/.
Wzorce powstaja ze zdjec w images/. Karty sa etykietowane na podstawie znanego
ukladu kart na tych trzech zdjeciach (ZONE_CARDS): dla kazdego miejsca przy stole
wiemy, jakie karty leza w danym obszarze, a konkretna karte rozpoznajemy po
liczbie oczek (karty z oczkami) albo po tym, ze to figura. Karty lezace obrotem
o 180 stopni sa wykrywane iteracyjnie - znaki rangi i koloru musza pasowac do
wzorcow, a nie do ich obrotu. Probki slabo pasujace do wzorcow sa odrzucane,
dzieki czemu zlepione karty (karta+karta, karta+zeton) nie psuja wzorcow.
Uruchomienie (z katalogu projektu):
python build_templates.py
"""
from __future__ import annotations
import collections
import os
import cv2
import numpy as np
import detector as det
from table import ZoneExtractor
# Karty lezace na zdjeciach testowych - kolejnosc w obrebie obszaru nie ma
# znaczenia, wazny jest zbior kart danego obszaru.
ZONE_CARDS = {
"test_table_01": {
"community_cards": [("8", "hearts"), ("5", "diamonds"), ("5", "spades"),
("7", "diamonds"), ("10", "spades")],
"player_one": [("4", "hearts"), ("K", "hearts")],
"player_two": [("8", "clubs"), ("9", "diamonds")],
"player_three": [("J", "spades"), ("K", "hearts")],
},
"test_table_02": {
"community_cards": [("2", "spades"), ("Q", "clubs"), ("4", "diamonds"),
("4", "clubs"), ("7", "spades")],
"player_one": [("6", "spades"), ("6", "hearts")],
"player_two": [("8", "spades"), ("J", "diamonds")],
"player_three": [("10", "hearts"), ("9", "hearts")],
},
"test_table_03": {
"community_cards": [("7", "spades"), ("Q", "clubs"), ("3", "spades"),
("10", "spades"), ("7", "clubs")],
"player_one": [("4", "clubs"), ("Q", "hearts")],
"player_two": [("K", "hearts"), ("3", "hearts")],
"player_three": [("J", "clubs"), ("3", "diamonds")],
},
}
SUIT_LABELS = {0: "hearts", 1: "spades", 2: "diamonds", 3: "clubs"}
PASSES = 4
MIN_FIT = 0.50
def score(first: np.ndarray | None, second: np.ndarray | None) -> float:
if first is None or second is None:
return -2.0
return float(cv2.matchTemplate(first, second, cv2.TM_CCOEFF_NORMED)[0, 0])
def best_score(glyph: np.ndarray | None, medoids: list[np.ndarray]) -> float:
return max((score(glyph, medoid) for medoid in medoids), default=-2.0)
def medoid(glyphs: list[np.ndarray]) -> np.ndarray:
"""Wzorzec najbardziej podobny do pozostalych znakow w grupie."""
if len(glyphs) == 1:
return glyphs[0]
return max(glyphs, key=lambda g: sum(score(g, other) for other in glyphs) / len(glyphs))
def k_medoids(glyphs: list[np.ndarray], k: int, iterations: int = 8):
"""Dzieli znaki na k grup; zwraca (srodki grup, grupy) od najliczniejszej."""
medoids = [glyphs[0]]
while len(medoids) < k:
weakest = min(glyphs, key=lambda g: best_score(g, medoids))
if any(weakest is medoid_glyph for medoid_glyph in medoids):
break
medoids.append(weakest)
for _ in range(iterations):
groups = [[] for _ in medoids]
for glyph in glyphs:
index = max(range(len(medoids)), key=lambda i: score(glyph, medoids[i]))
groups[index].append(glyph)
medoids = [medoid(group) if group else medoids[i] for i, group in enumerate(groups)]
groups = [[] for _ in medoids]
for glyph in glyphs:
index = max(range(len(medoids)), key=lambda i: score(glyph, medoids[i]))
groups[index].append(glyph)
order = sorted(range(len(medoids)), key=lambda i: -len(groups[i]))
return [medoids[i] for i in order], [groups[i] for i in order]
def collect_samples() -> list[dict]:
"""Karty z wycinkow wraz z etykieta odczytana ze znanego ukladu stojow."""
extractor = ZoneExtractor()
samples: list[dict] = []
for name, zones in ZONE_CARDS.items():
table = extractor.findTable(cv2.imread(f"images/{name}.jpg"))
for zone, crops in extractor.extract(table).items():
pool = list(ZONE_CARDS[name].get(zone, []))
# wycinki tego obszaru moga zawierac kilka kart (albo zetony)
for crop in crops:
for quad in det.candidate_quads(crop):
card = det.warp_card(crop, quad)
variants = (
det.index_glyphs(card),
det.index_glyphs(cv2.rotate(card, cv2.ROTATE_180)),
)
if all(rank is None or suit is None for rank, suit in variants):
continue
if det.is_court_card(card):
options = [c for c in pool if c[0] in ("J", "Q", "K")]
else:
pips = str(len(det.ink_blobs(card)))
options = [c for c in pool if c[0] == pips]
ranks = {c[0] for c in options}
suits = {c[1] for c in options}
samples.append({
"variants": variants,
"orientation": 0,
"rank": options[0][0] if len(ranks) == 1 else None,
"suit": options[0][1] if len(suits) == 1 else None,
"usable": bool(options),
})
if len(options) == 1:
pool.remove(options[0])
return samples
def main() -> None:
samples = collect_samples()
usable = [s for s in samples if s["usable"]]
print(f"kart znalezionych: {len(samples)}, z etykieta: {len(usable)}")
rank_medoids: dict[str, np.ndarray] = {}
suit_medoids: list[np.ndarray] = []
for _ in range(PASSES):
ranked = collections.defaultdict(list)
for sample in samples:
rank_glyph = sample["variants"][sample["orientation"]][0]
if sample["usable"] and sample["rank"] and rank_glyph is not None:
ranked[sample["rank"]].append(rank_glyph)
rank_medoids = {rank: medoid(glyphs) for rank, glyphs in ranked.items()}
suit_glyphs = [
sample["variants"][sample["orientation"]][1] for sample in usable
if sample["variants"][sample["orientation"]][1] is not None
]
suit_medoids, _ = k_medoids(suit_glyphs, 4)
# ulozenie karty: decyduje znak koloru (serce/pik/trefl sa
# niesymetryczne), a dla kara - znak rangi
flipped = 0
for sample in samples:
if sample["rank"] not in rank_medoids:
continue
fits = []
for orientation in (0, 1):
rank_glyph, suit_glyph = sample["variants"][orientation]
fits.append((best_score(suit_glyph, suit_medoids),
score(rank_glyph, rank_medoids[sample["rank"]])))
suit_delta = fits[0][0] - fits[1][0]
if abs(suit_delta) > 0.05:
choice = 0 if suit_delta > 0 else 1
else:
choice = 0 if fits[0][1] >= fits[1][1] else 1
flipped += choice != sample["orientation"]
sample["orientation"] = choice
print(f"kart obroconych w tej iteracji: {flipped}")
# odrzucamy probki, ktore nie pasuja do wzorcow swojej rangi/koloru
dropped = 0
for sample in samples:
if not sample["usable"]:
continue
rank_glyph, suit_glyph = sample["variants"][sample["orientation"]]
if sample["rank"] and score(rank_glyph, rank_medoids.get(sample["rank"])) < MIN_FIT:
sample["usable"], dropped = False, dropped + 1
elif sample["suit"] and best_score(suit_glyph, suit_medoids) < MIN_FIT:
sample["usable"], dropped = False, dropped + 1
print(f"odrzuconych probek: {dropped}")
os.makedirs("templates/ranks", exist_ok=True)
os.makedirs("templates/suits", exist_ok=True)
tiles: list[tuple[str, np.ndarray]] = []
for rank in det.RANKS:
medoid_glyph = rank_medoids.get(rank)
if medoid_glyph is None:
print(f"UWAGA: brak wzorca dla rangi {rank}")
continue
cv2.imwrite(f"templates/ranks/{rank}.png",
(np.clip(medoid_glyph, 0, 1) * 255).astype(np.uint8))
tiles.append((rank, medoid_glyph))
suit_glyphs = [
sample["variants"][sample["orientation"]][1] for sample in samples
if sample["usable"] and sample["variants"][sample["orientation"]][1] is not None
]
suit_medoids, suit_groups = k_medoids(suit_glyphs, 4)
for index, medoid_glyph in enumerate(suit_medoids):
label = SUIT_LABELS.get(index, f"suit{index}")
cv2.imwrite(f"templates/suits/{label}.png",
(np.clip(medoid_glyph, 0, 1) * 255).astype(np.uint8))
tiles.append((label, medoid_glyph))
print(f"kolor {label:9s}: {len(suit_groups[index])} probek (grupa {index})")
for rank in det.RANKS:
if rank not in rank_medoids:
continue
count = sum(1 for s in samples if s["usable"] and s["rank"] == rank)
print(f"ranga {rank:2s}: {count} probek")
scale, width, height = 4, 160, 190
sheet = np.full((height, width * len(tiles)), 30, np.uint8)
for index, (label, glyph) in enumerate(tiles):
big = cv2.resize((np.clip(glyph, 0, 1) * 255).astype(np.uint8),
(det.GLYPH_SIZE * scale, det.GLYPH_SIZE * scale),
interpolation=cv2.INTER_NEAREST)
x = index * width
sheet[8 * scale:8 * scale + big.shape[0], x:x + big.shape[1]] = big
cv2.putText(sheet, label, (x + 4, height - 8),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, 220, 2)
cv2.imwrite("templates/review.png", sheet)
print("\npodglad wzorcow: templates/review.png")
if __name__ == '__main__':
main()