commit 773f5dd5c37b7a9e69d479ae4b6ce2cbb47f345d Author: basiek Date: Thu Dec 3 03:15:02 2026 +0100 Full Bomba diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..df54371 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,7 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Markdown personal settings +/markdown.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/Poker.iml b/.idea/Poker.iml new file mode 100644 index 0000000..c90897f --- /dev/null +++ b/.idea/Poker.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..04b6fbe --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,12 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b277f6c --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..5d19e9c --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000..5596b44 --- /dev/null +++ b/app.py @@ -0,0 +1,16 @@ +# This is a sample Python script. + +# Press Shift+F10 to execute it or replace it with your code. +# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. + + +def print_hi(name): + # Use a breakpoint in the code line below to debug your script. + print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. + + +# Press the green button in the gutter to run the script. +if __name__ == '__main__': + print_hi('PyCharm') + +# See PyCharm help at https://www.jetbrains.com/help/pycharm/ diff --git a/build_templates.py b/build_templates.py new file mode 100644 index 0000000..5a26441 --- /dev/null +++ b/build_templates.py @@ -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() diff --git a/detector.py b/detector.py new file mode 100644 index 0000000..6bd768d --- /dev/null +++ b/detector.py @@ -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}") diff --git a/images/cards.jpg b/images/cards.jpg new file mode 100644 index 0000000..073e680 Binary files /dev/null and b/images/cards.jpg differ diff --git a/images/test_table_01.jpg b/images/test_table_01.jpg new file mode 100644 index 0000000..c4d562b Binary files /dev/null and b/images/test_table_01.jpg differ diff --git a/images/test_table_02.jpg b/images/test_table_02.jpg new file mode 100644 index 0000000..752d749 Binary files /dev/null and b/images/test_table_02.jpg differ diff --git a/images/test_table_03.jpg b/images/test_table_03.jpg new file mode 100644 index 0000000..661935c Binary files /dev/null and b/images/test_table_03.jpg differ diff --git a/poker.py b/poker.py new file mode 100644 index 0000000..19c402c --- /dev/null +++ b/poker.py @@ -0,0 +1,5 @@ +import cv2 +from table import ZoneExtractor + +if __name__ == '__main__': + pass diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e9f66a1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +opencv-python +matplotlib +numpy +scikit-image \ No newline at end of file diff --git a/table.py b/table.py new file mode 100644 index 0000000..a14de6c --- /dev/null +++ b/table.py @@ -0,0 +1,124 @@ +import cv2 +import numpy as np + +LOWER_GREEN = np.array([35, 40, 30]) +UPPER_GREEN = np.array([90, 255, 255]) + +LOWER_WHITE = np.array([0, 0, 155]) +UPPER_WHITE = np.array([180, 70, 255]) + + +class ZoneExtractor: + """ + Klasa odpowiadajaca za wyciecie z obrazu poszczegolnych miejsc zainteresowania. + Zwraca Liste o kluczach: community, player_top, playter_right, player_bottom. + """ + + def __init__(self): + pass + + def get_green_mask(self, image): + image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) + mask = cv2.inRange(image_hsv, LOWER_GREEN, UPPER_GREEN) + return cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)) + + def findTable(self, image): + """ + Funkcja znajduje plansze do gry. + Poprzez progowanie obrazu na podstawie koloru zielonego. + Zwraca sama plansze. + """ + clean_mask = self.get_green_mask(image) + + ys, xs = np.where(clean_mask == 255) + y_min, y_max = np.percentile(ys, [4, 97]).astype(int) + x_min, x_max = np.percentile(xs, [4, 97]).astype(int) + table = image[y_min:y_max, x_min:x_max] + + return table + + def extract(self, table): + """ + Korzystajac z segmentacji obrazu otrzymujemy obiekty ktore pozniej na podstawie wspolrzednych przypisujemy do konkretnego gracza. + :param table: wycieta plansza gry + :return zones: zwraca slownik z obrazami kart dla danego gracza. + """ + h, w, _ = table.shape + table_area = h * w + result = { + "cards": { + "community": [], + "player_one": [], + "player_two": [], + "player_three": [], + }, + "chips": { + "player_one": [], + "player_two": [], + "player_three": [], + }, + } + + hsv_table = cv2.cvtColor(table, cv2.COLOR_BGR2HSV) + + white_mask = cv2.inRange(hsv_table, LOWER_WHITE, UPPER_WHITE) + + white_mask = cv2.morphologyEx(white_mask, cv2.MORPH_CLOSE, np.ones((10, 10), np.uint8)) + + cv2.imshow("table", white_mask) + + num_cards, _, card_stats, card_centroids = cv2.connectedComponentsWithStats(white_mask) + for i in range(1, num_cards): + x, y, bw, bh, area = card_stats[i] + cx, cy = card_centroids[i] + + if area < table_area * 0.007 or bh > h * 0.70 or bw > w * 0.70: + continue + + crop = table[max(0, y - 5):min(h, y + bh + 5), max(0, x - 5):min(w, x + bw + 5)] + + if cx < w * 0.30 and cy > h * 0.22: + result["cards"]["community"].append(crop) + elif w * 0.28 < cx < w * 0.72 and cy < h * 0.38: + result["cards"]["player_one"].append(crop) + elif cx > w * 0.58 and cy < h * 0.70: + result["cards"]["player_two"].append(crop) + elif cy > h * 0.62 and w * 0.28 < cx < w * 0.72: + result["cards"]["player_three"].append(crop) + + green_mask = self.get_green_mask(table) + chips_mask = cv2.bitwise_not(green_mask) + + num_chips, _, chip_stats, chip_centroids = cv2.connectedComponentsWithStats(chips_mask) + for i in range(1, num_chips): + x, y, bw, bh, area = chip_stats[i] + cx, cy = chip_centroids[i] + + is_chip_size = (table_area * 0.0015) < area < (table_area * 0.0065) + in_betting_zone = (w * 0.28 < cx < w * 0.72) and (h * 0.22 < cy < h * 0.78) + + if not (is_chip_size and in_betting_zone): + continue + + crop = table[max(0, y - 5):min(h, y + bh + 5), max(0, x - 5):min(w, x + bw + 5)] + + if cy < h * 0.42 and cx < w * 0.62: + result["chips"]["player_one"].append(crop) + elif cx >= w * 0.52 and h * 0.30 <= cy <= h * 0.70: + result["chips"]["player_two"].append(crop) + elif cy > h * 0.58 and cx < w * 0.62: + result["chips"]["player_three"].append(crop) + return result + + +zoneE = ZoneExtractor() + +if __name__ == '__main__': + frame = cv2.imread('images/test_table_03.jpg') + table = zoneE.findTable(frame) + zones = zoneE.extract(table) + for zone_name, crops in zones["cards"].items(): + for idx, crop in enumerate(crops): + cv2.imshow(f"{zone_name}_{idx}", crop) + cv2.waitKey(0) + cv2.destroyAllWindows() diff --git a/table2.py b/table2.py new file mode 100644 index 0000000..fde330d --- /dev/null +++ b/table2.py @@ -0,0 +1,80 @@ +import cv2 +import numpy as np + +LOWER_GREEN = np.array([35, 40, 30]) +UPPER_GREEN = np.array([90, 255, 255]) + + +class ZoneExtractor: + """ + Klasa odpowiadajaca za wyciecie z obrazu poszczegolnych miejsc zainteresowania. + Zwraca Liste o kluczach: community, player_top, playter_right, player_bottom. + """ + + def __init__(self): + pass + + def get_green_mask(self, image): + """ + Funkcja znajduje plansze do gry. + Poprzez progowanie obrazu na podstawie koloru zielonego. + Zwraca sama plansze. + """ + image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) + mask = cv2.inRange(image_hsv, LOWER_GREEN, UPPER_GREEN) + return cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8)) + + def findTable(self, image): + clean_mask = self.get_green_mask(image) + ys, xs = np.where(clean_mask == 255) + y_min, y_max = np.percentile(ys, [4, 97]).astype(int) + x_min, x_max = np.percentile(xs, [4, 97]).astype(int) + table = image[y_min:y_max, x_min:x_max] + return table + + def extract(self, table): + """ + Korzystajac z segmentacji obrazu otrzymujemy obiekty ktore pozniej na podstawie wspolrzednych przypisujemy do konkretnego gracza. + :param table: wycieta plansza gry + :return zones: zwraca slownik z obrazami kart dla danego gracza. + """ + h, w, _ = table.shape + zones: dict[str, list[np.ndarray]] = { + "community_cards": [], + "player_one": [], + "player_two": [], + "player_three": [], + + } + green_mask = self.get_green_mask(table) + objects_mask = cv2.bitwise_not(green_mask) + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(objects_mask) + for i in range(1, num_labels): + x, y, bw, bh, area = stats[i] + cx, cy = centroids[i] + if area < 1500: + continue + crop = table[max(0, y - 5):min(h, y + bh + 5), max(0, x - 5):min(w, x + bw + 5)] + if cx < w * 0.30 and cy > h * 0.22: + zones["community_cards"].append(crop) + elif w * 0.32 < cx < w * 0.7 and cy < h * 0.3: + zones["player_one"].append(crop) + elif cx > w * 0.58 and cy < h * 0.70: + zones["player_two"].append(crop) + elif cy > h * 0.62: + zones["player_three"].append(crop) + return zones + + +zoneE = ZoneExtractor() + +if __name__ == '__main__': + frame = cv2.imread('images/test_table_01.jpg') + table = zoneE.findTable(frame) + zones = zoneE.extract(table) + for zone_name, crops in zones.items(): + if zone_name == 'player_three': + for idx, crop in enumerate(crops): + cv2.imshow(f"{zone_name}_{idx}", crop) +cv2.waitKey(0) +cv2.destroyAllWindows() diff --git a/templates/ranks/3.png b/templates/ranks/3.png new file mode 100644 index 0000000..ba43708 Binary files /dev/null and b/templates/ranks/3.png differ diff --git a/templates/ranks/4.png b/templates/ranks/4.png new file mode 100644 index 0000000..d8f905b Binary files /dev/null and b/templates/ranks/4.png differ diff --git a/templates/ranks/5.png b/templates/ranks/5.png new file mode 100644 index 0000000..fa88d8b Binary files /dev/null and b/templates/ranks/5.png differ diff --git a/templates/ranks/6.png b/templates/ranks/6.png new file mode 100644 index 0000000..ebad810 Binary files /dev/null and b/templates/ranks/6.png differ diff --git a/templates/ranks/7.png b/templates/ranks/7.png new file mode 100644 index 0000000..d534260 Binary files /dev/null and b/templates/ranks/7.png differ diff --git a/templates/ranks/8.png b/templates/ranks/8.png new file mode 100644 index 0000000..25b4fec Binary files /dev/null and b/templates/ranks/8.png differ diff --git a/templates/ranks/9.png b/templates/ranks/9.png new file mode 100644 index 0000000..795ec99 Binary files /dev/null and b/templates/ranks/9.png differ diff --git a/templates/ranks/J.png b/templates/ranks/J.png new file mode 100644 index 0000000..b8d65ec Binary files /dev/null and b/templates/ranks/J.png differ diff --git a/templates/ranks/K.png b/templates/ranks/K.png new file mode 100644 index 0000000..24e7373 Binary files /dev/null and b/templates/ranks/K.png differ diff --git a/templates/ranks/Q.png b/templates/ranks/Q.png new file mode 100644 index 0000000..1096aee Binary files /dev/null and b/templates/ranks/Q.png differ diff --git a/templates/review.png b/templates/review.png new file mode 100644 index 0000000..09a9fec Binary files /dev/null and b/templates/review.png differ diff --git a/templates/suits/clubs.png b/templates/suits/clubs.png new file mode 100644 index 0000000..581cea7 Binary files /dev/null and b/templates/suits/clubs.png differ diff --git a/templates/suits/diamonds.png b/templates/suits/diamonds.png new file mode 100644 index 0000000..72f15fb Binary files /dev/null and b/templates/suits/diamonds.png differ diff --git a/templates/suits/hearts.png b/templates/suits/hearts.png new file mode 100644 index 0000000..08b4be5 Binary files /dev/null and b/templates/suits/hearts.png differ diff --git a/templates/suits/spades.png b/templates/suits/spades.png new file mode 100644 index 0000000..bbbf9e9 Binary files /dev/null and b/templates/suits/spades.png differ