Full Bomba
This commit is contained in:
commit
773f5dd5c3
33 files changed
+968
No files matched your search
+443
@@ -0,0 +1,443 @@
|
||||
"""Rozpoznawanie kart na wycinkach zwracanych przez table.ZoneExtractor.
|
||||
|
||||
ZoneExtractor.extract() zwraca liste wycinkow dla kazdego miejsca przy stole.
|
||||
Wycinki nie sa pojedynczymi kartami: czasami dwie karty albo karta i zeton
|
||||
sa zlepione w jedna skladowa. CardDetector:
|
||||
|
||||
1. wycina z wycinka powierzchnie kart (maska "papieru" - jasne, malo nasycone
|
||||
piksele; zetony tez ja maja, wiec sama maska nie wystarcza),
|
||||
2. rozdziela zlepione obiekty (erozja + rozrost nasion, pozniej rekurencyjnie),
|
||||
3. zostawia tylko obiekty o ksztalcie karty (prostokat o proporcjach karty),
|
||||
4. prostuje perspektywe karty do stalego rozmiaru,
|
||||
5. czyta indeks z lewego gornego rogu (ranga nad kolorem) i porownuje go
|
||||
ze wzorcami z katalogu templates/.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
CARD_W = 200
|
||||
CARD_H = 280
|
||||
GLYPH_SIZE = 32
|
||||
GLYPH_WINDOW = 36 # okno znaku indeksu w pikselach obrazu karty
|
||||
|
||||
# maska papieru: karta jest jasna i malo nasycona (zeton bialy tez)
|
||||
PAPER_VALUE_MIN = 155
|
||||
PAPER_SATURATION_MAX = 95
|
||||
INK_MAX_GREY = 170
|
||||
|
||||
# karta wypelnia swoj prostokat; zeton jest okragly (extent ~0.78)
|
||||
CARD_ASPECT_MIN = 0.58
|
||||
CARD_ASPECT_MAX = 0.85
|
||||
CARD_EXTENT_MIN = 0.90
|
||||
CARD_AREA_MIN = 900
|
||||
|
||||
# indeks karty: znaki leza w lewej kolumnie, ranga nad kolorem
|
||||
INDEX_COLUMN = 0.12 # szerokosc kolumny indeksu (ulamek szerokosci karty)
|
||||
INDEX_HEIGHT = 0.40 # indeks konczy sie w gornej czesci karty
|
||||
GLYPH_HEIGHT_MIN = 0.03 # pojedynczy znak jest nizszy niz 16% karty
|
||||
GLYPH_HEIGHT_MAX = 0.16
|
||||
BORDER_PX = 4 # margines obrazu karty odcinany przed szukaniem indeksu
|
||||
|
||||
RANKS = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
|
||||
SUITS = ("spades", "hearts", "diamonds", "clubs")
|
||||
SUIT_SYMBOLS = {"spades": "♠", "hearts": "♥", "diamonds": "♦", "clubs": "♣"}
|
||||
|
||||
UNKNOWN = "?"
|
||||
|
||||
_KERNEL3 = np.ones((3, 3), np.uint8)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Card:
|
||||
"""Rozpoznana karta. rank/suit rowne '?' gdy rozpoznanie sie nie udalo."""
|
||||
|
||||
rank: str
|
||||
suit: str
|
||||
score: float = 0.0
|
||||
|
||||
@property
|
||||
def known(self) -> bool:
|
||||
return self.rank != UNKNOWN and self.suit != UNKNOWN
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.rank}{SUIT_SYMBOLS.get(self.suit, '')}"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# segmentacja wycinka
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def paper_mask(image: np.ndarray) -> np.ndarray:
|
||||
"""Maska jasnych, malo nasyconych pikseli - taka powierzchnie ma karta."""
|
||||
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
|
||||
return cv2.inRange(
|
||||
hsv,
|
||||
np.array([0, 0, PAPER_VALUE_MIN]),
|
||||
np.array([180, PAPER_SATURATION_MAX, 255]),
|
||||
)
|
||||
|
||||
|
||||
def _order_quad(points: np.ndarray) -> np.ndarray:
|
||||
"""Ustawia cztery wierzcholki jako lewy-gorny, prawy-gorny, prawy-dolny, lewy-dolny."""
|
||||
sums = points.sum(axis=1)
|
||||
diffs = np.diff(points, axis=1).ravel()
|
||||
return np.array(
|
||||
[
|
||||
points[np.argmin(sums)],
|
||||
points[np.argmin(diffs)],
|
||||
points[np.argmax(sums)],
|
||||
points[np.argmax(diffs)],
|
||||
],
|
||||
np.float32,
|
||||
)
|
||||
|
||||
|
||||
def rect_stats(mask: np.ndarray) -> dict | None:
|
||||
"""Opis konturu maski: pole, obrocony prostokat, wypelnienie prostokata."""
|
||||
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
if not contours:
|
||||
return None
|
||||
|
||||
contour = max(contours, key=cv2.contourArea)
|
||||
area = cv2.contourArea(contour)
|
||||
if area <= 0:
|
||||
return None
|
||||
|
||||
rect = cv2.minAreaRect(contour)
|
||||
width, height = rect[1]
|
||||
if min(width, height) < 5:
|
||||
return None
|
||||
|
||||
return {
|
||||
"rect": rect,
|
||||
"area": area,
|
||||
"aspect": min(width, height) / max(width, height),
|
||||
"extent": area / (width * height),
|
||||
}
|
||||
|
||||
|
||||
def _is_card_shape(stats: dict | None, min_area: float) -> bool:
|
||||
return (
|
||||
stats is not None
|
||||
and stats["area"] >= min_area
|
||||
and CARD_ASPECT_MIN <= stats["aspect"] <= CARD_ASPECT_MAX
|
||||
and stats["extent"] >= CARD_EXTENT_MIN
|
||||
)
|
||||
|
||||
|
||||
def _grow_labels(seeds: np.ndarray, allowed: np.ndarray) -> np.ndarray:
|
||||
"""Rozpycha etykiety nasion na caly dopuszczalny obszar (bez nadpisywania)."""
|
||||
labels = seeds.copy()
|
||||
while True:
|
||||
grown = cv2.dilate(labels, _KERNEL3)
|
||||
updated = np.where((labels == 0) & allowed, grown, labels)
|
||||
if np.array_equal(updated, labels):
|
||||
return labels
|
||||
labels = updated
|
||||
|
||||
|
||||
def split_component(component: np.ndarray, max_iterations: int = 40) -> list[np.ndarray]:
|
||||
"""Rozdziela zlepione obiekty (karta+karta, karta+zeton) na osobne maski."""
|
||||
area = cv2.countNonZero(component)
|
||||
eroded = component.copy()
|
||||
|
||||
for _ in range(max_iterations):
|
||||
eroded = cv2.erode(eroded, _KERNEL3)
|
||||
count, labels, stats, _ = cv2.connectedComponentsWithStats(eroded)
|
||||
seeds = [
|
||||
i
|
||||
for i in range(1, count)
|
||||
if stats[i, cv2.CC_STAT_AREA] > 0.06 * area
|
||||
]
|
||||
if len(seeds) >= 2:
|
||||
markers = np.zeros(component.shape, np.uint8)
|
||||
for marker, seed in enumerate(seeds, start=1):
|
||||
markers[labels == seed] = marker
|
||||
grown = _grow_labels(markers, component > 0)
|
||||
return [
|
||||
(((component > 0) & (grown == marker)).astype(np.uint8)) * 255
|
||||
for marker in range(1, len(seeds) + 1)
|
||||
]
|
||||
if cv2.countNonZero(eroded) == 0:
|
||||
break
|
||||
|
||||
return [component]
|
||||
|
||||
|
||||
def card_parts(component: np.ndarray, min_area: float, depth: int = 0) -> list[np.ndarray]:
|
||||
"""Zwraca czesci skladowej, ktore wygladaja jak pojedyncze karty."""
|
||||
if _is_card_shape(rect_stats(component), min_area):
|
||||
return [component]
|
||||
if depth >= 3:
|
||||
return []
|
||||
|
||||
parts = split_component(component)
|
||||
if len(parts) < 2:
|
||||
return []
|
||||
|
||||
cards: list[np.ndarray] = []
|
||||
for part in parts:
|
||||
cards.extend(card_parts(part, min_area, depth + 1))
|
||||
return cards
|
||||
|
||||
|
||||
def candidate_quads(crop: np.ndarray) -> list[np.ndarray]:
|
||||
"""Znajduje czworokaty kart w wycinku; kolejnosc czytania: od gory, od lewej."""
|
||||
mask = paper_mask(crop)
|
||||
height, width = mask.shape
|
||||
min_area = max(CARD_AREA_MIN, 0.002 * height * width)
|
||||
|
||||
count, labels, stats, _ = cv2.connectedComponentsWithStats(mask)
|
||||
quads: list[np.ndarray] = []
|
||||
for i in range(1, count):
|
||||
if stats[i, cv2.CC_STAT_AREA] < min_area:
|
||||
continue
|
||||
component = ((labels == i).astype(np.uint8)) * 255
|
||||
for part in card_parts(component, min_area):
|
||||
part_stats = rect_stats(part)
|
||||
if part_stats is None:
|
||||
continue
|
||||
quads.append(_order_quad(cv2.boxPoints(part_stats["rect"])))
|
||||
|
||||
quads.sort(key=lambda quad: (round(quad[:, 1].mean() / (CARD_H * 0.5)), quad[:, 0].mean()))
|
||||
return quads
|
||||
|
||||
|
||||
def warp_card(crop: np.ndarray, quad: np.ndarray) -> np.ndarray:
|
||||
"""Prostuje karte do CARD_W x CARD_H (dluzszy bok karty w pionie)."""
|
||||
box = quad
|
||||
if np.linalg.norm(box[1] - box[0]) > np.linalg.norm(box[3] - box[0]):
|
||||
box = np.array([box[1], box[2], box[3], box[0]], np.float32)
|
||||
|
||||
destination = np.array(
|
||||
[[0, 0], [CARD_W - 1, 0], [CARD_W - 1, CARD_H - 1], [0, CARD_H - 1]], np.float32
|
||||
)
|
||||
matrix = cv2.getPerspectiveTransform(box, destination)
|
||||
return cv2.warpPerspective(crop, matrix, (CARD_W, CARD_H))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# odczyt indeksu karty
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _ink_threshold(grey: np.ndarray) -> float:
|
||||
"""Prog tuszu wyznaczany lokalnie (Otsu) w okolicy indeksu karty."""
|
||||
region = grey[0:int(0.42 * CARD_H), 0:int(0.32 * CARD_W)]
|
||||
value, _ = cv2.threshold(region, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
|
||||
return float(min(max(value, 90), INK_MAX_GREY + 40))
|
||||
|
||||
|
||||
def _normalize(ink: np.ndarray, glyphs: list[dict]) -> np.ndarray:
|
||||
"""Wyciaga znak (lub znaki) w stalym oknie wokol jego srodka i skaluje.
|
||||
|
||||
Stale okno (a nie dopasowanie do obrysu) zachowuje proporcje znaku, dzieki
|
||||
czemu J, Q i K nie upodobniaja sie do siebie. Okno jest wysrodkowane na
|
||||
srodku ciezkosci tuszu, wiec przesuniecia karty nie przeszkadzaja.
|
||||
"""
|
||||
x0 = min(g["x"] for g in glyphs)
|
||||
y0 = min(g["y"] for g in glyphs)
|
||||
x1 = max(g["x"] + g["w"] for g in glyphs)
|
||||
y1 = max(g["y"] + g["h"] for g in glyphs)
|
||||
patch = ink[y0:y1, x0:x1].astype(np.float32)
|
||||
return cv2.resize(patch, (GLYPH_SIZE, GLYPH_SIZE), interpolation=cv2.INTER_AREA)
|
||||
|
||||
|
||||
def _index_candidates(ink: np.ndarray) -> list[dict]:
|
||||
"""Plamy tuszu, ktore moga byc znakami indeksu (bez oczek, ramek i tla)."""
|
||||
count, _, stats, _ = cv2.connectedComponentsWithStats(ink)
|
||||
candidates = []
|
||||
for i in range(1, count):
|
||||
x, y = int(stats[i, cv2.CC_STAT_LEFT]), int(stats[i, cv2.CC_STAT_TOP])
|
||||
w, h = int(stats[i, cv2.CC_STAT_WIDTH]), int(stats[i, cv2.CC_STAT_HEIGHT])
|
||||
area = int(stats[i, cv2.CC_STAT_AREA])
|
||||
if area < 25 or x > 0.30 * CARD_W or y > INDEX_HEIGHT * CARD_H:
|
||||
continue
|
||||
if w > INDEX_COLUMN * CARD_W:
|
||||
continue
|
||||
if not (GLYPH_HEIGHT_MIN * CARD_H <= h <= 0.30 * CARD_H):
|
||||
continue
|
||||
candidates.append({"x": x, "y": y, "w": w, "h": h, "area": area})
|
||||
return candidates
|
||||
|
||||
|
||||
def _cut_glyph_pair(ink: np.ndarray, glyph: dict) -> tuple[dict, dict]:
|
||||
"""Dzieli zlepiona ranga i kolor w najwezszym miejscu (najmniej tuszu w rzedzie)."""
|
||||
x, y, w, h = glyph["x"], glyph["y"], glyph["w"], glyph["h"]
|
||||
rows = ink[y:y + h, x:x + w].sum(axis=1)
|
||||
low, high = int(0.25 * h), int(0.80 * h)
|
||||
cut = low + int(np.argmin(rows[low:high])) if high > low else h // 2
|
||||
cut = max(4, min(h - 4, cut))
|
||||
return (
|
||||
{"x": x, "y": y, "w": w, "h": cut},
|
||||
{"x": x, "y": y + cut, "w": w, "h": h - cut},
|
||||
)
|
||||
|
||||
|
||||
def index_glyphs(card: np.ndarray) -> tuple[np.ndarray | None, np.ndarray | None]:
|
||||
"""Zwraca (znak rangi, znak koloru) z lewego gornego indeksu karty."""
|
||||
grey = cv2.cvtColor(card, cv2.COLOR_BGR2GRAY)
|
||||
ink = (grey < _ink_threshold(grey)).astype(np.uint8)
|
||||
ink = cv2.morphologyEx(ink, cv2.MORPH_CLOSE, _KERNEL3)
|
||||
# krawedz karty (i cien za nia) nie moze sklejac sie ze znakami indeksu
|
||||
ink[:BORDER_PX, :] = ink[-BORDER_PX:, :] = 0
|
||||
ink[:, :BORDER_PX] = ink[:, -BORDER_PX:] = 0
|
||||
|
||||
candidates = _index_candidates(ink)
|
||||
if not candidates:
|
||||
return None, None
|
||||
|
||||
left = min(glyph["x"] for glyph in candidates)
|
||||
column = [g for g in candidates if g["x"] <= left + INDEX_COLUMN * CARD_W]
|
||||
column.sort(key=lambda g: (g["y"], g["x"]))
|
||||
|
||||
rank = column[0]
|
||||
if rank["h"] > GLYPH_HEIGHT_MAX * CARD_H:
|
||||
rank_glyph, suit_glyph = _cut_glyph_pair(ink, rank)
|
||||
return _normalize(ink, [rank_glyph]), _normalize(ink, [suit_glyph])
|
||||
|
||||
rank_row = [g for g in column if abs(g["y"] - rank["y"]) <= 0.6 * rank["h"]]
|
||||
rest = [g for g in column if g not in rank_row]
|
||||
if not rest:
|
||||
return _normalize(ink, rank_row), None
|
||||
|
||||
suit = min(rest, key=lambda g: (g["y"], g["x"]))
|
||||
suit_row = [g for g in rest if abs(g["y"] - suit["y"]) <= 0.6 * suit["h"]]
|
||||
return _normalize(ink, rank_row), _normalize(ink, suit_row)
|
||||
|
||||
|
||||
def ink_blobs(card: np.ndarray, min_area: int = 80) -> list[int]:
|
||||
"""Pola plam tuszu na karcie (bez marginesu i obu indeksow), malejaco."""
|
||||
grey = cv2.cvtColor(card, cv2.COLOR_BGR2GRAY)
|
||||
ink = (grey < INK_MAX_GREY).astype(np.uint8)
|
||||
|
||||
margin = int(0.06 * min(CARD_W, CARD_H))
|
||||
ink[:margin, :] = ink[-margin:, :] = ink[:, :margin] = ink[:, -margin:] = 0
|
||||
ink[0:int(0.36 * CARD_H), 0:int(0.22 * CARD_W)] = 0
|
||||
ink[int(0.64 * CARD_H):, int(0.78 * CARD_W):] = 0
|
||||
|
||||
count, _, stats, _ = cv2.connectedComponentsWithStats(ink)
|
||||
return sorted(
|
||||
(int(stats[i, cv2.CC_STAT_AREA]) for i in range(1, count)
|
||||
if stats[i, cv2.CC_STAT_AREA] >= min_area),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def is_court_card(card: np.ndarray) -> bool:
|
||||
"""Figura (J/Q/K) - na srodku karty jest duzy rysunek zamiast oczek."""
|
||||
blobs = ink_blobs(card)
|
||||
return bool(blobs) and blobs[0] > 0.045 * CARD_W * CARD_H
|
||||
|
||||
|
||||
def rank_from_pips(card: np.ndarray) -> str | None:
|
||||
"""Ranga z liczby oczek - awaryjnie, gdy wzorzec rangi nie pasuje."""
|
||||
blobs = ink_blobs(card)
|
||||
if not blobs or blobs[0] > 0.045 * CARD_W * CARD_H:
|
||||
return None
|
||||
if len(blobs) == 1:
|
||||
return "A" if blobs[0] > 0.015 * CARD_W * CARD_H else None
|
||||
if 2 <= len(blobs) <= 10:
|
||||
return str(len(blobs))
|
||||
return None
|
||||
|
||||
|
||||
def _match(glyph: np.ndarray | None, templates: dict[str, np.ndarray]) -> tuple[str, float]:
|
||||
if glyph is None or not templates:
|
||||
return UNKNOWN, -2.0
|
||||
|
||||
best_name, best_score = UNKNOWN, -2.0
|
||||
for name, template in templates.items():
|
||||
score = float(cv2.matchTemplate(glyph, template, cv2.TM_CCOEFF_NORMED)[0, 0])
|
||||
if score > best_score:
|
||||
best_name, best_score = name, score
|
||||
return best_name, best_score
|
||||
|
||||
|
||||
def _load_templates(directory: str, names: tuple[str, ...]) -> dict[str, np.ndarray]:
|
||||
templates: dict[str, np.ndarray] = {}
|
||||
for name in names:
|
||||
path = os.path.join(directory, f"{name}.png")
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
|
||||
if image is None:
|
||||
continue
|
||||
image = cv2.resize(image, (GLYPH_SIZE, GLYPH_SIZE))
|
||||
templates[name] = image.astype(np.float32) / 255.0
|
||||
return templates
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# detektor
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
class CardDetector:
|
||||
"""Rozpoznaje karty w wycinkach zwracanych przez table.ZoneExtractor."""
|
||||
|
||||
def __init__(self, template_dir: str = "templates", min_score: float = 0.45):
|
||||
self.min_score = min_score
|
||||
self._rank_templates = _load_templates(
|
||||
os.path.join(template_dir, "ranks"), RANKS
|
||||
)
|
||||
self._suit_templates = _load_templates(
|
||||
os.path.join(template_dir, "suits"), SUITS
|
||||
)
|
||||
if not self._rank_templates or not self._suit_templates:
|
||||
raise FileNotFoundError(
|
||||
f"Brak wzorcow w '{template_dir}'. Uruchom build_templates.py, "
|
||||
"zeby utworzyc katalog templates/."
|
||||
)
|
||||
|
||||
def detect(self, crop: np.ndarray) -> list[Card]:
|
||||
"""Zwraca liste kart znalezionych w jednym wycinku."""
|
||||
return [self.read_card(warp_card(crop, quad)) for quad in candidate_quads(crop)]
|
||||
|
||||
def detect_zones(self, zones: dict[str, list[np.ndarray]]) -> dict[str, list[Card]]:
|
||||
"""To samo co detect(), ale dla calego slownika zwracanego przez extract()."""
|
||||
return {
|
||||
zone: [card for crop in crops for card in self.detect(crop)]
|
||||
for zone, crops in zones.items()
|
||||
}
|
||||
|
||||
def read_card(self, card: np.ndarray) -> Card:
|
||||
"""Rozpoznaje ranga i kolor na obrazie pojedynczej, wyprostowanej karty."""
|
||||
best = Card(UNKNOWN, UNKNOWN, -2.0)
|
||||
|
||||
# karta moze lezec obrotem o 180 stopni - probujemy oba ulozenia
|
||||
for variant in (card, cv2.rotate(card, cv2.ROTATE_180)):
|
||||
rank_glyph, suit_glyph = index_glyphs(variant)
|
||||
rank, rank_score = _match(rank_glyph, self._rank_templates)
|
||||
suit, suit_score = _match(suit_glyph, self._suit_templates)
|
||||
score = rank_score + suit_score
|
||||
if score > best.score:
|
||||
best = Card(rank, suit, score)
|
||||
|
||||
rank, suit, score = best.rank, best.suit, best.score / 2
|
||||
if score < self.min_score:
|
||||
fallback = rank_from_pips(card) or rank_from_pips(
|
||||
cv2.rotate(card, cv2.ROTATE_180)
|
||||
)
|
||||
if fallback is not None:
|
||||
rank = fallback
|
||||
|
||||
return Card(rank, suit, score)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from table import ZoneExtractor
|
||||
|
||||
zone_extractor = ZoneExtractor()
|
||||
detector = CardDetector()
|
||||
|
||||
frame = cv2.imread('images/test_table_01.jpg')
|
||||
zones = zone_extractor.extract(zone_extractor.findTable(frame))
|
||||
|
||||
for zone_name, cards in detector.detect_zones(zones).items():
|
||||
opis = ', '.join(str(card) for card in cards) if cards else '-'
|
||||
print(f"{zone_name:16s}: {opis}")
|
||||
Reference in new issue
Block a user