Ejemplo n.º 1
0
 def handle_new_player_msg(self, msg):
     self.his_id = int(msg[1])
     if self.his_id == 0:
         self.his_head = Head(self.his_id, self.game_path.p0path,
                              self.width, self.height, self.my_head)
     elif self.his_id == 1:
         self.his_head = Head(self.his_id, self.game_path.p1path,
                              self.width, self.height, self.my_head)
     self.my_head.stranger = self.his_head
     self.head_group.add(self.his_head)
Ejemplo n.º 2
0
 def handle_id_msg(self, msg):
     self.id = int(msg[1])
     if self.id == 0:
         self.my_head = Head(self.id, self.game_path.p0path, self.width,
                             self.height, self.his_head)
     elif self.id == 1:
         self.my_head = Head(self.id, self.game_path.p1path, self.width,
                             self.height, self.his_head)
     self.head_group.add(self.my_head)
     msg_out = ('balls ' + ' '.join(
         str(self.my_head.ball_list[i])
         for i in range(len(self.my_head.ball_list))) + '\n')
     self.send_msg(msg_out)
Ejemplo n.º 3
0
def reset():
    global data, score, snakeHead, isPlaying, isApple
    score = 0   
    for i in range(48):
            data[i] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    isApple = False
    snakeHead = Head((0, 149, 238),(mapWidth/2, mapHeight/2), pps)
Ejemplo n.º 4
0
    def __init__(self, color=colors.skins_snake, name=0):
        ''' Создает новую змею в случайном месте, длиной 50 шариков.
        Координатой змеи считаются координаты центра головы. '''
        '''
        Не готово:
        1) Имя змеи
        '''
        if color == colors.skins_snake:
            self.colors = random.choice(colors.skins_snake)
        else:
            self.colors = color
        self.num = len(self.colors)
        self.name = name
        self.energy = 0

        self.x = 500
        self.y = 500
        self.coords = Vector2d(self.x, self.y)
        self.r = 5
        config.snake_radius = self.r
        self.length = 0
        self.life = 1

        self.balls = []
        head = Head(color=self.colors[0], x=self.x, y=self.y)
        self.balls += [head]
        self.length += 1
        for i in range(9):
            color = self.colors[(i + 1) % self.num]
            new_ball = Ball(x=self.x, y=self.y, color=color, r=5)
            self.balls += [new_ball]
            self.length += 1
        self.energy = self.length
        self.speed_timer = 0
Ejemplo n.º 5
0
    def testParseBytesToBytes(self):
        # b'DB\x04\x00\x00\x00\x00\x00\x00\x00ABCD1997'
        parser = Parser(BYTES_ENCODED)
        parser_test_function(self,
                             parser=parser,
                             code="D",
                             dtype="B",
                             length=4,
                             payload=b'ABCD',
                             remaining=0)

        head = Head(code=parser.code,
                    dtype=parser.dtype,
                    length=parser.length,
                    remaining=parser.remaining)
        head_test_function(self,
                           head=head,
                           code="D",
                           dtype="B",
                           length=4,
                           remaining=0)

        payload = Payload(data=parser.payload,
                          dtype=parser.dtype,
                          length=parser.length)
        payload_test_function(self,
                              payload=payload,
                              data=b'ABCD',
                              dtype="B",
                              length=4)
Ejemplo n.º 6
0
    def testParseBytesToInt(self):
        parser = Parser(INT_ENCODED)
        parser_test_function(self,
                             parser=parser,
                             code="D",
                             dtype="I",
                             length=2,
                             payload=257,
                             remaining=256)

        head = Head(code=parser.code,
                    dtype=parser.dtype,
                    length=parser.length,
                    remaining=parser.remaining)
        head_test_function(self,
                           head=head,
                           code="D",
                           dtype="I",
                           length=2,
                           remaining=256)

        payload = Payload(data=parser.payload,
                          dtype=parser.dtype,
                          length=parser.length)
        payload_test_function(self,
                              payload=payload,
                              data=257,
                              dtype="I",
                              length=2)
Ejemplo n.º 7
0
    def testParseBytesToStr(self):
        # b'DS\x04\x00\x00\x00\x00\x00\x00\x00ABCD1997'
        parser = Parser(data=STR_ENCODED)
        parser_test_function(self,
                             parser=parser,
                             code="D",
                             dtype="S",
                             length=4,
                             payload="ABCD",
                             remaining=0)

        head = Head(code=parser.code,
                    dtype=parser.dtype,
                    length=parser.length,
                    remaining=parser.remaining)
        head_test_function(self,
                           head=head,
                           code="D",
                           dtype="S",
                           length=4,
                           remaining=0)

        payload = Payload(data=parser.payload,
                          dtype=parser.dtype,
                          length=parser.length)
        payload_test_function(self,
                              payload=payload,
                              data="ABCD",
                              dtype="S",
                              length=4)
Ejemplo n.º 8
0
 def testParseHandshakeToBytes(self):
     parser = Parser(HANDSHAKE_ENCODED)
     parser_test_function(self,
                          parser=parser,
                          code="H",
                          dtype="B",
                          length=0,
                          payload=b"",
                          remaining=0)
     head = Head(code=parser.code,
                 dtype=parser.dtype,
                 length=parser.length,
                 remaining=parser.remaining)
     head_test_function(self,
                        head=head,
                        code="H",
                        dtype="B",
                        length=0,
                        remaining=0)
     payload = Payload(data=parser.payload,
                       dtype=parser.dtype,
                       length=parser.length)
     payload_test_function(self,
                           payload=payload,
                           data=b"",
                           dtype="B",
                           length=0)
Ejemplo n.º 9
0
    def __init__(self, simulation=True):
        """Initializes various aspects of the Fetch.
        
        TODOs: get things working, also use `simulation` flag to change ROS
        topic names if necessary (especially for the cameras!). UPDATE: actually
        I don't think this is necessary now, they have the same topic names.
        """
        rospy.init_node("fetch")
        self.arm = Arm()
        self.arm_joints = ArmJoints()
        self.base = Base()
        self.camera = RGBD()
        self.head = Head()
        self.gripper = Gripper(self.camera)
        self.torso = Torso()
        self.joint_reader = JointStateReader()

        # Tucked arm starting joint angle configuration
        self.names = ArmJoints().names()
        self.tucked = [1.3200, 1.3999, -0.1998, 1.7199, 0.0, 1.6600, 0.0]
        self.tucked_list = [(x, y) for (x, y) in zip(self.names, self.tucked)]

        # Initial (x,y,yaw) position of the robot wrt map origin. We keep this
        # fixed so that we can reset to this position as needed. The HSR's
        # `omni_base.pose` (i.e., the start pose) returns (x,y,yaw) where yaw is
        # the rotation about that axis (intuitively, the z axis). For the base,
        # `base.odom` supplies both `position` and `orientation` attributes.
        start = copy.deepcopy(self.base.odom.position)
        yaw = Base._yaw_from_quaternion(self.base.odom.orientation)
        self.start_pose = np.array([start.x, start.y, yaw])
        self.TURN_SPEED = 0.3

        self.num_restarts = 0
Ejemplo n.º 10
0
    def __init__(self, simulation=True):
        """Initializes various aspects of the Fetch."""
        rospy.init_node("fetch")
        rospy.loginfo("initializing the Fetch...")
        self.arm = Arm()
        self.arm_joints = ArmJoints()
        self.base = Base()
        self.camera = RGBD()
        self.head = Head()
        self.gripper = Gripper(self.camera)
        self.torso = Torso()
        self.joint_reader = JointStateReader()

        # Tucked arm starting joint angle configuration
        self.names = ArmJoints().names()
        self.tucked = [1.3200, 1.3999, -0.1998, 1.7199, 0.0, 1.6600, 0.0]
        self.tucked_list = [(x,y) for (x,y) in zip(self.names, self.tucked)]

        # Initial (x,y,yaw) position of the robot wrt map origin. We keep this
        # fixed so that we can reset to this position as needed. The HSR's
        # `omni_base.pose` (i.e., the start pose) returns (x,y,yaw) where yaw is
        # the rotation about that axis (intuitively, the z axis). For the base,
        # `base.odom` supplies both `position` and `orientation` attributes.
        start = copy.deepcopy(self.base.odom.position)
        yaw = Base._yaw_from_quaternion(self.base.odom.orientation)
        self.start_pose = np.array([start.x, start.y, yaw])
        rospy.loginfo("...finished initialization!")
 def __init__(self, config):
     self.replica_count = config.replica_count
     self.head = Head(config.init_object)
     self.tail = Tail(config.init_object)
     # create inner_replicas with chains
     inner_replicas = [Replica(config.init_object) * self.replica_count]
     self.replicas = [head] + inner_replicas + [tail]
     pass
Ejemplo n.º 12
0
    def __init__(self, N, M, in_size, out_size, batch_size, lstm=False):
        super(NTM, self).__init__()

        if lstm:
            self.controller = LSTMController(in_size, out_size, M, batch_size)
        else:
            self.controller = FeedForwardController(in_size, out_size, M, batch_size)

        self.read_head = Head(batch_size, N, M)
        self.write_head = Head(batch_size, N, M)
        self.batch_size = batch_size
        self.N = N
        self.M = M
        self.eps = 1e-8
        self.memory = None
        self.register_parameter('memory_bias',
                                nn.Parameter(torch.randn(1, N, M) / math.sqrt(N)))
Ejemplo n.º 13
0
def instantiate_objects():
    """After connection has been made, instatiate the various robot objects
    """

    global perm_dir_path
    global dir_path

    logger.debug('instantiate_objects called')
    #get default json file
    def_start_protocol = FileIO.get_dict_from_json(
        os.path.join(dir_path, 'data/default_startup_protocol.json'))
    #FileIO.get_dict_from_json('/home/pi/PythonProject/default_startup_protocol.json')

    #instantiate the head
    head = Head(def_start_protocol['head'], publisher, perm_dir_path)
    logger.debug('head string: ')
    logger.debug(str(head))
    logger.debug('head representation: ')
    logger.debug(repr(head))
    #use the head data to configure the head
    head_data = {}
    head_data = prot_dict['head']  #extract the head section from prot_dict

    logger.debug("Head configured!")

    #instantiate the script keeper (sk)

    #instantiate the deck
    deck = Deck(def_start_protocol['deck'], publisher, perm_dir_path)
    logger.debug('deck string: ')
    logger.debug(str(deck))
    logger.debug('deck representation: ')
    logger.debug(repr(deck))

    runner = ProtocolRunner(head, publisher)

    #use the deck data to configure the deck
    deck_data = {}
    deck_data = prot_dict['deck']  #extract the deck section from prot_dict
    #    deck = RobotLib.Deck({})        #instantiate an empty deck
    deck.configure_deck(deck_data)  #configure the deck from prot_dict data
    logger.debug("Deck configured!")

    #do something with the Ingredient data
    ingr_data = {}
    ingr_data = prot_dict[
        'ingredients']  #extract the ingredient section from prot_dict
    ingr = Ingredients({})

    ingr.configure_ingredients(
        ingr_data)  #configure the ingredienets from prot_dict data
    logger.debug('Ingredients imported!')

    publisher.set_head(head)
    publisher.set_runner(runner)
    subscriber.set_deck(deck)
    subscriber.set_head(head)
    subscriber.set_runner(runner)
Ejemplo n.º 14
0
 def init(self):
     self.tray = Tray(self)
     self.head = Head(self)
     self.agenda = Agenda(self)
     self.set = Set(self)
     # qss
     with open('style.QSS', 'r') as fp:
         self.setStyleSheet(fp.read())
         fp.close()
Ejemplo n.º 15
0
    def __init__ (self):
        rospy.Subscriber("/head_camera/rgb/image_raw",Image,self.RGBImageCallback)
        rospy.Subscriber("/head_camera/depth_registered/image_raw",Image,self.DepthImageCallback)
        rospy.Subscriber("/ar_pose_marker",AlvarMarkers,self.GetArPosesCallBack)
        self.bridge = CvBridge()

        self.Arm = Arm()
        self.Gripper = Gripper()
        self.Head = Head()
        self.PoseProcessing = PoseProcessing()
Ejemplo n.º 16
0
 def init(self):
     PlayState.TICK_LENGTH = 0.1
     self.tick_time = 0
     self.head = Head(PlayState.GRID_SIZE)
     self.body = []
     for i in range(PlayState.INITIAL_BODY_SIZE):
         self.__add_body__()
     self.food = Food(PlayState.GRID_SIZE, self.head.pos)
     self.hud = HUD()
     pass
Ejemplo n.º 17
0
def webControl(x, y):
    x = int(x)
    y = int(y)
    usrMsgLogger = DataLogger()
    evobot = EvoBot("/dev/tty.usbmodemfa131", usrMsgLogger)
    head = Head(evobot)
    syringe = Syringe(evobot, 9)
    syringe.plungerSetConversion(1)
    evobot.home()

    head.move(x, y)
Ejemplo n.º 18
0
 def __init__(self,
              content: Union[bytes, str, int] = b'',
              code: str = "default",
              remaining: int = 0,
              encoded: bytes = None):
     if encoded:
         self.parser = Parser(encoded)
         self.head = Head(code=self.parser.code,
                          dtype=self.parser.dtype,
                          length=self.parser.length,
                          remaining=self.parser.remaining)
         self.payload = Payload(data=self.parser.payload,
                                dtype=self.parser.dtype,
                                length=self.parser.length)
         self.end_of_package = self.parser.eop
     else:
         self.payload = Payload(content)
         self.head = Head(code=code,
                          dtype=self.payload.dtype,
                          length=self.payload.length,
                          remaining=remaining)
         self.end_of_package = self.get_end_of_package()
     self.encoded = self.get_encoded()
Ejemplo n.º 19
0
 def testParseCorruptedStreamToBytes(self):
     parser = Parser(CORRUPTED_STREAM)
     parser_test_function(self,
                          parser=parser,
                          code="E",
                          dtype="B",
                          length=0,
                          payload=b"",
                          remaining=0)
     head = Head(code=parser.code,
                 dtype=parser.dtype,
                 length=parser.length,
                 remaining=parser.remaining)
     head_test_function(self, head, "E", "B", 0, 0,
                        b'EB\00\00\00\00\00\00\00\00')
Ejemplo n.º 20
0
 def testParseBytesToError(self):
     parser = Parser(ERROR_ENCODED)
     parser_test_function(self,
                          parser=parser,
                          code="E",
                          dtype="B",
                          length=0,
                          payload=b"",
                          remaining=0)
     head = Head(code=parser.code,
                 dtype=parser.dtype,
                 length=parser.length,
                 remaining=parser.remaining)
     head_test_function(self, head, "E", "B", 0, 0,
                        b'EB\00\00\00\00\00\00\00\00')
Ejemplo n.º 21
0
def run_game():
	# initiate game
	pygame.init()

	ai_settings = Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
	pygame.display.set_caption("Snake")

	# set up the original images of all necessary body parts
	image_source = ImageSource()
	# the bodies already attached to the head
	bodies = Group()
	# the bodies NOT attached to the snake and to be eaten by the snake
	foods = Group()
	# generate a head
	head = Head(screen, ai_settings, image_source, bodies)
	# record game statistics
	filename = 'high_score.txt'
	stats = GameStats(filename)
	# record a list of messages that will be shown at the beginning and end of game
	msgs = []
	gf.create_msgs(msgs, stats)

	# use clock to control fps
	clock = time.Clock()

	# main game loop
	while True:
		gf.check_events(screen, ai_settings, image_source, bodies, head, foods, stats, filename)

		if ai_settings.game_active:
			gf.update_head(head, foods, bodies, screen, ai_settings, image_source, stats)
			# update the location of snake body
			bodies.update()
			# update msgs that will show when game ends
			gf.update_msgs(msgs, stats)
			# snake speed will be controlled by frame rate
			clock.tick(ai_settings.fps)
		
		else:
			if head.dead:
				# show msg when game ends
				button = Button(screen, ai_settings, msgs, True)
			else:
				# show msg before game starts
				button = Button(screen, ai_settings, msgs, False)
		gf.update_screen(bodies, foods, ai_settings, screen, head, button)
Ejemplo n.º 22
0
def main():
    '''Main function of Snake.'''

    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width,
        ai_settings.screen_height))
    pygame.display.set_caption('Snake')
    head = Head(ai_settings, screen)

    while True:
        # Check events
        gf.check_events()

        #
        head.update()

        # Update the items drawn on the screen
        screen.fill(ai_settings.bg_color)
        head.draw_head()
        pygame.display.flip()
Ejemplo n.º 23
0
    def __init__(self, torso_center, lower_body_flag):
        self._body_center = torso_center
        self._lower_body_flag = lower_body_flag
        self.head = Head(
            Point(torso_center.x, torso_center.y + 15, torso_center.z))
        self.torso = Torso(
            Point(torso_center.x, torso_center.y, torso_center.z))
        self.left_arm = Arm(
            Point(torso_center.x + 6.6, torso_center.y + 8, torso_center.z))
        self.right_arm = Arm(
            Point(torso_center.x - 6.6, torso_center.y + 8, torso_center.z))

        self.right_arm.set_slocal_rotate_angle(180, 0, 0)

        if self._lower_body_flag:
            self.left_leg = Leg(
                Point(torso_center.x + 4, torso_center.y - 10.6,
                      torso_center.z))
            self.right_leg = Leg(
                Point(torso_center.x - 4, torso_center.y - 10.6,
                      torso_center.z))
            self.right_leg.set_hlocal_rotate_angle(180, 0, 0)
Ejemplo n.º 24
0
    def build(self, robot_type):
        """Builds a robot object.

        Returns: Robot. A robot object.
        """

        # Interface
        interface = Interface(robot_type)

        # Navigation
        tf_listener = tf.TransformListener()
        location_db = LocationDb('location_db', tf_listener)
        navigation = Navigation(robot_type, location_db, tf_listener)

        # Speech and sounds
        sound_db = SoundDb('sound_db')
        for i in range(10):
            sound_db.set('sound' + str(i + 1))
        voice = Voice(sound_db)

        command_db = CommandDb('command_db')
        speech_monitor = SpeechMonitor(command_db)

        # Head
        # TODO: Head action database?
        if robot_type == RobotType.PR2:
            head = Head()
        else:
            head = None

        # Arms
        # TODO: Arm action database?
        # TODO: Arm action execution
        #arms = Arms()

        robot = Robot(robot_type, interface, navigation, voice, head,
                      speech_monitor, tf_listener)

        return robot
Ejemplo n.º 25
0
    def __init__(self):
        # Set up logger to log to screen
        self.log = createLogger()

        # Construction
        self.numLegs = 0  # number of legs - start with none
        self.legPairs = []  # start with no legs (they will be added later)
        self.head = Head(self.interrupt, self.log)
        self.leftAntenna = Button(6)
        self.rightAntenna = Button(12)

        self.voicePin = 16
        GPIO.setup(self.voicePin, GPIO.OUT)
        self.pwm = GPIO.PWM(self.voicePin, 1000)

        # Robot health (not used at the moment)
        # Can use these to determine behaviour, e.g. slowing down as energy drops
        self.alertness = 120
        self.energy = 1000
        self.age = 0

        # Helper objects, to idenntify legs and threads
        self._legs = {}  # dictionary to quickly find legs
        self._threads = {}  # dictionary to quickly find threads

        # Actions will run on a thread
        self._actionThread = None  # thread on which current action is running
        self._threadCount = 0  # so we can track threads

        self._stopped = False  # flag to indicate if we want the animal to stop what it is doing (i.e. stop current thread)

        # Antennae handlers - called when antenna triggered
        self.leftAntenna.when_pressed = self._leftAntennaPressed
        self.rightAntenna.when_pressed = self._rightAntennaPressed

        # Caller can register a callback to receive messages (for display purposes)
        self.messageCallback = None

        self.log.info("Created Animal")
Ejemplo n.º 26
0
def callback(msg):
    global avatars

    msg_json = json.loads(msg)

    if "hasAvatar" in msg_json:
        user = extract_user_id(msg_json["object_id"])
        if msg_json["hasAvatar"]:
            if user not in avatars:
                avatars[user] = Head(user)
            avatars[user].rig_on()
        else:
            if user in avatars:
                avatars[user].rig_off()
                del avatars[user]

    elif "hasFace" in msg_json and msg_json["hasFace"]:
        user = extract_user_id(msg_json["object_id"])
        if user in avatars and avatars[user].rig_enabled:
            if not avatars[user].has_face:
                avatars[user].add_face(msg_json)
            else:
                avatars[user].update_face(msg_json)
Ejemplo n.º 27
0
 def __init__(self, head, structure, morphology={}):
     if (sys.version_info > (3, 0)):
         # Python 3
         self.new_python = True
     else:
         # Python 2
         self.new_python = False
     self.parent = None
     self.head = Head(head, structure["head"])
     self.components = copy.deepcopy(structure["components"])
     if self.components is None:
         self.components = {}
         self.order = ["head"]
     else:
         self.order = copy.deepcopy(structure["order"])
     if "agreement" in structure:
         self.agreement = copy.deepcopy(structure["agreement"])
     else:
         self.agreement = {}
     if "governance" in structure:
         self.governance = copy.deepcopy(structure["governance"])
     else:
         self.governance = {}
     self.morphology = copy.deepcopy(morphology)
Ejemplo n.º 28
0

if __name__ == '__main__':
    sleep_time = 20
    if len(sys.argv) > 2:
        _TOKEN_ = sys.argv[1]
        _MASTER_ID_ = sys.argv[2]

    if len(sys.argv) > 3 and sys.argv[3] == 'no-wait':
        sleep_time = 0
    time.sleep(sleep_time)

    if _MASTER_ID_ and _TOKEN_:
        bot = None
        while True:
            try:
                bot = telepot.Bot(_TOKEN_)
                _HEAD_ = Head(bot)
                bot.message_loop(handle)
                print('Listening ...')
                say_hi()
                break
            except:
                print("error... retrying in {0} seconds".format(sleep_time))
                time.sleep(sleep_time)

        # Keep the program running.
        while True:
            pass

    print('exiting...')
Ejemplo n.º 29
0
    def __init__(self, root, sizeX, sizeY, title):
        super().__init__(root)
        # self.pack(expand='no', fill='both')
        self.root = root
        self.state_ = False
        root.wm_title(title)
        root.focus_force()
        self.img_ = create_img()
        self.pack(expand=True, fill=tk.BOTH)
        set_application_icons(root, 'ico')  # imgdir
        self.path = pathlib.Path(cwddir)
        path_ = self.path.joinpath(
            'Проекты')  # каталог для файлов конвертора  'project'
        if not path_.exists():
            os.mkdir(path_)
        self.b = {}  # контейнер для виджетов
        self.dir_cvt = path_
        self._zona = config.getfloat('System', 'vzona')
        self._opgl = 0
        self.mb = config.getboolean('Amplituda', 'mb')  # 1 - RGB
        # fxen = dict(fill=tk.X, expand=False)
        (self.glub_var, self.stop_var, self.time_var, self.numstr_var,
         self.ampl_var, self.skale_var, self.porog_var,
         self.frek_var) = (tk.StringVar() for _ in range(8))

        self.tol_bar = Toolbar(self, bso_)  # объект tolbar
        self.tol_bar.pack(fill=tk.X, expand=False)
        # ttk.Separator(self).pack(**fxen)

        self.head = Head(self)  # объект этикетки head
        self.head.pack(fill=tk.X, expand=False)

        self.stbar = Footer(self, bso_)  # объект строки состояния
        self.stbar.pack(side=tk.BOTTOM, fill=tk.X)

        self.sep = ttk.Separator(self)
        self.sep.pack(side=tk.BOTTOM, fill=tk.X, pady=1)
        self.frame_upr = ttk.Frame(self)  # фрейм для управления
        self.frame_upr.pack(side=tk.BOTTOM, fill=tk.X)

        self.infobar = InfoBar(self)  # объект Info
        self.infobar.pack(side=tk.BOTTOM, fill=tk.X)

        self.board = CanvasT(self, sizeX, sizeY, bso_)  # объект CanvasT
        self.board.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        self.ser = RS232(trace)  # объект Serial
        self.gser = Gps(trace)  # объект Gps
        self.gser.tty.baudrate = 4800
        self.gser.tty.timeout = 0.01
        self._zg = config.getfloat('System', 'zagl')
        self.head.set_z(self.zg)  # zg - свойство
        self.d0 = {
            'L': 'МГ',
            'M': 'СГ',
            'H': 'БГ',
            'C': 'B8',
            'D': 'B10',
            'B': 'Б6'
        }
        self.fil_ametka = 'DodgerBlue2'
        self.stringfile = 0  # число строк записанных в файл
        self.txt_opmetka = 0  # счётчик оперативных отметок ручн.
        self.y_g = 0
        # self.error = 0                              # занулить ошибки при старте проги
        self.file_gals = None  # нет файла для записи галса
        self.man_metkawriteok = (False, False)
        self.avto_metkawriteok = False
        self.yold_ = 0.0  # для перемещен текста врем. меток
        self.hide_metka = False  # Показывать метки
        self.hide_grid = False  # Показывать гор. линии
        self.gl_0 = 0
        self.d_gps = None
        self.last_d_gps = None
        self.tavto_ = None
        self.tbname = None
        self.view_db = None
        # self.count_gps = 0
        self.ida = None
        self.ida_ = True
        self.last_sec = -1
        self.count_tmetka = 1
        self.vz_last = self.rej_last = 0
        self.diap_last = self.old_depth = 'МГ'
        self.helpDialog = None
        self.color_ch = True
        self.t_pausa = 0
        self.y_metka = self.board.y_top
        self.flag_gals = False
        self.vzvuk = 1500
        if bso_:
            self.gui_main()
            self.sep.pack_forget()
Ejemplo n.º 30
0
def capture_action(pred_path, cb, debug=False, log=False):
    """Facial detection and real time processing credit goes to:

    https://www.pyimagesearch.com/2017/04/17/real-time-facial-landmark-detection-opencv-python-dlib/
    """
    action_handler = ActionHandler()

    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(pred_path)

    camera = cv2.VideoCapture(0)

    while True:
        _, frame = camera.read()
        if frame is None:
            continue

        _, w_original, _ = frame.shape
        frame = resize_frame(frame)

        h, w, _ = frame.shape

        display_bounds(frame)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        rects = detector(gray, 0)

        for rect in rects:
            shape = predictor(gray, rect)
            shape = face_utils.shape_to_np(shape)

            cur_head = Head(shape, w)
            cur_eyes = Eyes(shape, frame)

            eye_action = detect_eyes(shape, cur_eyes)
            head_action = detect_head(shape, cur_head)

            COUNTER_LOG[eye_action] += 1
            COUNTER_LOG[head_action] += 1

            perform, action = action_handler.get_next(eye_action, head_action)

            if log:
                display_decisions(frame, head_action, eye_action)
                display_counters(frame, COUNTER_LOG)

            if perform:
                COUNTER_LOG[action] += 1
                cb(action)

            if debug:
                cur_head.debug(frame)
                cur_eyes.debug(frame)

                cv2.imshow("Frame", frame)

        key = cv2.waitKey(1) & 0xFF

        if key == ord("q"):
            break

    cv2.destroyAllWindows()