#!/usr/bin/env python3 from pathlib import Path import logging logging.basicConfig(format='[%(asctime)s] %(process)s %(levelname)s {%(filename)s:%(lineno)d} - %(message)s', level=logging.DEBUG) try: import cv2 except ImportError as e: logging.error(f"Missing dependency: {e}") logging.error("Install with: pip install opencv-python") sys.exit(1) class Command: """Dataclass for commands""" __AUTHOR__ = 'anima' __VERSION__ = '1.1.3' image_dir: Path = Path('images/') supported_extensions = {".png", ".jpg", ".jpeg", ".bmp"} def __init__(self, image_name: str, commands: list, counter: int = None, threshold: float = 0.95, position: tuple = None): self.valid = False self.name = image_name self.commands = commands self.threshold = threshold self.position = position self.pos_dif = 10 self.counter = counter self.count = 0 self.load_image() def load_image(self) -> bool: """search, load and save image convertet as matchable object Returns: bool: Return True if image load successfull """ images = list(self.image_dir.rglob('*' + self.name + '*')) if len(images) > 0: for image in images: logging.debug(f'found image: {image.name} (pattern: {self.name})') if len(images) > 1: logging.warning(f'more than one images found for pattern {self.name}, can not load command') return False elif len(images) == 1: logging.info(f'load image for command {self.name}') else: logging.warning('no images found for pattern {self.name}') return False if image.suffix.lower() not in self.supported_extensions: logging.warning(f'image type of {image} is not supported') return False self.image = cv2.imread(str(image), cv2.IMREAD_COLOR) if image is None: logging.warning(f'could not load {image}') else: self.valid = True return self.valid def check_position(self, position: tuple) -> bool: """check if image on expected position Args: position (tuple): expected x, y position Returns: bool: True if image on expected position """ if self.position is None: logging.debug('no expected position set, skip check') return True if not isinstance(position, tuple): logging.debug(f'position check get wrong value {position=} ({type(position)})') return False i_x, i_y = self.position p_x, p_y = position if (i_x - self.pos_dif) < int(p_x) < (i_x + self.pos_dif) and \ (i_y - self.pos_dif) < int(p_y) < (i_y + self.pos_dif): return True else: logging.debug(f'image is not on expected {position=}') return False