Esempio n. 1
0
    def run(self, throttle):
        if throttle > 0:
            pulse = utils.map_range(throttle, 0, self.MAX_THROTTLE,
                                    self.zero_pulse, self.max_pulse)
        else:
            pulse = utils.map_range(throttle, self.MIN_THROTTLE, 0,
                                    self.min_pulse, self.zero_pulse)

        self.controller.set_pulse(pulse)
Esempio n. 2
0
def optimize(points, model, loss_type=LossType.BEST_MATCH):
    num_steps = 500

    optimizers = [
        torch.optim.SGD(optimizer_param.params, lr=0.1, momentum=0.9)
        for optimizer_param in model.optimizer_config
    ]
    schedulers = [
        (lambda x: torch.optim.lr_scheduler.LambdaLR(
            optimizer, lambda i: map_range(i, 0.0, num_steps - 1, x.start_lr, x
                                           .end_lr)))(optimizer_param)
        for (optimizer,
             optimizer_param) in zip(optimizers, model.optimizer_config)
    ]

    model.train()

    # Uncomment the line below in the event of an anomaly detection
    #with torch.autograd.detect_anomaly():
    for i in range(num_steps):
        model.lambda_ = map_range(i, 0, num_steps - 1, 0.01, 8.0)

        for optimizer in optimizers:
            optimizer.zero_grad()

        loss = model(points, loss_type=loss_type)
        print("Loss: " + str(loss))

        if math.isnan(loss.item()):
            raise NumericalInstabilityException(
                "Loss score was NaN. Consider using torch.autograd.detect_anomaly() to track down the source of the NaN"
            )

        loss.backward()

        # Occasionally the gradient can blow up, so clip it here to make
        # sure we don't jump too far around the parameter space
        torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0)

        for optimizer in optimizers:
            optimizer.step()

        model.normalize()

        for scheduler in schedulers:
            scheduler.step()

    # Don't use the raw loss score since the different geometric models may have different incomparable loss scores
    # (like comparing apples to oranges)
    return model.exact_forward(points, loss_type=loss_type)
Esempio n. 3
0
        def send_control():
            control_input = request.args
            logger.debug('control input: {}'.format(control_input))
            if 'steer' in control_input:
                steer = map_range(int(control_input['steer']), -100.0, 100.0, -1.0, 1.0)
                self.steering = steer
            if 'throttle' in control_input:
                throttle = map_range(int(control_input['throttle']), -170.0, 170.0, -1.0, 1.0)
                self.throttle = throttle
            if 'record' in control_input:
                self.record = str(control_input['record']) == 'true'
            if 'auto' in control_input:
                self.autonomous = str(control_input['auto']) == 'true'

            self.publish_message(self.steering, self.throttle, self.record, self.autonomous)
            return ''
Esempio n. 4
0
    def run(self, angle):
        #map absolute angle to angle that vehicle can implement.
        pulse = utils.map_range(angle,
                                self.LEFT_ANGLE, self.RIGHT_ANGLE,
                                self.left_pulse, self.right_pulse)

        self.controller.set_pulse(pulse)
Esempio n. 5
0
def predict_img(net,
                ldr_img,
                scale_factor=0.5,
                out_threshold=0.5,
                use_dense_crf=True,
                use_gpu=False,
                output_path: '',
                tone_map: 'durand'):

    img_height = ldr_img.size[1]
    img_width = ldr_img.size[0]

    # preprocess
    img = ldr_img.astype('float32')
    img = only_resizeCV(img,224,224)
    ldr_input = map_range(img)

    t_ldr = cv2torch(ldr_input)

    if use_gpu:
        t_ldr = t_ldr.cuda()
        
    with torch.no_grad():
        pred = net(t_ldr)
        pred = map_range(torch2cv(pred).cpu(),0,1)

        # extension = 'exr' if opt.use_exr else 'hdr'
        extension = 'hdr'
        out_name =  create_name(ldr_img,'prediction_{0}'.format(),extension,output_path)

        print(f'Writing {out_name}')
        cv2.imwrite(out_name, pred)
        tmo_img =  tone_map(pred,tone_map,**create_tmo_param_from_args(tone_map))

        out_name = create_name(
                ldr_img,
                'prediction_{0}'.format(tone_map),
                'jpg',
                output_path
            )

        cv2.imwrite(out_name, (tmo_img * 255).astype(int))

    if use_dense_crf:
        full_mask = dense_crf(np.array(ldr_img).astype(np.uint8), full_mask)

    return full_mas k > out_threshold
    def set_motor(self, motor_number, value):
        if self.motor_controller is not None:
            motor = self.motor_controller.devices[motor_number]
            value = self.apply_sensitivity(value)
            pwm_value = int(map_range(value, -1.0, 1.0, FULL_REVERSE, FULL_FORWARD))

            # print("setting motor {0} to {1}".format(motor_number, pwm_value))
            motor.off = pwm_value
Esempio n. 7
0
 def on_message(self, channel, throttle):
     if throttle == 0:
         pca9685.set_throttle(self.channel, 0)
     elif throttle is not None:
         pca9685.set_throttle(
             self.channel,
             map_range(throttle, -1, 1, self.min_throttle,
                       self.max_throttle))
    def update_button(self, button, value):
        if button == UP:
            self.light = min(1.0, self.light + LIGHT_STEP)
        elif button == DOWN:
            self.light = max(0.0, self.light - LIGHT_STEP)
        elif button == RESET:
            self.light = 0.0

        light_value = map_range(self.light, 0.0, 1.0, -1.0, 1.0)
        print("button %s, light = %s, light_value = %s" % (button, self.light, light_value))
        self.set_motor(LIGHT, light_value)
Esempio n. 9
0
    def run(self, angle):
        if self.invert_steering_angle:
            if angle != 0.0:
                angle = 1 / angle

        # map absolute angle to angle that vehicle can implement.
        pulse = utils.map_range(angle, 
                                self.LEFT_ANGLE, self.RIGHT_ANGLE,
                                self.left_pulse, self.right_pulse)

        self.controller.set_pulse(pulse)
Esempio n. 10
0
 def on_message(self, channel, angle):
     """
     Args:
         channel:
         angle: float: -1 to 1
     """
     if angle == 0:
         pca9685.set_angle(self.channel, self.straight_angle)
     elif angle is not None:  #
         pca9685.set_angle(
             self.channel,
             int(
                 map_range(angle, self.MIN_STEERING, self.MAX_STEERING,
                           self.full_left_angle, self.full_right_angle)))
Esempio n. 11
0
    def run(self, speed):
        '''
        Update the speed of the motor where 1 is full forward and
        -1 is full backwards.
        '''
        if speed > 1 or speed < -1:
            raise ValueError(
                "Speed must be between 1(forward) and -1(reverse)")

        self.speed = speed
        self.throttle = int(utils.map_range(abs(speed), -1, 1, -255, 255))

        if speed > 0:
            self.motor.run(self.FORWARD)
        else:
            self.motor.run(self.BACKWARD)

        self.motor.setSpeed(self.throttle)
Esempio n. 12
0
            # Cool, we detected a single hand. Update the coordinates and open status
            landmarks = multi_hand_landmarks[0].landmark

            # Get the hand open status
            if get_average_knuckle_distance(landmarks) >= MIN_HAND_OPEN_DISTANCE:
                hand_open = True
            else:
                hand_open = False
            palm_coordinates_unmapped = get_palm_coordinate(landmarks)
            cv2.putText(image,
                        "Hand open" if hand_open else "Hand closed", (20, 70), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 1, cv2.LINE_AA)

            # Get the coordinates of the palm
            draw_palm_coordinates = (int(palm_coordinates_unmapped[0] * image.shape[1]), int(palm_coordinates_unmapped[1] * image.shape[0]))

            mapped_palm_x = (int)(map_range(
                palm_coordinates_unmapped[0], margined_start_point[0] / image.shape[1], margined_end_point[0] / image.shape[1], 0, MAPPED_WIDTH))
            mapped_palm_y = (int)(map_range(
                palm_coordinates_unmapped[1], margined_start_point[1] / image.shape[0], margined_end_point[1] / image.shape[0], 0, MAPPED_HEIGHT))
            palm_coordinates = (mapped_palm_x, mapped_palm_y)

            # Draw a purple circle at the palm
            cv2.circle(image, draw_palm_coordinates,
                       15, (255, 0, 255), cv2.FILLED)

            hands_detected = 1
    else:
        hands_detected = 0
    cv2.imshow('Hand detection', image)
    send_payload = True
    if cv2.waitKey(5) & 0xFF == 27:
        break
Esempio n. 13
0
period_time = time.monotonic()

wave_inc = 8

# let's declare our "dt" to always be 0.01 secs, THEN
# what wave part do I pick for given period
# 
dt = 0.001
wave_dt = period / len(wave)
#print("steps:",len(wave), "period:",period, "dt:",dt,"period_dt:",wave_dt, "wave_inc:",wave_inc)

base_dt = 0.001
dtcnt=0
while True:

    wave_dt = max(0, utils.map_range(knob_a.value, (65500,150), (0.001, 0.25)))
    volt_amplitude = utils.map_range(knob_b.value, (150,65500), (0.1,5) )
    # period = max(0, utils.map_range(knob_a.value, (150,65500), (0.1, 20)))
    # wave_dt = wave_inc * period / len(wave)

    #if wave_dt*2 < dt:
    #    wave_inc = 2*wave_inc
    #    wave_dt = 2*wave_dt

    wave_inc = max(1,utils.map_range(wave_dt, (0,0.1), (16,1))) # this is a float
    dt = wave_dt / wave_inc
    wave_inc = int(wave_inc)
    
    wave_index = (wave_index + wave_inc) % len(wave)
        
    print("steps:",len(wave), "wave_inc:",wave_inc,"period:",period, "wave_dt:",wave_dt, "dt:",dt)