Example #1
0
    def __init__(self,
                 mode=1,
                 position=glm.vec3(1, 0, 0),
                 target=glm.vec3(0),
                 worldUp=glm.vec3(0, 1, 0)):

        # settings
        self.fpsRotationSpeed = 0.005  # speed with which the camera rotates in fps mode
        self.moveSpeed = 0.125  # speed with which the camera moves in fps mode
        self.tbRotationSpeed = 0.015  # speed with which the camera rotates in trackball mode
        self.panSpeed = 0.006  # speed with which the camera pans in trackball mode
        self.zoomSpeed = 0.25  # speed with which the camera zooms (used for Z axis in trackball mode)
        self.enableAllControls = False  # enable movement while in trackball mode and pan/zoom while in fps mode
        self.movementSmoothing = 0.25  # higher numbers result in stronger smoothing and delayed movement
        self.rotationSmoothing = 0.3  # higher numbers result in stronger smoothing and delayed rotation
        self.worldUp = worldUp  # worlds up vector
        self.mode = mode  # 0 = trackball, 1 = first person
        self.movementSpeedMod = 1.0  # temporary modified movement speed, will be reset every frame

        # cameras internal state (DO NOT WRITE)
        self._movementInput = glm.vec3(0)
        self._rotationInput = glm.vec2(0)
        self._desiredTransform = Transform(
        )  # Transform(position)  # desired transform based on inputs
        self._desiredTargetDistance = 0  # desired distance along the front vector where the center for trackball mode lives
        self._currentTransform = Transform(
        )  #Transform(position)  # transform object describing orientation and position of camera
        self._currentTargetDistance = 0  # distance along the front vector where the center for trackball mode lives
        self.setPosition(position)
        self.setTarget(target)

        # variables depending on state, they are automatically updated when calling the Camera.update() (DO NOT WRITE, only read)
        self.modelMatrix = self._currentTransform.mat4()
        self.viewMatrix = glm.inverse(self.modelMatrix)
Example #2
0
def test_rotate_vector():
    v = Vec3(1, 1, 0)

    q1 = Quat.from_rotation_on_axis(0, np.pi / 3)
    q2 = Quat.from_rotation_on_axis(1, np.pi / 3)
    q3 = Quat.from_rotation_on_axis(2, np.pi / 3)

    t1 = Transform(q1, Vec3.zero())
    t2 = Transform(q2, Vec3.zero())
    t3 = Transform(q3, Vec3.zero())

    # forward rotation
    v1 = t1.rotate(v)
    v2 = t2.rotate(v)
    v3 = t3.rotate(v)

    theta1 = (60) * np.pi / 180.0
    v1_true = Vec3(1, math.cos(theta1), math.sin(theta1))
    v2_true = Vec3(math.cos(theta1), 1, -math.sin(theta1))

    theta2 = (45 + 60) * np.pi / 180.0
    v3_true = math.sqrt(2) * Vec3(math.cos(theta2), math.sin(theta2), 0)

    assert v1 == v1_true
    assert v2 == v2_true
    assert v3 == v3_true

    # inverse rotate
    v1_rev = t1.inverse_rotate(v1_true)
    v2_rev = t2.inverse_rotate(v2_true)
    v3_rev = t3.inverse_rotate(v3_true)

    assert v == v1_rev
    assert v == v2_rev
    assert v == v3_rev
Example #3
0
def test_finte():
    q1 = Quat(10000000000, 210000000000, 310000000000, -2147483647)
    q2 = Quat(np.nan, 210000000000, 310000000000, -2147483647)
    q3 = Quat(np.inf, 210000000000, 310000000000, -2147483647)
    q4 = Quat(0.0, 210000000000, np.NINF, -2147483647)

    v1 = Vec3(10000000000, 210000000000, 310000000000)
    v2 = Vec3(np.nan, 210000000000, 310000000000)
    v3 = Vec3(np.inf, 210000000000, 310000000000)
    v4 = Vec3(0.0, 210000000000, np.NINF)

    t1 = Transform(q1, v1)
    assert t1.is_finite()
    assert not t1.is_nan()

    t2 = Transform(q1, v2)
    assert not t2.is_finite()
    assert t2.is_nan()

    t3 = Transform(q3, v1)
    assert not t3.is_finite()
    assert t3.is_nan()

    t4 = Transform(q4, v4)
    assert not t4.is_finite()
    assert t4.is_nan()
Example #4
0
    def __init__(self, content=None, parent=None):
        Element.__init__(self, content, parent)

        if isinstance(content, str):
            self._transform = Transform()
            self._computed_transform = self._transform
        else:
            self._transform = Transform(content.get("transform", None))
            self._computed_transform = self._transform
            if parent:
                self._computed_transform = self._transform + self.parent.transform
Example #5
0
def test_normalize():
    q1 = Quat(0.4619398, 0.1913417, 0.4619398, 0.7325378)  # 45 around X then Y then Z
    t1 = Transform(q1, Vec3.zero())

    assert t1.is_normalized()

    q2 = Quat(3, 0, 4, 7)
    t2 = Transform(q2, Vec3.zero())
    assert not t2.is_normalized()

    t2.normalize()
    assert t2.is_normalized()
Example #6
0
    def _build_model(self):
        """Build traning model.

        First embed user/item inputs into training dimension, then feed them in 
        LSTMCell. Further affine the matrics into emission dimension after LSTM
        and emit the prediction.
        """
        phase = 'ENCODE'
        with tf.variable_scope(phase):
            self.encode_user = Transform(self.user_input, self.user_hparas,
                                         phase)
            self.encode_item = Transform(self.item_input, self.item_hparas,
                                         phase)

        phase = 'LSTM'
        with tf.variable_scope(phase):
            self.lstm_user = LSTM(self.encode_user.output, self.user_hparas)
            self.lstm_item = LSTM(self.encode_item.output, self.item_hparas)

        phase = 'AFFINE'
        with tf.variable_scope(phase):
            self.trans_user = Transform(self.lstm_user.output,
                                        self.user_hparas, phase)
            self.trans_item = Transform(self.lstm_item.output,
                                        self.item_hparas, phase)

        phase = 'EMISSION'
        with tf.variable_scope(phase):
            self.dynamic_state = tf.einsum('ijl,kjl->jik',
                                           self.trans_user.output,
                                           self.trans_item.output,
                                           name='dynamic_state')
            self.stationary_state = tf.matmul(self.user_stationary_factor,
                                              self.item_stationary_factor,
                                              transpose_b=True,
                                              name='stationary_state')

            if self.loss_function == 'log_loss':
                logits = tf.add(self.dynamic_state * 0.5,
                                self.stationary_state * 0.5,
                                name='logits')
                self.logits = tf.nn.sigmoid(logits, name='logits_activation')

            elif self.loss_function == 'rmse':
                logits = tf.add(self.dynamic_state,
                                self.stationary_state,
                                name='logits')
                self.logits = tf.nn.relu(logits, name='logits_activation')
            else:
                raise NotImplementedError(
                    "Didn't implement the loss function yet.")

            self.logits_last = self.logits[-1, :, :]
Example #7
0
 def __init__(self, trans=[0] * 6, vel=[0] * 6, radius=0.25):
     # cosmetic name, specific to this instance
     self.name = ''
     # set spatial member vars
     self.position = Transform(is_velocity=False,
                               pos=trans[:3],
                               rot=trans[3:])
     self.velocity = Transform(is_velocity=True, pos=vel[:3], rot=vel[3:])
     self.radius = 0.25
     # set simulation parameters
     self.vote_exit = False
     self.force_exit = False
     # metrics; add to this for output
     self.metrics = dict()
Example #8
0
def run_etl(filename):
    logger.info("application ran")
    start = time.time()
    app = Extract()
    raw_data_list = app.get_data_from_bucket(filename) # extract output
    end_extract = time.time()
    extract_time = round(end_extract - start, 4)
    print(f"Extract time: {extract_time}")
    logger.info(f"Extract time: {extract_time}")
    apple = Transform()
    transformed_data, transformed_drink_menu_data = apple.transform_new_data(raw_data_list) # raw data into transform returns transformed data and drinks dic

    end_transform = time.time()
    transform_time = round(end_transform - end_extract,4)
    logger.info(f"Transform time: {transform_time}")
    print(f"Transform time: {transform_time}")
    appley = Load()

    appley.save_transaction(transformed_data) # populate RDS instance with cleaned data.
    appley.save_drink_menu(transformed_drink_menu_data) # generate drinks menu
 
    end_load = time.time()
    load_time = round(end_load - end_transform, 4)
    logger.info(f"Loading time: {load_time}")
    total_time = extract_time + transform_time + load_time
    logger.info(f"total time: {total_time}")
    print(f"Load time: {load_time}\nTotal time: {total_time}")
Example #9
0
    def __init__(self, scene_mgr):
        self.scene_mgr = scene_mgr
        self.transform = Transform(self)
        self.components = {}

        self.children = []
        self.parent = None
Example #10
0
def main(args):
    workdir = Path(args.workdir)
    logger = get_logger()
    logger.info(f'config:\n{args}')
    state = Saver.load_best_from_folder(workdir, map_location='cpu')

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    logger.info(f'use device: {device}')

    num_points = len(args.data.symmetry)
    model = models.__dict__[args.model.name](num_points)
    model.load_state_dict(state['model'])
    model.to(device)

    # datasets
    valtransform = Transform(args.dsize, args.padding, args.data.meanshape,
                             args.data.meanbbox)
    valdata = datasets.__dict__[args.data.name](**args.data.val)
    valdata.transform = valtransform
    valloader = DataLoader(valdata,
                           args.batch_size,
                           False,
                           num_workers=args.num_workers,
                           pin_memory=False)

    score_fn = IbugScore(args.left_eye, args.right_eye)
    evalmeter = evaluate(model, valloader, score_fn, device)
    logger.info(evalmeter)
    def __init__(self, da):
        self.display_file = DisplayFile()
        self.draw_counter = 0
        self.da = da

        da_width = da.get_allocation().width
        da_height = da.get_allocation().height

        # Window and viewport start with the same size as the drawing area,
        # but compensating for the clipping border size (otherwise you
        # wouldn't see by default a point drawn at 0,0).
        self.window = Window(-cbz, -cbz, da_width - cbz, da_height - cbz)
        self.viewport = Viewport(-cbz, -cbz, da_width - cbz, da_height - cbz)

        self.transform = Transform()

        # Pass reference to window for Transform and Viewport
        self.transform.setWindow(self.window)
        self.viewport.setWindow(self.window)

        # To verify that both normalize() and denormalize() work
        # print(self.transform.normalize(0,0))
        # print(self.transform.normalize(self.window.getWidth(),self.window.getHeight()))
        # print(self.transform.denormalize(-1,-1))
        # print(self.transform.denormalize(1,1))

        self.projection = 'parallel'
Example #12
0
def etl_fact_draw_main(engine_source, engine_target,chunksize=5000,record_file='etl_fact_draw.record'):
    """绘图事实表的ETL

    :param engine_source: 源数据库引擎
    :param engine_target: 目标数据库引擎
    """
    extract = Extract(engine_source,chunksize,record_file)
    transform = Transform()
    load = Load(engine_target)
    # 抽取数据
    df_industry,df_draw_gen = extract.extract_main()
    logging.info('Extract datasets completed.')

    for k,df_draw in enumerate(df_draw_gen,1):
        logging.info('Round %d, From obs.%d to obs.%d,start.' % \
                     (k, (k-1)*chunksize, k*chunksize))
        # 清理、转换数据
        df_clean = transform.transform_main(df_industry, df_draw)
        logging.info('Round %d, Data cleaning completed.'%k)

        try:
            load.load_main(df_clean)
            logging.info('Round %d, loading %d obs. Secceed '%(k,len(df_clean)))
            with open(record_file,'w') as f:
                f.write(str(max(df_draw['id'])))
        except Exception as e:
            df_clean[['drawGuid', 'marketGuid']].to_csv('unsecceed_samples.csv', mode='a',index=False)
            logging.error('Round %d,%s' %(k,e))
            raise
def process_image(file_name, path, show):
    """
    Loads a given image path, and applies the pipeline to it

    :param file_name: The name of the file (without extension)
    :param path: Path to the input (image, video) to process.
    :param show: Show the outcome

    :return: None
    """

    # load the image
    image = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    height, width = image.shape[:2]

    # initialize the objects
    threshold = Threshold()
    lane = Lane(height=height)
    camera = Camera(image_size=(width, height))
    transform = Transform(width=width, height=height)

    # process the frame
    output = pipeline(image, camera, threshold, transform, lane)

    # save the output
    cv2.imwrite(f'data/processed/output_images/{file_name}.jpg', output)
    def create(self, objDest):
        vertices = []
        faces = []

        # read file and get rid of '\n' at the end of each line.
        with open(objDest) as f:
            lines = f.readlines()
        lines = [line.strip() for line in lines]

        # parse vertices
        for line in lines:
            if line != '' and line[0] is 'v':
                vertexLine = line.split(' ')
                # create vertex
                vertices.append(
                    Vec3D(float(vertexLine[1]), float(vertexLine[2]),
                          float(vertexLine[3]), 1.0))

        # parse faces
        for line in lines:
            if line != '' and line[0] is 'f':
                # find vertex indices
                faceElements = [int(e) for e in line.split(' ')[1:]]
                faceVertices = []
                for faceElement in faceElements:
                    faceVertices.append(vertices[faceElement - 1].clone())
                # create face with color
                faces.append(Face3D(faceVertices, [0.6, 0.6, 0.8]))

        # create object with faces
        return Model3D(
            Transform(Vec3D(0.0, 0.0, 0.0, 1.0), Vec3D(0.0, 0.0, 0.0, 1.0),
                      Vec3D(1.0, 1.0, 1.0, 1.0)), faces)
Example #15
0
    def __init__(self,
                 teach_file,
                 repeat_files=None,
                 im_time_files=None,
                 gps_files=None,
                 gps_time_files=None):
        if repeat_files is None:
            repeat_files = []
        if im_time_files is None:
            im_time_files = {}
        if gps_files is None:
            gps_files = {}
        if gps_time_files is None:
            gps_time_files = {}

        # Read teach run transforms from file
        transforms_temporal = np.loadtxt(teach_file, delimiter=",")
        self.teach_id = int(transforms_temporal[0, 0])
        self.vertices = {}
        self.matches = {}

        # Add teach run vertices
        for row in transforms_temporal:
            transform = Transform(np.array([row[4:7], row[8:11], row[12:15]]),
                                  np.array([row[7], row[11], row[15]]))
            self.add_vertex(row[0], row[1], row[2], row[3], transform, True)

        self.add_prev_ids()

        # If repeat run transforms, add those to graph
        for run_file in repeat_files:
            self.add_run(run_file)

        self.add_timestamps(im_time_files)
        self.add_gps(gps_files, gps_time_files)
Example #16
0
    def __init__(self,
                 fname='/dev/ttyACM0',
                 brate=1000000,
                 dim=(12, 10),
                 gamma=2.2):
        """
Initialise a LedScreen object.

>>> screen = LedScreen()
        """
        if type(dim) not in (tuple, list) or len(dim) != 2:
            raise ValueError("Invalid dimension. Format is tuple(x,y)")
        self.tty = uspp.SerialPort(fname, timeout=0)
        #self.tty = uspp.SerialPort(fname, speed=brate, timeout=0)
        os.environ['LEDWALL_TTY'] = fname
        os.system("stty -F $LEDWALL_TTY " + str(brate))
        self.w, self.h = dim
        self.buf = [(0, 0, 0)] * self.w * self.h
        self.transform = Transform(*dim)

        gamma = float(gamma)
        max_gamma = 255.**gamma
        self.gamma_map = [
            int((1 + 2 * x**gamma / (max_gamma / 255.)) // 2)
            for x in xrange(256)
        ]
        for i, v in enumerate(self.gamma_map):
            if v == 254:
                self.gamma_map[i] = 253
Example #17
0
 def __init__(self):
     self._type = ''
     self._id = ''
     self._category = ''
     self._level = ''
     self.guid = guid()
     self.transform = Transform()
Example #18
0
def etl_fact_macro_details(source_engine, target_engine):
    """fact_macro_details的etl主函数

    从235 tag_detail表etl到240 fact_macro_details表
    :param source_engine: 源数据库引擎
    :param target_engine: 目标数据库引擎
    """
    extract = Extract(source_engine, target_engine)
    transform = Transform()
    load = Load(target_engine)
    record = Record(table='fact_macro_detail', record_path='rec.cfg')

    start_params = record.get_record()
    divisions = extract.std_divisions()

    for i in range(start_params['rounds']):
        start_id = start_params['update_id'] + i * start_params['chunksize'] + 1
        end_id = start_params['update_id'] + (
            i + 1) * start_params['chunksize'] + 1

        tag_details = extract.tag_details(start_id, end_id)
        if len(tag_details) == 0:
            continue
        macro_details = transform.compile_datasets(tag_details, divisions)
        load.loading(macro_details)
        update_id = tag_details['id'].max() if tag_details['id'].max(
        ) else start_params['update_id']
        record.update_record(update_id)
Example #19
0
def test_init_and_eq_and_ne():
    t1 = Transform()
    assert t1.rotation == Quat.identity()
    assert t1.translation == Vec3.zero()

    rot = Quat.from_rotation_on_axis(2, np.pi)
    trans = Vec3(1, 2, 3)
    t2 = Transform(rot, trans)
    assert t2.rotation == rot
    assert t2.translation == trans

    t3 = Transform.identity()

    assert t1 == t3
    assert t1 != t2
    assert t3 != t2
Example #20
0
    def __init__(self,
                 xres,
                 yres,
                 title,
                 fullscreen=False,
                 vsync=False,
                 samples=0):
        self._closeIssued = False
        self._window = None
        self.gameTime = 0

        self.keyMap = defaultdict(lambda: False)
        self.mousePosition = vec2(0, 0)
        self.mouseDelta = vec2(0, 0)
        self.mouseWheelPosition = 0

        self.cameraTransform = Transform()

        self.resolution = vec2(0, 0)
        self.updateObjects = []

        self._init(xres, yres, title, fullscreen, vsync, samples)

        self.makeRenderStats = False
        self.renderStats = {}
Example #21
0
def test_numpy_interop():
    rot = Quat.from_rotation_on_axis(2, np.pi / 2)
    trans = Vec3(1, 1, 1)

    # fmt: off
    np_T = np.array([
        [0, -1, 0, 1],
        [1, 0, 0, 1],
        [0, 0, 1, 1],
        [0, 0, 0, 1],
    ])
    # fmt: on

    T_a_b = Transform(rot, trans)
    T_a_b_from_mat4 = Transform.from_mat4_numpy(np_T)
    T_a_b_from_quatvec3 = Transform.from_quat_vec3_numpy(
        np.concatenate((rot.to_xyzw_numpy(), trans.to_numpy()))
    )

    assert T_a_b == T_a_b_from_mat4
    assert T_a_b == T_a_b_from_quatvec3
    assert T_a_b_from_quatvec3 == T_a_b_from_mat4

    np_mat4_T = T_a_b.to_mat4_numpy()
    np_quatvec3_T = T_a_b.to_quat_vec3_numpy()

    assert np.allclose(
        np_quatvec3_T, np.concatenate((rot.to_xyzw_numpy(), trans.to_numpy()))
    )
    assert np.allclose(np_mat4_T, np_T)
Example #22
0
    def __init__(self):
        super().__init__()

        image_paths = sorted(
            glob('/home/ubuntu/FaceDatasets/jd/Training_data/*/picture/*.jpg'))
        landmarks_paths = sorted(
            glob(
                '/home/ubuntu/FaceDatasets/jd/Training_data/*/landmark/*.txt'))

        for i in range(len(image_paths)):
            assert image_paths[i].split('/')[-1].split(
                '.')[0] == landmarks_paths[i].split('/')[-1].split(
                    '.')[0], 'CHECK ERROR'

        self.image_paths = image_paths
        self.landmarks_paths = landmarks_paths
        assert len(self.image_paths) == len(
            self.landmarks_paths), 'CHECK ERROR'

        self.COMPONETS = self.jdComponent()
        self.transform = Transform(degrees=30,
                                   scale=(0.75, 1.0),
                                   translate=(-0.05, 0.05),
                                   colorjitter=0.3,
                                   out_size=256,
                                   flip=True)
Example #23
0
 def applyTransform(self, transform):
     matrix = Transform().createMatrix(transform)
     (x1, y1) = matrix.applyOnPoint(self.xmin, self.ymin)
     (x2, y2) = matrix.applyOnPoint(self.xmax, self.ymax)
     self.reinit()
     self.addPoint(x1, y1)
     self.addPoint(x2, y2)
Example #24
0
 def transform_OK_callback(self):
     transform_appid = self.v_transform_appid.get()
     transform_apikey = self.v_transform_apikey.get()
     transform_audiopath = self.v_transform_audiopath.get()
     if transform_appid == "":
         self.t_transform_process.configure(state = "normal")            
         self.t_transform_process.insert(END, "请输入APPID!\n")
         self.t_transform_process.see(END)
         self.t_transform_process.configure(state = "disabled")
     elif transform_apikey == "":
         self.t_transform_process.configure(state = "normal")              
         self.t_transform_process.insert(END, "请输入APIkey!\n")
         self.t_transform_process.see(END)
         self.t_transform_process.configure(state = "disabled")
     elif transform_audiopath== "":
         self.t_transform_process.configure(state = "normal") 
         self.t_transform_process.insert(END, "请选择音频文件!\n")
         self.t_transform_process.see(END)
         self.t_transform_process.configure(state = "disabled")
     else:
         #调用转写模块
         T = Transform()
         th_transform = threading.Thread(target = T.start,args=(transform_appid,transform_apikey,transform_audiopath,self.t_transform_process,))
         th_transform.setDaemon(True)
         th_transform.start()
Example #25
0
 def translate(self, x, y):
     transform = self.get('transform', default='')
     matrix = Transform().createMatrix(transform)
     matrix = matrix.add_translate(x, y)
     parser = Factory().create('transform_parser')
     transform = parser.unparse(matrix.createTransform())
     self.set('transform', transform)
Example #26
0
def calculate_order_position(order_pose,
                             agv_id,
                             incrementX=0,
                             incrementY=0,
                             incrementZ=0):
    tray_frame = TRAY_FRAME[agv_id]
    transform_part = Transform(
        [order_pose.position.x, order_pose.position.y, order_pose.position.z],
        [
            order_pose.orientation.x, order_pose.orientation.y,
            order_pose.orientation.z, order_pose.orientation.w
        ])
    transform_agv = global_vars.tf_manager.get_transform('world', tray_frame)

    final_position, final_rotation = transform.transform_to_world(
        transform_part, transform_agv)

    # moving to the middle of the tray
    final_position[0] += TRAY_POSITIONS2[agv_id][0] + incrementX
    final_position[1] += TRAY_POSITIONS2[agv_id][1] + incrementY
    final_position[2] += TRAY_POSITIONS2[agv_id][2] + incrementZ

    final_rotation = transf.transformations.euler_from_quaternion([
        order_pose.orientation.x, order_pose.orientation.y,
        order_pose.orientation.z, order_pose.orientation.w
    ])

    return final_position, final_rotation
Example #27
0
def evaluate():
    checkpoint_path = os.path.join(args.model_root, args.model_name)
    checkpoint = torch.load(checkpoint_path, map_location=device)
    model = SSD300(n_classes=len(label_map), device=device).to(device)
    model.load_state_dict(checkpoint['model'])

    transform = Transform(size=(300, 300), train=False)
    test_dataset = VOCDataset(root=args.data_root,
                              image_set=args.image_set,
                              transform=transform,
                              keep_difficult=True)
    test_loader = DataLoader(dataset=test_dataset,
                             collate_fn=collate_fn,
                             batch_size=args.batch_size,
                             num_workers=args.num_workers,
                             shuffle=False,
                             pin_memory=True)

    detected_bboxes = []
    detected_labels = []
    detected_scores = []
    true_bboxes = []
    true_labels = []
    true_difficulties = []

    model.eval()
    with torch.no_grad():
        bar = tqdm(test_loader, desc='Evaluate the model')
        for i, (images, bboxes, labels, difficulties) in enumerate(bar):
            images = images.to(device)
            bboxes = [b.to(device) for b in bboxes]
            labels = [l.to(device) for l in labels]
            difficulties = [d.to(device) for d in difficulties]

            predicted_bboxes, predicted_scores = model(images)
            _bboxes, _labels, _scores = model.detect_objects(predicted_bboxes,
                                                             predicted_scores,
                                                             min_score=0.01,
                                                             max_overlap=0.45,
                                                             top_k=200)

            detected_bboxes += _bboxes
            detected_labels += _labels
            detected_scores += _scores
            true_bboxes += bboxes
            true_labels += labels
            true_difficulties += difficulties

        all_ap, mean_ap = calculate_mAP(detected_bboxes,
                                        detected_labels,
                                        detected_scores,
                                        true_bboxes,
                                        true_labels,
                                        true_difficulties,
                                        device=device)

    pretty_printer = PrettyPrinter()
    pretty_printer.pprint(all_ap)
    print('Mean Average Precision (mAP): %.4f' % mean_ap)
def pwmControlThread():
    # setup arduino serial comm
    pwm.setPWMFreq(50)
    t = Transform(True, False) #invert one motor and not the other when constructing
    watchdog = time.time()

    # thread main loop
    while True:
	time.sleep(.005)
        # check for data that needs to be bridged to arduino
        dataFlag = True
        if not serialRealTimeQueue.empty():
            data = serialRealTimeQueue.get()
        else:
            dataFlag = False

        # if data was recieved parse and update pwm hat
        if dataFlag:
            data = data[5:-1]
            print data
            data_nums = [int(x) for x in data.split(':') if x.strip()]
            print " ", data_nums[0], " ", data_nums[1]
            leftMtr,rightMtr = t.transform(data_nums[0],data_nums[1])
            print " ", leftMtr , " ", rightMtr
            setServoPulse(LEFT_MOT, leftMtr)
            setServoPulse(RIGHT_MOT, rightMtr)

            Transform.MOTOR_MIN = data_nums[5]*10
            Transform.MOTOR_IDLE = data_nums[6]*10
            Transform.MOTOR_MAX = data_nums[7]*10


            leftIntake = Transform.MOTOR_IDLE
            rightIntake = Transform.MOTOR_IDLE
            if data_nums[2] > 127 + 10: # if left trigger pressed (i think) spin motors in opposite direction
                leftIntake = Transform.map_range(data_nums[2],127,255,Transform.MOTOR_IDLE,Transform.MOTOR_MAX)
                rightIntake = Transform.map_range(data_nums[2],127,255,Transform.MOTOR_IDLE,Transform.MOTOR_MIN)
            elif data_nums[3] > 127 + 10: # if right trigger pressed
                leftIntake = Transform.map_range(data_nums[3],127,255,Transform.MOTOR_IDLE,Transform.MOTOR_MIN)
                rightIntake = Transform.map_range(data_nums[3],127,255,Transform.MOTOR_IDLE,Transform.MOTOR_MAX)
            else :
                leftIntake = Transform.MOTOR_IDLE
                rightIntake = Transform.MOTOR_IDLE
 
            print " " , leftIntake, " ", rightIntake

            setServoPulse(LEFT_MANIP,leftIntake)
            setServoPulse(RIGHT_MANIP,rightIntake)

            watchdog = time.time()

        if watchdog + WATCHDOG_DELAY < time.time():
            setServoPulse(LEFT_MOT, Transform.MOTOR_IDLE)
            setServoPulse(RIGHT_MOT, Transform.MOTOR_IDLE)
            setServoPulse(LEFT_MANIP, Transform.MOTOR_IDLE)
            setServoPulse(RIGHT_MANIP, Transform.MOTOR_IDLE)

            watchdog = time.time()
            print "you need to feed the dogs"
Example #29
0
def pwmControlThread():
    # setup arduino serial comm
    pwm.setPWMFreq(50)
    t = Transform(True, False)
    watchdog = time.time()

    # thread main loop
    while True:
        # check for data that needs to be bridged to arduino
        dataFlag = True
        if not serialRealTimeQueue.empty():
            data = serialRealTimeQueue.get()
        else:
            dataFlag = False

        # if data was recieved send it to arduino
        if dataFlag:
            data = data[5:-1]
            print data
            data_nums = [int(x) for x in data.split(':') if x.strip()]
            #print "have data"
            print " ", data_nums[0], " ", data_nums[1]
            leftMtr, rightMtr = t.transform(data_nums[0], data_nums[1])
            print " ", leftMtr, " ", rightMtr
            setServoPulse(LEFT_MOT, leftMtr)
            setServoPulse(RIGHT_MOT, rightMtr)

            leftIntake = Transform.MOTOR_IDLE
            rightIntake = Transform.MOTOR_IDLE
            if data_nums[2] > 127 + 10:
                leftIntake = Transform.map_range(data_nums[2], 127, 255,
                                                 Transform.MOTOR_IDLE,
                                                 Transform.MOTOR_MAX)
                rightIntake = Transform.map_range(data_nums[2], 127, 255,
                                                  Transform.MOTOR_IDLE,
                                                  Transform.MOTOR_MIN)
            elif data_nums[3] > 127 + 10:
                rightIntake = Transform.map_range(data_nums[3], 127, 255,
                                                  Transform.MOTOR_IDLE,
                                                  Transform.MOTOR_MAX)
                leftIntake = Transform.map_range(data_nums[3], 127, 255,
                                                 Transform.MOTOR_IDLE,
                                                 Transform.MOTOR_MIN)

            print " ", leftIntake, " ", rightIntake

            setServoPulse(LEFT_MANIP, leftIntake)
            setServoPulse(RIGHT_MANIP, rightIntake)

            watchdog = time.time()

        if watchdog + WATCHDOG_DELAY < time.time():
            setServoPulse(LEFT_MOT, Transform.MOTOR_IDLE)
            setServoPulse(RIGHT_MOT, Transform.MOTOR_IDLE)
            setServoPulse(LEFT_MANIP, Transform.MOTOR_IDLE)
            setServoPulse(RIGHT_MANIP, Transform.MOTOR_IDLE)

            watchdog = time.time()
            print "you need to feed the dogs"
Example #30
0
def transform(args, x_queue, datadir, fname_index, joint_index, o_queue):
    trans = Transform(args)
    while True:
        x = x_queue.get()
        if x is None:
            break
        x, t = trans.transform(x.split(','), datadir, fname_index, joint_index)
        o_queue.put((x.transpose((2, 0, 1)), t))