def run(*args):
     logger().info('Open')
     while (True):
         # for i in range(1):
         time.sleep(0.1)
         message = ''
         with open('./data/message_2.json') as f:
             message = f.read()
         ws.send(message)
         logger().debug('Sent:{}'.format(message))
     ws.close()
     logger().info('Thread terminating...')
def run():
    logger().info('run')
    # 黄色
    car_monitor = CarMonitor([[20, 10, 180], [50, 255, 255]])
    # 緑
    car_monitor_2 = CarMonitor([[60, 50, 90], [100, 255, 255]])
    while(True):
    # for i in range(1):
        #time.sleep(0.1)
        degree, distance = car_monitor.get_car_dests(False)
        degree_2, distance_2 = car_monitor_2.get_car_dests(False)
        logger().info('degree, distance: {}, {}'.format(degree, distance))
        logger().info('degree_2, distance_2: {}, {}'.format(degree_2, distance_2))
        message_dict_1 = get_message_dict(degree, distance,
                                          (degree_2 != CarMonitor.INVALID_DEGREE))
        with open('./data/message_1.json', 'w') as f:
            json.dump(message_dict_1, f)
        message_dict_2 = get_message_dict(degree_2, distance_2, False)
        with open('./data/message_2.json', 'w') as f:
            json.dump(message_dict_2, f)
    logger().info('Thread terminating...')
def message_received(client, server, message):
    logger().info('Message has been received from {}:{}'.format(client['address'][0], client['address'][1]))
    try:
        message_dict = json.loads(message)
        if message_dict['type'] == 'color':
            try:
                client_list[str(client['id'])]['color'] = [[message_dict.get('color', {}).get('H', {}).get('min', 0),
                                                            message_dict.get('color', {}).get('H', {}).get('max', 0)],
                                                           [message_dict.get('color', {}).get('S', {}).get('min', 0),
                                                            message_dict.get('color', {}).get('S', {}).get('max', 0)],
                                                           [message_dict.get('color', {}).get('V', {}).get('min', 0),
                                                            message_dict.get('color', {}).get('V', {}).get('max', 0)]]
            except AttributeError:
                logger().info('faild to get color data')
                client_list[str(client['id'])]['color'] = [[0, 0], [0, 0], [0, 0]]
            car_monitor_list[str(client['id'])] = CarMonitor([[client_list[str(client['id'])]['color'][0][0],
                                                              client_list[str(client['id'])]['color'][1][0],
                                                              client_list[str(client['id'])]['color'][2][0]],
                                                              [client_list[str(client['id'])]['color'][0][1],
                                                              client_list[str(client['id'])]['color'][1][1],
                                                              client_list[str(client['id'])]['color'][2][1]]])
    except json.JSONDecodeError:
        logger().info('faild to decode message to json')
    logger().info('client_list : {}'.format(client_list))
def send_order(server):
    for k, v in car_monitor_list.items():
        degree, distance = v.get_car_dests()
        logger().info('degree, distance: {}, {}'.format(degree, distance))
def client_left(client, server):
    logger().info('Client {}:{} has left.'.format(client['address'][0], client['address'][1]))
def new_client(client, server):
    logger().info('New client {}:{} has joined.'.format(client['address'][0], client['address'][1]))
    client_list[str(client['id'])] = {}
    client_list[str(client['id'])]['client'] = client
예제 #7
0
# coding: UTF-8

from multiprocessing import Process
from debug import logger
# import monitor_main
import socket_main

if __name__ == '__main__':
    logger().info('main line')

    # p_monitor = Process(target=monitor_main.run, args=())
    p_socket_1 = Process(target=socket_main.run_socket_1, args=())
    p_socket_2 = Process(target=socket_main.run_socket_2, args=())

    # p_monitor.start()
    # logger().info('p_monitor started')
    p_socket_1.start()
    logger().info('p_socket_1 started')
    p_socket_2.start()
    logger().info('p_socket_2 started')

    # p_monitor.join()
    p_socket_1.join()
    p_socket_2.join()
예제 #8
0
 def __init__(self, back_color_hsv, camera_device_num=0):
     logger().debug('CarMonitor init() start')
     self._device_num = camera_device_num
     self._back_color_hsv = back_color_hsv
     self._cap = cv2.VideoCapture(self._device_num)
     logger().debug('CarMonitor init() end')
    def get_car_dests(self, save_img=False, path='img'):
        """
        
        calculate angle between car and station entrance
        
        Args:
            save_img (bool): True -> save intermediate picture as png file (debug function)
            path (string): directory path to save image
            
        Returns:
            float: angle[degree]
            float: distance
        
        """
        readable, img = self._get_img()
        if save_img:
            cv2.imwrite(path + '/origin.png', img)
        hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv_img, np.array(self._back_color_hsv[0]),
                           np.array(self._back_color_hsv[1]))
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

        trim_mask = np.zeros_like(img)
        convex_hull_list = []
        for contour in contours:
            approx = cv2.approxPolyDP(contour,
                                      0.01 * cv2.arcLength(contour, True),
                                      True)
            # 四角形に近い形のみ扱う
            if 3 < len(approx) < 10:
                M = cv2.moments(approx)
                if M['m00'] > CarMonitor.DETECT_AREA_SIZE:
                    convex_hull_list.append({'approx': approx, 'moment': M})
                    cv2.fillConvexPoly(trim_mask,
                                       approx,
                                       color=(255, 255, 255))

        if save_img:
            cv2.imwrite(path + '/trim_mask.png', trim_mask)
        bg_color = (255, 255, 255)
        bg_img = np.full_like(img, bg_color)
        trim_img = np.where(trim_mask == 255, img, bg_img)

        marker_mask = cv2.inRange(trim_img, np.array([0, 0, 0]),
                                  np.array([255, 255, 100]))
        if save_img:
            cv2.imwrite(path + '/marker_mask.png', marker_mask)
        marker_contours, _ = cv2.findContours(marker_mask, cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_SIMPLE)
        m_convex_hull_list = []
        for contour in marker_contours:
            approx = cv2.approxPolyDP(contour,
                                      0.01 * cv2.arcLength(contour, True),
                                      True)
            # 四角形に近い形のみ扱う
            if 3 < len(approx) < 10:
                M = cv2.moments(approx)
                if M['m00'] > CarMonitor.DETECT_AREA_SIZE / 20:
                    m_convex_hull_list.append({'approx': approx, 'moment': M})

                    cx = int(M['m10'] / M['m00'])
                    cy = int(M['m01'] / M['m00'])
                    self._draw_marker(trim_img, cx, cy, (0, 0, 255))

        p1 = [-1, -1]
        p2 = [-1, -1]
        if len(m_convex_hull_list) > 1:
            m_convex_hull_list.sort(key=lambda x: x['moment']['m00'],
                                    reverse=True)
            p1 = [
                int(m_convex_hull_list[0]['moment']['m10'] /
                    m_convex_hull_list[0]['moment']['m00']),
                int(m_convex_hull_list[0]['moment']['m01'] /
                    m_convex_hull_list[0]['moment']['m00'])
            ]
            p2 = [
                int(m_convex_hull_list[1]['moment']['m10'] /
                    m_convex_hull_list[1]['moment']['m00']),
                int(m_convex_hull_list[1]['moment']['m01'] /
                    m_convex_hull_list[1]['moment']['m00'])
            ]
            logger().debug('p1: {}, p2: {}'.format(p1, p2))
            degree_car = degrees(atan2(p2[1] - p1[1], p1[0] - p2[0]))
            degree_station = degrees(
                atan2(((p1[1] + p2[1]) / 2) - CarMonitor.STATION_POINT[1],
                      CarMonitor.STATION_POINT[0] - ((p1[0] + p2[0]) / 2)))
            degree = self._compress_degree_in_180(degree_car - degree_station,
                                                  360)
            a = np.array(
                [CarMonitor.STATION_POINT[0], CarMonitor.STATION_POINT[1]])
            b = np.array([(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2])
            u = b - a
            distance = np.linalg.norm(u)
        else:
            degree = CarMonitor.INVALID_DEGREE
            distance = CarMonitor.INVALID_DISTANCE

        if save_img:
            cv2.imwrite(path + '/result_mask.png', trim_img)
            self._draw_marker(img, CarMonitor.STATION_POINT[0],
                              CarMonitor.STATION_POINT[1], (255, 0, 0))
            if p1[0] != -1:
                self._draw_marker(img, (p1[0] + p2[0]) / 2,
                                  (p1[1] + p2[1]) / 2, (255, 0, 0))
                cv2.line(img,
                         tuple(p1),
                         tuple(p2),
                         color=(0, 0, 255),
                         thickness=2)
                cv2.line(img, (int(
                    (p1[0] + p2[0]) / 2), int((p1[1] + p2[1]) / 2)),
                         (int(CarMonitor.STATION_POINT[0]),
                          int(CarMonitor.STATION_POINT[1])),
                         color=(0, 255, 0),
                         thickness=2)
                cv2.putText(img,
                            'angle[deg]: ' + str(degree), (30, 100),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 255),
                            thickness=2)
                cv2.putText(img,
                            'distance: ' + str(distance), (30, 150),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1.0, (255, 255, 255),
                            thickness=2)
            cv2.imwrite(path + '/result.png', img)

        return degree, distance
 def __init__(self, back_color_hsv):
     logger().debug('CarMonitor init() start')
     self._back_color_hsv = back_color_hsv
     logger().debug('CarMonitor init() end')
def on_message(ws, message):
    logger().info('Received:{}'.format(message))
def on_close(ws):
    logger().info('Close')
def on_error(ws, error):
    logger().info('Error:{}'.format(error))