Exemple #1
0
    def __init__(self, vo, library):
        self.vo = vo
        self.library = library

        rospy.TopicSub('/vo/key', Frame, self.incoming_frame)
        self.pub_tmo = rospy.Publisher("/vo/tmo", Pose44)
        self.frameq = Queue()

        self.mark0 = Marker(1)
        self.mark1 = Marker(2)
Exemple #2
0
    def construct(self, csvFileIn, csvFileOut='grades_with_groundtruths.csv'):
        '''
		Assigns data to @self nmarkers, markers, paper and data from
		@param csvFileIn the CSV file that contains the grades 
		@param csvFileOut the CSV file that will store the @self data
		using a @self csvManager 

		@see self.getNumberOfMarkers
		@see self.defineMeanOfReviews
		@see self.defineAvgOfReviews
		@see self.getPaperReviews

		@see CSV.extractGradesColumn
		@see CSV.printGroundTruth
		@see CSV.extractData
		'''
        self.csvManager = CSV(csvFileIn, csvFileOut)
        self.nmarkers = self.csvManager.getNumberOfMarkers()
        if self.nmarkers == 0:
            print("File is empty")
        else:
            for i in range(self.nmarkers):
                self.markers.append(
                    Marker(self.csvManager.extractGradesColumn(i)))

            for i in range(1, len(self.markers[1].reviews) + 1):
                self.paper.add(self.defineMeanOfReviews(i),
                               self.defineAvgOfReviews(i),
                               self.getPaperReviews(i))

            self.csvManager.printGroundTruth(self)
            self.data = self.csvManager.extractData()
            self.main()
Exemple #3
0
    def __init__(self):
        super(bciApp,self).__init__(config_path = r'./config.js')

        self.PHASES = [ {'name':'start','next':'test','duration':1},
                        {'name':'test','next':'relax','duration':5},
                        {'name':'relax','next':'test','duration':3},
                        {'name':'rrelax','next':'stop','duration':1}]

        self.CODER = DefaultCoder()

        layout = {'screen': {'size': (1000, 250), 'color': (0, 0, 0), 'type': 'normal',
                             'Fps': 60, 'caption': 'this is an example'},
                  'ssvep1': {'class': 'sinBlock', 'parm': {'size': (150, 150), 'position': (125, 125),'borderon':True,
                        'bordercolor':(0,0,0),'anchor':'center','frequency': 6, 'visible': True, 'start': False}},
                  'ssvep2': {'class': 'sinBlock', 'parm': {'size': (150, 150), 'position': (375, 125),'borderon':True,
                        'bordercolor':(0,0,0),'anchor': 'center','frequency': 7, 'visible': True, 'start': False}},
                  'ssvep3': {'class': 'sinBlock', 'parm': {'size': (150, 150), 'position': (625, 125),'borderon':True,
                        'bordercolor':(0,0,0),'anchor':'center','frequency': 8, 'visible': True, 'start': False}},
                  'ssvep4': {'class': 'sinBlock', 'parm': {'size': (150, 150), 'position': (875, 125),'borderon':True,
                        'bordercolor':(255,0,0),'anchor': 'center', 'frequency': 9, 'visible': True, 'start': False}},
                  }

        self.gui = GuiIF(None,layout)
        _ = multiprocessing.Process(target=guiengine_proc,args=(self.gui.args,))
        _.start()
        self.gui.wait()

        sp_ip = self.configs['signal_processing']['sp_host_ip']
        sp_port = self.configs['signal_processing']['sp_host_port']
        self.marker = Marker((sp_ip,sp_port))

        self.TEST_NUM = 3
        self.test_count = 1
    def __init__(self):
        self.du = DU()
        self.vocab, self.recab = self.du.initialize_vocabulary()
        self.tag, self.retag = self.du.init_tag()  #载入标签和对应的id
        self.ids_arr = []
        for line in open(self.du.ids_path):
            line = line.strip()
            if len(line) > 0:
                temp = line.split(' ')
                for i in range(len(temp)):
                    try:
                        temp[i] = int(temp[i])
                    except Exception:
                        temp[i] = 3
                self.ids_arr.append(temp)
            else:
                self.ids_arr.append([])

#		self.train = json.load(open(self.du.train_path))
#		self.dev = json.load(open(self.du.dev_path))
#		self.test = json.load(open(self.du.test_path))

        self.model = Marker(
            vocab_size=FLAGS.vocab_size,
            embedding_size=FLAGS.emd_size,
            memory_size=FLAGS.mem_size,
            label_size=FLAGS.tag_size,
            batch_size=FLAGS.batch_size,
            max_ut_size=FLAGS.max_ut_size,
            max_gradient_norm=FLAGS.max_gradient_norm,
            learning_rate=FLAGS.learning_rate,
            learning_rate_decay_factor=FLAGS.learning_rate_decay_factor,
            use_lstm=False,
            train_mode=FLAGS.train)
Exemple #5
0
def _create_markers(steps, pois):
    markers = []
    for step in steps:
        poi = Poi.from_id(pois, step.id)
        marker = Marker(poi, step)
        markers.append(marker)
    return markers
Exemple #6
0
    def __init__(self, mode, library):
        self.mode = mode
        self.library = library

        rospy.TopicSub('/videre/images', ImageArray, self.display_array)
        rospy.TopicSub('/videre/cal_params', String, self.display_params)
        rospy.TopicSub('/vo/tmo', Pose44, self.handle_corrections)

        self.viz_pub = rospy.Publisher("/overlay", Lines)
        self.vo_key_pub = rospy.Publisher("/vo/key", Frame)
        self.Tmo = Pose()

        self.mymarker1 = Marker(10)
        self.mymarkertrail = [Marker(11 + i) for i in range(10)]
        self.trail = []

        self.vis = Vis()
def main():
    (rand_proc, tree_height) = parse_args()
    if isinstance(rand_proc, R3):
        marker = MarkerR3(tree_height)
    else:
        marker = Marker(tree_height)
    marker.run(rand_proc)
    print(marker.status())
    return 0
def main():
    image_fn = '/home/joni/smallbrains-nas1/array1/pseudopupil_joni/Spectrometer/DPP_cal_1_ty2/snap_2020-02-21_14.15.08.088000_0.tiff'
    
    fig, ax = plt.subplots()
    marker = Marker(fig, ax, [image_fn], None)
    pinhole = marker.run()    
    
    crop = pinhole[image_fn])
    pinhole_image = image_fn


    coodinates = get_xy_coordinates(image_fn)
Exemple #9
0
    def border_loop_markers(self):
        output = list()

        count = 0
        for l in self.border_loops:
            points = l.to_list()
            if len(points) > 3:
                color = get_color(count)
                count += 1
                for p in points:
                    output.append(Marker(p.x, p.y, color))

        return output
Exemple #10
0
def play():
    sprites = [
        Marker(4, 4)

        # Lava(0),
        # Lava(1),
        # Lava(2),
        # Lava(3),
        # Lava(4),
        # Lava(5),
        # Lava(6),
        # Lava(7)
    ]

    launch_single_tile(sprites)
Exemple #11
0
    def __init__(self):
        super(bciApp,self).__init__(config_path = r'./config.js')

        self.PHASES = [ {'name':'start','next':'test','duration':1},
                        {'name':'test','next':'relax','duration':7},
                        {'name':'relax','next':'test','duration':5},
                        {'name':'rrelax','next':'stop','duration':1}]

        self.CODER = DefaultCoder()
        
        w = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
        h = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
        
        camera_h = 2*240
        camera_w = 2*320

        layout = {'screen': {'size': (w, h), 'color': (0, 0, 0), 'type': 'normal',
                             'Fps': 60, 'caption': 'this is an example'},
                  'camera':{'class':'MjpegStream','parm':{'size':(camera_w,camera_h),'position':(int(w/2),int(h/2)),
                            'anchor':'center','visible':True,'start':True,'url':'http://192.168.1.1:8080/?action=stream'}},
                  'ssvep1': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w-320-65), int(0.5*h-240+30)),
                        'text':'forward','textsize':20,'frequency': 6.6, 'visible': True, 'start': False}},
                  'ssvep2': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w-320-65), int(0.5*h)),
                        'text':'left','textsize':20,'frequency': 7.6, 'visible': True, 'start': False}},
                  'ssvep3': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w-320-65), int(0.5*h+240-30)),
                        'text':'r-left','textsize':20,'frequency': 8.6, 'visible': True, 'start': False}},
                  'ssvep4': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w+320+65), int(0.5*h-240+30)),
                        'text':'backward','textsize':20,'frequency': 9.3, 'visible': True, 'start': False}},
                  'ssvep5': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w+320+65), int(0.5*h)),
                        'text':'right','textsize':20,'frequency': 12.2, 'visible': True, 'start': False}},
                  'ssvep6': {'class': 'sinCircle', 'parm': {'radius':65, 'position': (int(0.5*w+320+65), int(0.5*h+240-30)),
                        'text':'r-right','textsize':20,'frequency': 13.8, 'visible': True, 'start': False}},
                  }

        self.gui = GuiIF(None,layout)
        _ = multiprocessing.Process(target=guiengine_proc,args=(self.gui.args,))
        _.start()
        self.gui.wait()

        sp_ip = self.configs['signal_processing']['sp_host_ip']
        sp_port = self.configs['signal_processing']['sp_host_port']
        self.marker = Marker((sp_ip,sp_port))

        self.TEST_NUM = 12
        self.test_count = 1
        
        self.ROBOT = WIFIROBOT_CTR()
Exemple #12
0
def find_markers(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #blur = cv2.medianBlur(gray, 5)
    blur = cv2.GaussianBlur(gray, (3, 3), 0)
    __, thresh = cv2.threshold(blur, 100, 255, cv2.THRESH_BINARY)
    contours, __ = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
                                    cv2.CHAIN_APPROX_SIMPLE)

    markers = dict()

    for contour in contours:
        if small_area(contour):
            continue

        eps = 0.05 * cv2.arcLength(contour, closed=True)
        polygon = cv2.approxPolyDP(contour, eps, closed=True)

        if not_quadrilateral(polygon):
            continue

        polygon_fl = np.float32(polygon)
        tr_matrix = transform_matrix(polygon)
        transform = cv2.getPerspectiveTransform(polygon_fl, tr_matrix)

        # FIXME: Choose algorithm
        # Reuse thresholded image,
        # -- OR --
        # Run warpPerspective on "gray" threshold the result again.
        # In the latter case, the call to thresh.copy() is redundant.
        sq_marker = cv2.warpPerspective(thresh, transform, (WIDTH, HEIGHT))
        #__, sq_marker_bin = cv2.threshold(sq_marker, 0, 255,
        #                                  cv2.THRESH_BINARY + cv2.THRESH_OTSU)

        if no_black_border(sq_marker):
            continue

        marker = parse_marker(sq_marker)
        valid_marker, marker_id, rotations = validate_marker(marker)

        if not valid_marker:
            continue

        markers[marker_id] = Marker(marker_id, contour, polygon, rotations)

    return markers
Exemple #13
0
def updatemarker():
    # check the data against the marker regular expression to check if there is complete marker information in the received data
    global DATA
    MARKER_RE_MATCH = re.search(MARKER_REGEX, DATA)

    # as long as we still have more complete marker information...
    while MARKER_RE_MATCH != None:
        # find the first marker information from the received data
        MARKER = Marker(MARKER_RE_MATCH.group())
        # show that we have found something
        #print("Found marker {0}.".format(MARKER.number))
        # update information in the marker collection
        MARKERS.update_marker(MARKER)
        # remove outdated observations
        MARKERS.clean_outdated_markers(MARKER_TIMEOUT)
        # remove the processed data from the buffer
        DATA = DATA[MARKER_RE_MATCH.end():]
        # look for the next marker in the buffer
        MARKER_RE_MATCH = re.search(MARKER_REGEX, DATA)

        # send something arbitrary to the Zigbee dongle. This has no real function except to demonstrate how to send something.
        #ZIGBEE.write(b'Hello')

    if len(DATA) > BUFFER_SIZE:
        # something is going wrong, flush garbage data
        DATA = ""
    # indicate that the markers are global
    global ORIGIN
    global ROBOTA
    global OB1
    global OB2
    global OB3
    global FINISH

    # find all markers
    ORIGIN = MARKERS.get_marker('origin')
    ROBOTA = MARKERS.get_marker('robotA')
    OB1 = MARKERS.get_marker('ob1')
    OB2 = MARKERS.get_marker('ob2')
    OB3 = MARKERS.get_marker('ob3')
    FINISH = MARKERS.get_marker('finish')
Exemple #14
0
def index():
    user_agent = request.headers.get('User-Agent')
    data1 = request.get_data()
    data_json = json.loads(data1)
    poi_list = data_json["poi_list"]
    # for poi in poi_list:
    #     lat = poi["lat"]
    #     lng = poi["lon"]
    tuple_latlng_str = ["8.5208, 47.37288", "8.53410, 47.37290"]
    marker = tuple_latlng_str
    context = Context()

    # if center is not None:
    #     context.set_center(parse_latlng(center))
    # if zoom is not None:
    #     context.set_zoom(zoom)
    for coords in marker:
        context.add_object(Marker(parse_latlng(coords)))
    image = context.render(264, 264)

    return '<h1>Hello World! Your browser is {}</h1>'.format(user_agent)
Exemple #15
0
    def __init__(self,
                 _world,
                 _filename=None,
                 _friction=None,
                 _id=None,
                 _traditional=False):
        self.world = _world
        self.filename = _filename
        self.friction = _friction
        if self.filename is not None:
            _b_trad = 1 if _traditional else 0
            # print "=" * 80
            # print _b_trad
            # print "=" * 80
            self.id = papi.addSkeleton(self.world.id, _filename, _friction,
                                       _b_trad)
        else:
            self.id = _id

        # Initialize dofs
        _ndofs = papi.getSkeletonNumDofs(self.world.id, self.id)
        self.dofs = [Dof(self, i) for i in range(_ndofs)]
        self.name_to_dof = {dof.name: dof for dof in self.dofs}

        # Initialize bodies
        _nbodies = papi.getSkeletonNumBodies(self.world.id, self.id)
        self.bodies = [Body(self, i) for i in range(_nbodies)]
        self.name_to_body = {body.name: body for body in self.bodies}
        self.controller = None

        # Initialize markers
        self.markers = list()
        for body in self.bodies:
            for j in range(body.num_markers()):
                m = Marker(body, j)
                self.markers.append(m)
Exemple #16
0
 def __init__(self):
     print '<===INIT QUALIFY===>'
     self.marker = Marker()
     self.gate = Gate()
Exemple #17
0
    def __init__(self, stims, Q_c2g, E_g2c, server_address):
        """
        stims:  dict to define a stimulus.
                eg. stims = {'cue':{'class':'Block','parm':{'size':(100,40),'position':(0,0)}}}
        Q_c2g: multiprocessing.Queue, used for accepting stimulus control command from core process
        kwargs: server_address = ?, the target server's address to accept marker
        
        property for describe screen
        size: (width,height)
        type: fullscreen/normal
        frameless: True/False
        color: (R,G,B)
        caption: string
        Fps: int, strongly suggest you set Fps as the same with system's Fps
        """

        self.Q_c2g = Q_c2g
        self.E_g2c = E_g2c
        self.marker_on = False
        self.marker_event = {}
        self.stp = False
        self.lock = threading.Lock()

        pygame.init()
        #初始化screen
        # 当且仅当window环境变量设置成功且fullscreen时,SCREEN_SYNC=True
        if stims['screen']['type'].lower() == 'fullscreen':
            self.screen = pygame.display.set_mode(
                (0, 0), FULLSCREEN | DOUBLEBUF | HWSURFACE, 32)
        else:
            # 将窗口置中
            if OS == 'windows':
                w, h = stims['screen']['size']
                x = int((SCRW - w) / 2.)
                y = int((SCRH - 50 - h) / 2.) - 50  # 扣除任务栏高度
                os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % (x, y)

            self.screen = pygame.display.set_mode(stims['screen']['size'],
                                                  NOFRAME | DOUBLEBUF, 32)
            SCREEN_SYNC = False

        self.screen_color = stims['screen']['color']
        self.screen.fill(self.screen_color)
        pygame.display.set_caption(stims['screen']['caption'])
        self.Fps = stims['screen']['Fps']
        del stims['screen']

        self.ask_4_update_gui = False  #线程接收到刷新请求后,通知主进程刷新
        self.update_in_this_frame = False  #主进程在一帧真实的刷新帧中确定能够进行刷新
        self.__update_per_frame_list = []  #接受帧刷新对象

        if server_address is None:

            class Marker():
                def __init__(self, sa):
                    pass

                def send_marker(self, marker):
                    raise Exception(
                        'marker_sender was not initilized because server_address parameter was not given'
                    )

        self.marker_sender = Marker(server_address)

        #注册刺激,生成实例
        for ID in stims:
            element = stims[ID]
            clas = element['class']
            if clas in MODULES:
                self.stimuli[ID] = MODULES[clas](self.screen,
                                                 **element['parm'])

        backthread = threading.Thread(target=self.backthreadfun,
                                      args=(),
                                      daemon=True)
        backthread.start()
Exemple #18
0
from marker import Marker
import random

learn=Marker()
learn.load()
x={"speed":0,"sentenceSpeed":0}
i=0
while i<10:
    x["speed"]=random.random()*5+3
    x["sentenceSpeed"]=random.random()*3/15
    i+=1
    y0,y1=learn.cal_score(x)
    print (str(x["speed"])+"word/s : score"+str(y0*100))
    print (str(x["sentenceSpeed"])+"space/s : score"+str(y1*100))
Exemple #19
0
 def __init__(self) -> None:
     self._zero_metadata: Metadata = {}
     self._marker = Marker("api_route", default=self._zero_metadata)
Exemple #20
0
import tornado.ioloop
import tornado.websocket
import tornado.options
import tornado.web
import tornado.escape
import uuid
import os
import redis
from marker import Marker
from tornado.options import define, options
from analyzer import Analyzer

define("port", default=8880, help="run on the given port", type=int)

DATASTORE_KEY = "15s_learning_data_"
G_Marker = Marker()
#store data
#G_Database = redis.Redis(host='localhost', port=6379, db=0)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


class TextSocketHandler(tornado.websocket.WebSocketHandler):
    waiters = set()
    Store_Number = 101
    Store_y = 0

    cache = []
Exemple #21
0
 def __init__(self):
     # 0 is the bottom part home and is player 2s home of the board. 25 is the top home and is player 1's
     # this is player 2's home, bottom right
     self.board = \
     [[], \
     [Marker(1), Marker(1)], \
     [], [], [], [], \
     [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
     [], \
     [Marker(2), Marker(2), Marker(2)], \
     [], [], [], \
     [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)], \
     [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
     [], [], [], \
     [Marker(1), Marker(1), Marker(1)], \
     [], \
     [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)], \
     [], [], [], [], \
     [Marker(2), Marker(2)], \
     [],\
     [],\
     []]
Exemple #22
0
x = 0
y = 0

book = xlrd.open_workbook('Оборотно-сальдовая.xls',
                          encoding_override='cp1251',
                          formatting_info=True)  # open exel-table
sheet = book.sheet_by_index(0)

new_book = xlwt.Workbook()  # creating new exel-table for sorted data
new_book_sheet = new_book.add_sheet('breed_to_breath')

check = Reader().ids(file='param.txt')  # reading item ids from file

for i in range(7, sheet.nrows - 6):  # the CORE... cycle for soring data
    cell = sheet.cell_value(i, 0)
    marker = Marker().marker(cell)
    if marker in check:
        checked.append(marker)
        k = sheet.cell_value(i + 1, 5)  # quantity of item at the end of term
        p = sheet.cell_value(i, 5)  # price at the end of term
        print(marker, 'kol-vo:', k, 'Price:', p)
        new_book_sheet.write(x, y, cell)
        new_book_sheet.write(x, y + 1, k)
        new_book_sheet.write(x, y + 2, p)
        x += 1

print(Checker().checked(check, checked))
new_book.save('sort-test.xls')
'''
for rownum in range(sheet.nrows):
    row = sheet.row_values(rownum)
Exemple #23
0
def testWin():
    game.board.board = \
    [[], \
    [], \
    [], [], [], [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], \
    [Marker(2), Marker(2), Marker(2)], \
    [], [], [], \
    [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], [], [], \
    [], \
    [], \
    [], \
    [], [],
    [], \
    [Marker(2), Marker(2)], \
    [], [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)],[],[]]

    if (not (game.gameComplete() == 1)):
        raise AssertionError()
    print("testWinOff() passed")
    # read new data (if any) from the TCP connection
    try:
        DATA += LMSOCKET.recv(BUFFER_SIZE)
    except socket.error:
        # no data is available on the socket, sleep for 100ms
        sleep(0.1)
        # try again
        continue

    # check the data against the marker regular expression to check if there is complete marker information in the received data
    MARKER_RE_MATCH = re.search(MARKER_REGEX, DATA)

    # as long as we still have more complete marker information...
    while MARKER_RE_MATCH != None:
        # find the first marker information from the received data
        MARKER = Marker(MARKER_RE_MATCH.group())
        # show that we have found something
        #print("Found marker {0}.".format(MARKER.number))
        # update information in the marker collection
        MARKERS.update_marker(MARKER)
        # remove outdated observations
        MARKERS.clean_outdated_markers(MARKER_TIMEOUT)
        # remove the processed data from the buffer
        DATA = DATA[MARKER_RE_MATCH.end():]
        # look for the next marker in the buffer
        MARKER_RE_MATCH = re.search(MARKER_REGEX, DATA)

        # send something arbitrary to the Zigbee dongle. This has no real function except to demonstrate how to send something.
        ZIGBEE.write(b'Hello')

    if len(DATA) > BUFFER_SIZE:
Exemple #25
0
def testBearOff():
    game.board.board = \
    [[], \
    [], \
    [], [], [], [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], \
    [Marker(2), Marker(2), Marker(2)], \
    [], [], [], \
    [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], [], [], \
    [Marker(1)], \
    [Marker(2), Marker(2)], \
    [], \
    [], [Marker(1), Marker(1)], [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)],
    [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)], \
    [Marker(1), Marker(1)], \
    [],[],[]]
    game.players[1].moves = [4, 5, 6, 6]
    if game.players[1].move(game.board, 24, 1):
        raise AssertionError()
    if not game.players[1].move(game.board, 17, 1):
        raise AssertionError()
    game.board.printBoard()
    print(game.board.getBoardState(1))
    if not game.players[1].move(game.board, 23, 1):
        raise AssertionError()
    if not game.players[1].move(game.board, 23, 1):
        raise AssertionError()

    game.board.board = \
    [[], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2),Marker(2), Marker(2), Marker(2),Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], [], [], [], \
    [], \
    [], \
    [], \
    [], [], [], \
    [], \
    [], \
    [], [], [], \
    [Marker(1)], \
    [], \
    [], \
    [], [Marker(1), Marker(1)], [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)],
    [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)], \
    [], \
    [Marker(1), Marker(1)],[],[]]

    game.players[2].moves = [4, 5, 6]
    if not game.players[2].move(game.board, 1, 1):
        raise AssertionError()
    game.board.board = \
    [[], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2), Marker(2),Marker(2), Marker(2), Marker(2),Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], [], [], [], \
    [], \
    [], \
    [], \
    [], [], [], \
    [], \
    [], \
    [], [], [], \
    [], \
    [], \
    [], \
    [], [Marker(1), Marker(1)], [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)],
    [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)], \
    [], \
    [Marker(1),Marker(1), Marker(1)],[],[]]

    game.players[1].moves = [4, 5, 6]
    if not game.players[1].move(game.board, 23, 1):
        raise AssertionError()
    if game.players[1].move(game.board, 25, 1):
        raise AssertionError()
    game.board.printBoard()

    print("testBearOff() passed")
Exemple #26
0
 def test_magic(self):
     m = Marker()
     self.assertTrue(m.checkDnsMagic())
 def __init__(self, robot_name, marker_namespace):
     super(TrackerRecording, self).__init__(robot_name)
     self.marker = Marker(marker_namespace)
     self.tracker = True
Exemple #28
0
def testKnockedOff():
    game.board.board = \
    [[], \
    [ Marker(1)], \
    [], [], [], [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], \
    [Marker(2), Marker(2), Marker(2)], \
    [], [ Marker(1)], [Marker(2)], \
    [], \
    [Marker(2), Marker(2), Marker(2), Marker(2), Marker(2)], \
    [], [], [], \
    [Marker(1)], \
    [Marker(2)], \
    [Marker(2), Marker(2)], \
    [], [Marker(1), Marker(1)], [Marker(1), Marker(1), Marker(1), Marker(1), Marker(1)],
    [Marker(1), Marker(1), Marker(1), Marker(1)], \
    [Marker(1)], \
    [],[],[]]

    game.players[2].moves = [2, 5, 6]
    if not game.players[2].move(game.board, 19, 1):
        raise AssertionError()
    game.players[1].moves = [2, 5, 6]
    if game.players[1].move(game.board, 1, 1):
        raise AssertionError()
    if not game.players[1].move(game.board, 26, 1):
        raise AssertionError()

    game.players[1].moves = [1, 5, 6]
    if not game.players[1].move(game.board, 10, 1):
        raise AssertionError()

    game.players[2].moves = [1, 1, 6]
    if game.players[2].move(game.board, 1, 1):
        raise AssertionError()

    if not game.players[2].move(game.board, 27, 1):
        raise AssertionError()
Exemple #29
0
    def run(self):
        """ 
        Main application function. Starts image stream from real or simulated
        camera (or loads a single image); initialises any pipeline modules; and
        then enters the main pipeline processing loop. Once in the loop the
        pipeline runs until a shutdown flag is set. The message queue from the
        simulator, if there is one, is checked on each loop iteration for image
        data and synchronisation messages (such as a shutdown message).
        
        """

        self.running = True
        if self.fwcam and not self.single_img:
            self.fwcam.start(interactive=True)
            time.sleep(1)
            self.orig = np.copy(np.asarray(self.fwcam.current_image))
            self.canv = np.copy(self.orig)
            self.init_output = Pipeline_Output(sim=False)
            self.init_output.cam = Camera_Vals(camera_id='chameleon1')
            self.init_output.markers.append(Marker(cam=self.init_output.cam))
        elif self.options.simulate is not None:
            self.q2sim = multiprocessing.Queue()
            self.q2pipe = multiprocessing.Queue()
            queues = self.q2sim, self.q2pipe
            args = queues, self.options
            process = multiprocessing.Process(name='child',
                                              target=GL_Simulator,
                                              args=args)
            self.processes.append(process)
            process.start()
            self.init_output = Pipeline_Output(sim=True)
            self.q2sim.put(copy.deepcopy(self.init_output))
            incoming = self.q2pipe.get()
            if 'stop' in incoming:
                self.shutdown()
            elif 'simulglob' in incoming:
                _, self.orig, output = incoming
                self.outputs.append(copy.deepcopy(output))
                self.init_output.cam = self.outputs[0].cam

        m = []
        if self.options.nr_modules == 0:
            self.logger.info('running an empty pipeline')
        else:
            if self.options.nr_modules >= 1:
                self.modules.append(ContourFinder(pipeline=self))
            if self.options.nr_modules >= 2:
                self.modules.append(EllipseFitter(pipeline=self))
            if self.options.nr_modules >= 3:
                self.modules.append(PoseEstimatorA(pipeline=self))
        self.logger.info('running with %d modules' % self.options.nr_modules)

        if self.options.windows:
            for module in self.modules:
                if not (module.__class__.__name__ == 'PoseEstimatorA'):
                    self.windows.append(module.__class__.__name__)

        if self.single_img:
            for module in self.modules:
                module.run()
                if self.options.windows:
                    cv2.imshow(module.__class__.__name__, self.canv)
                    cv2.waitKey(2)
                    time.sleep(5)
                self.shutdown()

        while self.running:
            if self.fwcam:
                self.orig = np.copy(np.asarray(self.fwcam.current_image))
                if self.options.windows:
                    cv2.imshow("original", self.orig)
            elif (self.options.simulate
                  is not None) and self.outputs[-1].end_time:
                incoming = self.q2pipe.get()
                if 'stop' in incoming:
                    self.running = False
                    continue
                elif 'simulglob' in incoming:
                    _, self.orig, output = incoming
                    self.outputs.append(copy.deepcopy(output))
                    self.new_output = True
                else:
                    self.logger.error('unknown in queue: \'%s\'' % incoming)
                    self.shutdown()
            self.canv = np.copy(self.orig)
            for module in self.modules:
                module.run()
                classname = module.__class__.__name__
                if not (self.options.windows
                        and classname == 'PoseEstimatorA'):
                    cv2.imshow(module.__class__.__name__, self.canv)
            self.loops += 1
            self.outputs[-1].complete()
            if self.ellipses:
                self.ellipses = None
            if self.options.windows:
                cv2.waitKey(2)
            if time.time() - self.start >= self.options.simtime:
                self.running = False
        self.shutdown()
Exemple #30
0
    def _find_marker_candidates(self, contours, max_squared_distance=100):
        """Search for possible markers amongst a number of contours."""
        # For each contour: decide if it's a possible marker.
        possible_markers = []
        for c in contours:
            # Approximate to polygon.
            eps = len(c) * 0.05
            approx_curve = cv2.approxPolyDP(curve=c, epsilon=eps, closed=True)
            # Only consider polygons that have 4 points and are convex.
            if not len(approx_curve) == 4:
                continue
            if not cv2.isContourConvex(approx_curve):
                continue

            # Distance between points has to be large enough.
            min_dist = float("inf")
            for i in range(4):
                side = approx_curve[i] - approx_curve[(i + 1) % 4]
                side = side[0]
                squared_side_length = np.dot(side, side)
                min_dist = min(min_dist, squared_side_length)
            if min_dist < self.min_contour_length_allowed:
                continue

            # Prepare marker for saving.
            m = [np.array([p[0][0], p[0][1]]) for p in approx_curve]
            v1 = m[1] - m[0]
            v2 = m[2] - m[0]
            o = (v1[0] * v2[1]) - (v1[1] * v2[0])
            if o < 0:
                m[1], m[3] = m[3], m[1]
            possible_markers.append(np.array(m))

        # Mask elements with corners too close to each other.
        too_near_candidates = []
        for i in range(len(possible_markers)):
            m1 = possible_markers[i]
            for j in range(i + 1, len(possible_markers)):
                m2 = possible_markers[j]
                squared_distance = 0
                for c in range(4):
                    v = m1[c] - m2[c]
                    squared_distance += np.dot(v, v)
                squared_distance /= 4

                if squared_distance < max_squared_distance:
                    too_near_candidates.append((i, j))

        # Mask element with smaller perimeter.
        removal_mask = np.zeros(len(possible_markers))
        for i in range(len(too_near_candidates)):
            p1 = cv2.arcLength(
                curve=possible_markers[too_near_candidates[i][0]], closed=True)
            p2 = cv2.arcLength(
                curve=possible_markers[too_near_candidates[i][1]], closed=True)
            if p1 > p2:
                removal_index = too_near_candidates[i][0]
            else:
                removal_index = too_near_candidates[i][1]
            removal_mask[removal_index] = 1

        # Return only unmasked elements.
        detected_markers = []
        for i in range(len(possible_markers)):
            if not removal_mask[i]:
                detected_markers.append(Marker(possible_markers[i]))

        return detected_markers