Ejemplo n.º 1
0
def prepare_env():
    if path.exists("pose/webcam_calibration_params.npz"):
        return read_cam_paramns()
    else:
        photo.take_photos()
        calibrate.calibrate()
        return read_cam_paramns()
Ejemplo n.º 2
0
def Q1(inputPath):
    pts_2d = read_data(inputPath, "pts2d-norm-pic_a.txt")
    pts_3d = read_data(inputPath, "pts3d-norm.txt")
    M_least_squared = calibrate(pts_2d, pts_3d, "least_squared")
    M_SVD = calibrate(pts_2d, pts_3d, "SVD")
    C = projectionCenter(M_SVD)
    return M_least_squared, M_SVD, C
Ejemplo n.º 3
0
def main():
    SCREEN_HEIGHT = 700
    SCREEN_WIDTH  = 1024
    clock  = pygame.time.Clock()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    screen_rect = screen.get_rect()
    x = screen_rect.centerx
    y = screen_rect.centery

    pygame.init()
    pygame.display.set_caption('Think-Blast')

    title_unscale = pygame.image.load('../assets/title.png')
    title         = pygame.transform.scale(title_unscale, (500, 200))
    title_rect    = title.get_rect(center = (SCREEN_WIDTH/2, 150))

    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_q]:
            done = True
        if pressed[pygame.K_p]:
            game.gameplay(screen, clock)
        if pressed[pygame.K_c]:
            calibrate.calibrate(screen, clock)

        play, play_rect = render.text("Press p to Play", 30, (x,y))
        play_rect.top += 0
        cal, cal_rect   = render.text("Press c to Calibrate", 30, (x,y))
        cal_rect.left = play_rect.left
        cal_rect.top += 40
        quit, quit_rect = render.text("Press q to Quit", 30, (x,y))
        quit_rect.left = play_rect.left
        quit_rect.top += 80

        screen.fill((0, 0, 0))
        screen.blit(title, title_rect)
        screen.blit(play, play_rect)
        screen.blit(cal, cal_rect)
        screen.blit(quit, quit_rect)
       
        pygame.display.flip() 
        clock.tick(60)
def calibration(cam, threshold):
    print(str1 + "Start calibration" + str2)
    while True:
        retval, img = cam.read()
        if retval:
            b, x, y = calibrate.calibrate(img, threshold)
            print(str1 + "Calibration done" + str2)
            return b, x, y
Ejemplo n.º 5
0
def runCalibration():
    # Run through calibration process
    write_pot_value(BASE_POT_VALUE)
    m, b = calibrate(True)
    print("Completed calibration stage and received the following parameters:")
    print("\tM = " + str(m))
    print("\tB = " + str(b))
    return m, b
Ejemplo n.º 6
0
def runCalibration():
    # Run through calibration process
    input("Press \'Enter\' to begin calibration")
    m, b = calibrate(plot=True)
    print("Completed calibration stage and received the following parameters:")
    print("\tM = " + str(m))
    print("\tB = " + str(b))
    return m, b
Ejemplo n.º 7
0
 def test_xaj_calibrate(self):
     starttime = datetime.datetime.now()
     run_counts = 100
     optimal_params = calibrate(run_counts)
     print("本次优化的计算结果,即优选参数集为:")
     print(optimal_params)
     endtime = datetime.datetime.now()
     print("率定完毕,耗费时间为 " + str((endtime - starttime).seconds) + " s")
Ejemplo n.º 8
0
 def __init__(self, cam_matrix):
     if not os.path.exists(cam_matrix):
         mtx, dist = calibrate()
     else:
         with open(cam_matrix, 'rb') as f:
             calib_info = pickle.load(f)
             self.mtx = calib_info['mtx']
             self.dist = calib_info['dist']
Ejemplo n.º 9
0
 def test_xaj_calibrate(self):
     starttime = datetime.datetime.now()
     run_counts = 100
     optimal_params = calibrate(run_counts)
     print("本次优化的计算结果,即优选参数集为:")
     print(optimal_params)
     with open('optimal_params', 'wb') as f:
         pickle.dump(optimal_params, f)
     endtime = datetime.datetime.now()
     print("率定完毕,耗费时间为 " + str((endtime - starttime).seconds) + " s")
Ejemplo n.º 10
0
def calibrateImageCallBack():
    logScreen("Calibrando imagen...")
    data.matrix = cal.calibrate(
        data.matrix, frame_name="A", debug=False, cache=False
    )  # La imagen se puede calibrar con cualquiera de los dos Telemetry Frame
    data.frameA = utils.get_frame(data.matrix, 'A')
    data.frameB = utils.get_frame(data.matrix, 'B')
    img = Image.fromarray(data.matrix)
    data.image = img
    logScreen("Imagen calibrada correctamente.")
    previewImageCallBack(1)
Ejemplo n.º 11
0
def main():
    model_path = './resnet50_v1.onnx'
    calibration_dataset_path = './calibration_data_set_test'
    dr = ResNet50DataReader(calibration_dataset_path)
    #call calibrate to generate quantization dictionary containing the zero point and scale values
    quantization_params_dict = calibrate(model_path, dr)
    calibrated_quantized_model = quantize(
        onnx.load(model_path),
        quantization_mode=QuantizationMode.QLinearOps,
        force_fusions=False,
        quantization_params=quantization_params_dict)
    output_model_path = './calibrated_quantized_model.onnx'
    onnx.save(calibrated_quantized_model, output_model_path)
    print('Calibrated and quantized model saved.')
Ejemplo n.º 12
0
def remove_distortion(images):
    out = calibrate(images)
    matrix = out['camera_matrix']
    dist = out['distortion_coefficient']

    undistorted_images = []
    for (image, color_image) in images:
        size = image.shape[::-1]
        new_matrix, roi = cv.getOptimalNewCameraMatrix(matrix, dist, size,
                                                       1, size)

        img = cv.undistort(color_image, matrix, dist, None, new_matrix)
        undistorted_images.append(img)

    return undistorted_images
Ejemplo n.º 13
0
 def on_calibrate(self, widget):
     """ Calibrates video gaze if its hasn't been done already.
         If calibration is not successful, user can try again or use default calibration instead.
     """
     if self.is_Calibrated:
         # Create information dialog box
         dialog = Gtk.MessageDialog(
             parent=None,
             flags=0,
             message_type=Gtk.MessageType.INFO,
             buttons=Gtk.ButtonsType.OK,
             text="Glasses already calibrated. Ready to record.")
         # Launch dialog box
         dialog.run()
         dialog.destroy()
     else:
         print("Calibrating video gaze ...")
         self.participant_id, status = calibrate.calibrate(
             self.glasses_ip, PORT)
         if status == 'failed':
             dialog = Gtk.MessageDialog(
                 parent=None,
                 flags=0,
                 message_type=Gtk.MessageType.WARNING,
                 buttons=Gtk.ButtonsType.OK_CANCEL,
                 text="Calibration Failed")
             dialog.format_secondary_text(
                 "Using default calibration instead. Press 'ok' to continue or 'cancel' to try again."
             )
             response = dialog.run()
             if response == Gtk.ResponseType.OK:
                 self.is_Calibrated = True
             elif response == Gtk.ResponseType.CANCEL:
                 self.participant_id = ""
                 self.is_Calibrated = False
             dialog.destroy()
         else:
             self.is_Calibrated = True
             dialog = Gtk.MessageDialog(parent=None,
                                        flags=0,
                                        message_type=Gtk.MessageType.INFO,
                                        buttons=Gtk.ButtonsType.OK,
                                        text="Calibration Successful")
             dialog.run()
             dialog.destory()
Ejemplo n.º 14
0
    def __init__(self):
        cv2.namedWindow("left", cv2.WINDOW_AUTOSIZE)
        cv2.namedWindow("right", cv2.WINDOW_AUTOSIZE)
        #create our image publishers
        self.image_left_pub = rospy.Publisher("detect_left", Image)
        self.image_right_pub = rospy.Publisher("detect_right", Image)

        #a place to put the last images published by a node
        self.left_prev = None
        self.right_prev = None

        self.bridge = CvBridge()
        #create our subscriber
        self.left_image_sub = rospy.Subscriber("/my_stereo/left/image_raw", Image, self.callback_left)
        self.right_image_sub = rospy.Subscriber("/my_stereo/right/image_raw", Image, self.callback_right)

        self.cal = calibrate.calibrate(["cal/left.txt", "cal/right.txt"])
        if not self.cal.load():
            self.cal.calibrate()
Ejemplo n.º 15
0
def getThermalImage(matrix, satellite_NOAA="19", frame_name="A"):
    temp_min = 1000
    temp_max = 0
    if satellite_NOAA == "19":
        satellite = sat.NOAA_19()
    elif satellite_NOAA == "18":
        satellite = sat.NOAA_18()
    elif satellite_NOAA == "15":
        satellite = sat.NOAA_15()
    matrix = cal.calibrate(utils.mean_filter(matrix, 2), frame_name)
    #matrix = utils.mean_filter(matrix,2)
    frame = utils.get_frame(matrix, frame_name)
    mayor_frame = tlmtry.get_mayor_frame(matrix, frame_name)
    Cs = tlmtry.compute_CS(matrix, frame_name)
    print("Cs:", Cs)
    print("mayor frame:", mayor_frame)
    thermal_matrix = get_temp_3A(frame, mayor_frame, satellite, Cs)
    imgt = Image.fromarray(thermal_matrix)
    imgt = np.array(imgt)
    numrows, numcols = imgt.shape
    return thermal_matrix
Ejemplo n.º 16
0
    for j in xrange(sample_num):
        cur_ctr = 0.0
        for k in xrange(len(ctrs)):
            cur_ctr += weights[k] * math.log(ctrs[k][j]/(1-ctrs[k][j]))
        cur_ctr = 1/(1+math.exp(-cur_ctr))
        print >> f, str(cur_ctr)
    f.close()

def sub(result,testfile,output):
    f = open(testfile)
    r = open(result)
    o = open(output,"w")
    l1 = f.readline()
    print >> o, "id,click"
    while True:
        l1 = f.readline()
        l2 = r.readline().strip()
        if not l1:
            break
        print >> o, l1.split(',')[0]+","+l2
    f.close()
    r.close()
    o.close()

files = ["../ftrl_1","../ftrl_2","../fm_test_2.out","../fm_test_2_split"]
weights = [1,1,1,1]
ensemble(weights,files,"../ensemble")
sub("../ensemble","../test","../ensemble_sub")
calibrate("../ensemble_sub","../ensemble_cal")

Ejemplo n.º 17
0
import calibrate
import lanedetect
import cv2

ret, mtx, dist, rvecs, tvecs = calibrate.calibrate("data/camera_cal/", 6, 9)

cap = cv2.VideoCapture('data/video/project_video.mp4')

if (cap.isOpened() == False):
    print("Error opening video stream or file")

while (cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:

        ds = calibrate.undistort(frame, mtx, dist)
        ds = lanedetect.filterYellowWhiteLane(ds)
        resized = cv2.resize(ds, (960, 540))
        cv2.imshow('output', resized)

        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

    else:
        break

cap.release()

cv2.destroyAllWindows()
Ejemplo n.º 18
0
               'betaH': BETA_H, 'betaW': BETA_W, 'betaC': BETA_C, 'betaS': BETA_S, 'betaTravel': BETA_TRAVEL,
               'hdAreaFactor':HD_AREA_FACTOR, 'hdAreaExponent':HD_AREA_EXPONENT, 'intervention': INTERVENTION, 
               'outputDirectoryBase': output_directory_base, 'inputDirectory': input_directory,
               'calibrationDelay': CALIBRATION_DELAY, 'daysBeforeLockdown': DAYS_BEFORE_LOCKDOWN }
    
    print ('Parameters: ', params)    
    
    start_time = time.time()
    processed_list = Parallel(n_jobs=num_cores)(delayed(run_sim)(simNum, params) for simNum in range(num_sims))     
    print ('Execution time: ',time.time()-start_time, ' seconds') 

    ##############################################################
    calculate_means_fatalities_CPP(output_directory_base, num_sims,"./data/")
    calculate_means_lambda_CPP(output_directory_base, num_sims,"./data/") 
    
    [flag, BETA_SCALE_FACTOR, step_beta_h, step_beta_w, step_beta_c, delay, slope_diff, lambda_h_diff, lambda_w_diff, lambda_c_diff] = calibrate(resolution,count)
    with open(LOGFILE, "a+") as logfile:
        logfile.write(f"beta_h: {BETA_H}\n")
        logfile.write(f"beta_w: {BETA_W}\n")
        logfile.write(f"beta_c: {BETA_C}\n")
        logfile.write(f"beta_s: {BETA_S}\n")
        logfile.write(f"slope_diff: {slope_diff}\n")
        logfile.write(f"lambda_h_diff: {lambda_h_diff}\n")
        logfile.write(f"lambda_w_diff: {lambda_w_diff}\n")
        logfile.write(f"lambda_c_diff: {lambda_c_diff}\n\n\n")        
    count+=1    
    if flag == True:
        continue_run = False
    else:
        BETA_H = max(BETA_H + step_beta_h,0)*BETA_SCALE_FACTOR
        BETA_W = max(BETA_W + step_beta_w,0)*BETA_SCALE_FACTOR
Ejemplo n.º 19
0
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
                                               NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from calibrate import calibrate
from controller import controller
import numpy as np
from matplotlib.figure import Figure

from calibrate import calibrate

files = []  #to supply csvs
for argument in argv[1:]:
    files.append(argument)

window = tk.Tk()
newfig = calibrate(*files)

canvas = FigureCanvasTkAgg(newfig.fig, master=window)
canvas.draw()

toolbar = NavigationToolbar2Tk(canvas, window)
toolbar.update()


def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)


canvas.mpl_connect("key_press_event", on_key_press)
Ejemplo n.º 20
0

def find_largest_contour(contours):
    maxarea = 0
    pos = -1
    for i in range(len(contours)):
        area = cv2.contourArea(contours[i])
        if area > maxarea:
            maxarea = area
            pos = i
    return pos


cap = cv2.VideoCapture(0)

colors_thresh, colors_Y_Channel = cal.calibrate(cap)

while 1:
    _, im = cap.read()

    imgYUV = cv2.cvtColor(im, cv2.COLOR_BGR2YUV)

    equY = cv2.equalizeHist(imgYUV[:, :, 0])

    hist, bins = np.histogram(equY.ravel(), 256, [0, 256])

    equY = cal.transform(equY, colors_Y_Channel["Blue"])

    equalisedYUV = cv2.merge([equY, imgYUV[:, :, 1], imgYUV[:, :, 2]])

    im = cv2.cvtColor(equalisedYUV, cv2.COLOR_YUV2BGR)
Ejemplo n.º 21
0
    def receive(self, text, get_next_text):
        if self.state == States.LISTENING:
            if Commands.INIATE in text:
                play_audio(AudioKeys.COMMAND_PROMPT)
                self.state = States.TAKING_COMMAND
            else:
                play_audio(AudioKeys.MISUNDERSTOOD)
                self.state = States.LISTENING
        elif self.state == States.TAKING_COMMAND:
            if Commands.RESET_BEGIN in text:
                play_audio(AudioKeys.CONFIRM_RESET_BEGIN)
                self.state = States.RESETING
                threading.Thread(target=begin_reset,
                                 args=(self.gopro, )).start()
            elif Commands.TAKE_CHECKPOINT in text:
                play_audio(AudioKeys.CONFIRM_CHECKPOINT)
                self.state = States.LISTENING
                save_checkpoint(self.gopro)
            elif Commands.NEVERMIND in text:
                play_audio(AudioKeys.OK)
                self.state = States.LISTENING
            elif Commands.SHOW_SHOT in text:
                play_audio(AudioKeys.OK)
                self.state = States.LISTENING
                send_command(UiCommands.SHOW_SHOT_AIM)
            elif Commands.SHOW_BOARD in text:
                play_audio(AudioKeys.OK)
                self.state = States.LISTENING
                send_command(UiCommands.SHOW_POOL_TABLE)
            elif Commands.SHOW_RESETTER in text:
                play_audio(AudioKeys.OK)
                self.state = States.LISTENING
                send_command(UiCommands.SHOW_RESET_FRAME)
            elif Commands.CALIBRATE in text:
                self.state = States.CALIBRATING
                play_audio(AudioKeys.CONFIRM_CALIBRATING_BEGIN)
                calibrate(self.gopro)
                play_audio(AudioKeys.CONFIRM_CALIBRATION_END)
                self.state = States.LISTENING
            elif Commands.PRACTICE in text:
                play_audio(AudioKeys.CONFIRM_PRACTICE)

                play_audio(AudioKeys.PROMPT_PRACTICE_TYPE)
                practice_type = get_next_text(
                    re.compile('(random|spot|learning)'))

                include_walls = None
                num_practice_balls = None
                practice_type_num = -1

                if practice_type == 'random':
                    practice_type_num = 0
                    self.num_practice_balls = int(
                        get_next_text(re.compile('\\d')))
                elif practice_type == 'spot':
                    practice_type_num = 1
                    include_walls = bool(
                        get_next_text(re.compile('(true|false)')))
                    self.num_practice_balls = int(
                        get_next_text(re.compile('\\d')))
                elif practice_type == 'learning':
                    practice_type_num = 2
                else:
                    raise Exception('This should not be possible.')

                self.state = States.PRACTICE
            elif Commands.QUIT in text:
                play_audio(AudioKeys.CONFIRM_QUIT)
                self.state = States.LISTENING
                return False
            else:
                play_audio(AudioKeys.MISUNDERSTOOD)
                self.state = States.LISTENING
        elif self.state == States.RESETING:
            if Commands.RESET_END in text:
                play_audio(AudioKeys.CONFIRM_RESET_END)
                self.state = States.LISTENING
                stop_resetting()
            else:
                play_audio(AudioKeys.MISUNDERSTOOD)
                # self.state = States.LISTENING
        elif self.state == States.PRACTICING:
            if Commands.SELECT_SHOT in text:
                play_audio(AudioKeys.CONFIRM_SELECT_SHOT)
                ballNumber = int(get_next_text(re.compile('\\d')))
                pocketNumber = int(get_next_text(re.compile('\\d')))
                send_shot_selection(ballNumber, pocketNumber)
            elif Commands.SET_RESULT in text:
                play_audio(AudioKeys.CONFIRM_SET_RESULT)
                result = get_next_text("(" + "|".join([
                    cmdText
                    for cmd, cmdText, numBalls in ShotResult.POSSIBLE_RESULTS
                    if numBalls == self.num_practice_balls
                ]) + ")")
                shotResultNums = [
                    cmd
                    for cmd, cmdText, numBalls in ShotResult.POSSIBLE_RESULTS
                    if numBalls == self.num_practice_balls
                    and cmdText == result.group()
                ]
                if len(shotResultNums) != 1:
                    raise Exception("This should not happen")
                send_shot_result(shotResultNums[0])
            elif Commands.SET_TRY_AGAIN_OFF in text:
                play_audio(AudioKeys.CONFIRM_TRY_AGAIN_OFF)
                send_command(UiCommands.TURN_OFF_TRY_AGAIN)
            elif Commands.SET_TRY_AGAIN_ON in text:
                play_audio(AudioKeys.CONFIRM_TRY_AGAIN_ON)
                send_command(UiCommands.TURN_ON_TRY_AGAIN)
            elif Commands.QUIT_PRACTICE in text:
                play_audio(AudioKeys.CONFIRM_END_PRACTICE)
                send_command(UiCommands.END_PRACTICE)
                self.state = States.LISTENING
            else:
                play_audio(AudioKeys.MISUNDERSTOOD)
        else:
            raise Exception('Illegal state.')
        return True
Ejemplo n.º 22
0
        'betaPT': BETA_PT,
        'initFrac': INIT_FRAC,
        'initFracScaleFactor': INIT_FRAC_SCALE_FACTOR,
        'compliance': COMPLIANCE,
        'interventions': INTERVENTION
    }

    print('Parameter:', params)

    processed_list = Parallel(n_jobs=num_cores)(
        delayed(run_sim)(driverLocation, options, simNum, params)
        for simNum in range(NUM_SIM))

    calculate_means(download_dir, result_dir)

    [flag, BETA_SCALE_FACTOR, step_beta_h, step_beta_w, step_beta_c,
     delay] = calibrate(resolution, count)
    count += 1
    if flag == True:
        continue_run = False
    else:
        print('BETA_HOUSE ', BETA_HOUSE, 'BETA_WORK', BETA_WORK,
              'BETA_SCHOOL:', BETA_SCHOOL, 'BETA_COMMUNITY:', BETA_COMMUNITY)

        BETA_HOUSE = max(BETA_HOUSE + step_beta_h, 0) * BETA_SCALE_FACTOR
        BETA_WORK = max(BETA_WORK + step_beta_w, 0) * BETA_SCALE_FACTOR
        BETA_SCHOOL = max(BETA_SCHOOL + step_beta_w, 0) * BETA_SCALE_FACTOR
        BETA_COMMUNITY = max(BETA_COMMUNITY + step_beta_c,
                             0) * BETA_SCALE_FACTOR
        #INIT_FRAC_SCALE_FACTOR = INIT_FRAC_SCALE_FACTOR*init_frac_mult_factor
Ejemplo n.º 23
0
path = '/Volumes/Yangchao/Sentient/'
product = ProductIO.readProduct(path+'S1B_IW_GRDH_1SDV_20170522T161401_20170522T161430_005713_00A024_4EF8.zip')


# In[142]:


ProductIO.writeProduct(product, 'S1A_IW_GRDH_1SDV_20170719T232015_20170719T232040_017547_01D590_DF13.nc', 'NetCDF4-CF')


# In[8]:


produc1 = calibrate.thermal_app(product)
product2 = calibrate.calibrate(produc1)
product3 = calibrate.specklefilter(product2, filter='Median')
#ProductIO.writeProduct(product3, 'S1B_IW_GRDH_1SDV_20170522T161401_20170522T161430_005713_00A024_4EF8.nc', 'NetCDF4-CF')


# In[4]:


product2 = calibrate.calibrate(produc1)


# In[5]:


product3 = calibrate.specklefilter(product2, filter='Median')
Ejemplo n.º 24
0
 def execute(self, action):
     data_filename = datetime.datetime.fromtimestamp(
         time.time()).strftime('%H_%M_%Son%m-%d-%Y.tsv')
     data_filepath = os.path.join(
         self.data_path, str(self.subject))
     if action == 'q':
         self.testWin.close()
         self.experWin.close()
         if not self.testing:
             self.tobii_cont.destroy()
         return False
     elif action == '3' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'lighttest')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'lighttest' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as light_file:
             lightdarktest.lightdarktest(self, 1, light_file)
         return True
     elif action == '2' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'darktest')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'darktest' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as dark_file:
             lightdarktest.lightdarktest(self, 0, dark_file)
         return True
     elif action == '1' and not self.testing:
         calib_filename = datetime.datetime.fromtimestamp(
             time.time()).strftime('%H_%M_%Son%m-%d-%Y-Calibration.p')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         with open(os.path.join(data_filepath, calib_filename), 'w') as calib_file:
             calibrate.calibrate(self, calib_file)
         return True
     elif action == '6' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'oddball')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'oddball' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as odd_file:
             oddball.oddball(self, odd_file)
         return True
     elif action == '5' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'revlearn')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'revlearn' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as revlearn_file:
             revlearn.revlearn(self, revlearn_file)
         return True
     elif action == '4' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'PST')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'PST' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as pst_file:
             pst.pst(self, pst_file)
         return True
     elif action == '7' and self.calib_complete:
         data_filepath = os.path.join(
             data_filepath, 'ImageTest')
         if not os.path.isdir(data_filepath):
             os.makedirs(data_filepath)
         data_filename = 'ImageTest' + data_filename
         with open(os.path.join(data_filepath, data_filename), 'w') as imagetest_file:
             imagetest.imagetest(self, imagetest_file)
         return True
     elif action == '0' and not self.testing:
         draweyes.show_eyes(self)
         return True
     elif action == 's':
         # open settings box
         setting_window = gui.DlgFromDict(self.settings)
         if setting_window.OK:
             with open(self.settings_file, 'w+') as settings:
                 json.dump(self.settings, settings)
         return True
     elif action == 'r':
         # reset to default settings
         with open("default_settings.json") as settings:
             self.settings = json.load(settings)
         with open(self.settings_file, 'w+') as settings:
             json.dump(self.settings, settings)
         return True
     else:
         print "Please enter a valid action"
         return True
Ejemplo n.º 25
0
        camera_matrix, dist_coeffs, (w, h), 1, (w, h))

    dst = cv2.undistort(distort_im, camera_matrix, dist_coeffs, None,
                        new_camera_matrix)

    # crop and save the image
    # without cropping the edge would be black
    x, y, w, h = roi
    dst = dst[y:y + h, x:x + w]

    return dst


if __name__ == '__main__':
    # calibrate first
    _, camera_matrix, dist_coeffs, _, _ = calibrate.calibrate()

    # used the image saved in calibrate.calibrate()
    # undistorted images would be saved in output_path.
    input_path = './output/'
    output_path = './output/'
    for file in os.listdir(input_path):
        distort_im = cv2.imread(input_path + '/' + file)
        distort_im = cv2.cvtColor(distort_im, cv2.COLOR_RGB2GRAY)

        undistort_im = undistort(distort_im, camera_matrix, dist_coeffs)

        outfile = output_path + file[:6] + '_undistorted.jpg'
        print('Undistorted image written to: {}'.format(outfile))
        cv2.imwrite(outfile, undistort_im)
Ejemplo n.º 26
0
from PIL import Image


def indice_nubosidad(frame, x1, y1, x2, y2):
    '''
    Completar código aquí
    '''

    utils.plot_image(matrix[y1:y2, x1:x2], 'Imagen APT ')
    index = 0

    return index


'''
Decodifico y calibro la señal
'''
matrix = apt.decode('wav/am_demod/2019.03.04.19.30.49.wav', cache=True)
matrix = cal.calibrate(matrix, frame_name="A", debug=False, cache=True)
'''
Visualizamos la imagen APT para identificar el canal infrarrojo
'''

utils.plot_image(matrix, 'Imagen APT ')
matrix_channel_A = utils.get_frame(matrix, "A")
matrix_channel_B = utils.get_frame(matrix, "B")
''''
Invocamos la función que calcula el índice de nubosidad
'''
indice = indice_nubosidad(matrix_channel_A, x1=140, y1=612, x2=750, y2=790)
Ejemplo n.º 27
0
def main():
    # calibrate the camera using the given chessboard images
    ret, mtx, dist, rvecs, tvecs = calibrate(
        path='../camera_cal/calibration*.jpg', xy=(9, 6), draw_corners=False)

    # inst. Lane object
    lane = Lane()

    # read video
    predicted_frames = []
    input_video = 'project_video.mp4'
    cap = cv2.VideoCapture(os.path.join('../input_videos/', input_video))
    while cap.isOpened():
        ret, frame = cap.read()

        if not ret:
            print('Cant receive frame. Exiting..')
            break

        # undistort an image
        rgb_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # BGR => RGB
        undist = undistort(rgb_img, mtx, dist)

        # convert to gray
        gray = cv2.cvtColor(undist, cv2.COLOR_RGB2GRAY)  # RGB => GRAY

        # apply gradient and color thresholding
        gradx = th.abs_sobel_thresh(gray)
        direction = th.dir_thresh(gray)
        gradient_binary = np.zeros_like(direction)
        gradient_binary[(gradx == 1) & (direction == 1)] = 1

        color_binary = th.saturation_thresh(frame)

        # combine gradient and color thresholding
        thresholded_img = th.threshold(gradient_binary, color_binary)

        # perspective transform: easier to measure curvature of lane from bird's eye view
        # also makes it easier to match car's location with a road map
        src, dst, M, M_inv = pt.get_transform_matrix()

        # transform image
        size = (thresholded_img.shape[1], thresholded_img.shape[0])
        transformed_img = cv2.warpPerspective(thresholded_img, M, size)

        # draw lines on transformed
        gray_transformed_img = np.uint8(transformed_img * 255)
        bgr_transformed_img = cv2.cvtColor(gray_transformed_img,
                                           cv2.COLOR_GRAY2BGR)
        #pt.draw_plot_save(bgr_transformed_img, dst, 'Test Transformation', '../output_images/test_transform.png')

        # fit lines
        left_fit, right_fit, y, offset_meters = lane.fit_polynomials(
            transformed_img)

        # create blank for drawing lane lines
        zeros = np.zeros_like(transformed_img).astype(np.uint8)
        draw_img = np.dstack((zeros, zeros, zeros))

        # format points for fill poly
        pts_left = np.array([np.transpose(np.vstack([left_fit,
                                                     y]))])  # [left_fit ... y]
        pts_right = np.array(
            [np.flipud(np.transpose(np.vstack([right_fit, y])))])
        pts = np.hstack((pts_left, pts_right))  # [pts_left, pts_right]
        cv2.fillPoly(draw_img, np.int_([pts]), (0, 255, 0))

        # unwarp transformed image
        unwarped = cv2.warpPerspective(draw_img, M_inv,
                                       (gray.shape[1], gray.shape[0]))

        # combine lane drawing w/ original image
        final_image = cv2.addWeighted(undist, 1, unwarped, 0.25, 0)

        # add measurement data to frame
        offset_side = 'left' if offset_meters < 0 else 'right'
        final_image = cv2.putText(
            final_image,
            f'Offset: {abs(offset_meters):0.2f}m {offset_side} of center',
            (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2,
            cv2.LINE_AA)

        # show predict
        cv2.imshow('frame', cv2.cvtColor(final_image, cv2.COLOR_RGB2BGR))

        # store predicted frames
        predicted_frames.append(final_image)

        if cv2.waitKey(1) == ord('q'):
            break

    # release cap object
    cap.release()
    cv2.destroyAllWindows()
Ejemplo n.º 28
0
def process_cfg(cfg, dbname=None, dbhost=None, replace=False):
    print(
        "Processing channel %d / shutter %d / pos %d %d / filter %s / %s - %s: %d frames"
        % (cfg['channel'], cfg['shutter'], cfg['pos0'], cfg['pos1'],
           cfg['filter'], cfg['night1'], cfg['night2'], cfg['count']))

    favor2 = Favor2(dbname=dbname, dbhost=dbhost)

    res = favor2.query(
        'select time,night,filename from images where channel=%s and shutter=%s and pos0=%s and pos1=%s and filter=%s and (type=\'survey\' or type=\'widefield\') and night>=%s and night<=%s order by time',
        (cfg['channel'], cfg['shutter'], cfg['pos0'], cfg['pos1'],
         cfg['filter'], cfg['night1'], cfg['night2']))

    night0 = res[0]['night']

    header0 = fits.getheader(res[0]['filename'], -1)
    header0['type'] = 'masterflat'
    header0['NFRAMES'] = cfg['count']
    header0['NIGHT1'] = cfg['night1']
    header0['NIGHT2'] = cfg['night2']

    darkname = favor2.find_image(res[0]['time'],
                                 type='masterdark',
                                 shutter=cfg['shutter'],
                                 channel=cfg['channel'])
    dark = fits.getdata(darkname, -1)

    basename = 'calibrations/masterflats/superflat_channel_%d_shutter_%d_pos_%d_%d_%s_%s.fits' % (
        cfg['channel'], cfg['shutter'], cfg['pos0'], cfg['pos1'],
        cfg['filter'], night0)
    if posixpath.exists(basename) and not replace:
        print('Skipping', basename)
        return

    random.shuffle(res)

    images = []
    coadd, counts = None, 0

    for i, r in enumerate(res):
        filename = r['filename']

        image, header = fits.getdata(filename,
                                     -1), fits.getheader(filename, -1)
        image, header = calibrate(image, header, dark=dark)

        # Mask stars in the image
        bg = sep.Background(image)
        mask = image > bg.back() + 2.0 * bg.rms()
        image[mask] = np.nan
        image /= np.nanmedian(image)

        images.append(image)

        if len(images) == 5:
            flat = np.nanmedian(images, axis=0)
            flat /= np.nanmedian(flat)
            idx = np.isfinite(flat)
            images = []

            if coadd is None:
                coadd = np.zeros_like(image)
                counts = np.zeros_like(image, dtype=np.int)

            coadd[idx] += flat[idx]
            counts[idx] += 1

            print(i, '/', len(res), basename)

    # Make masterflat and interpolate the gaps
    idx = counts > 5
    masterflat = np.ones_like(coadd) * np.nan
    masterflat[idx] = coadd[idx] / counts[idx]

    idx |= masterflat < 0.1

    bg = sep.Background(masterflat, mask=~idx)
    masterflat[~idx] = bg.back()[~idx]

    fits.writeto(basename, masterflat, header0, overwrite=True)

    print(basename)
Ejemplo n.º 29
0
        cur_ctr = 0.0
        for k in xrange(len(ctrs)):
            cur_ctr += weights[k] * math.log(ctrs[k][j] / (1 - ctrs[k][j]))
        cur_ctr = 1 / (1 + math.exp(-cur_ctr))
        print >> f, str(cur_ctr)
    f.close()


def sub(result, testfile, output):
    f = open(testfile)
    r = open(result)
    o = open(output, "w")
    l1 = f.readline()
    print >> o, "id,click"
    while True:
        l1 = f.readline()
        l2 = r.readline().strip()
        if not l1:
            break
        print >> o, l1.split(',')[0] + "," + l2
    f.close()
    r.close()
    o.close()


files = ["../ftrl_1", "../ftrl_2", "../fm_test_2.out", "../fm_test_2_split"]
weights = [1, 1, 1, 1]
ensemble(weights, files, "../ensemble")
sub("../ensemble", "../test", "../ensemble_sub")
calibrate("../ensemble_sub", "../ensemble_cal")
Ejemplo n.º 30
0
#spec.check_connected() #allows you to check that you are ready to take data

''' Open your Data'''

#f = pyfits.open('test.fits')
#f[0].header
# f[1].data['auto0_real'] #returns the first spectrum for the first polarization
# f[1].data['auto1_real'] #returns the first spectrum for the second polarization
#f[N].data[’auto0 real’] returns the N th spectrum for the first polarization.


#plt.plot(f[10].data['auto0_real'])
#Spectrometer.read_spec('noise_off.fits',100,(80.01,180.01),'eq')

calibrate.calibrate()
#Spectrometer.read_spec('noise_on.fits',100,(80.01,180.01),'eq')


#Spectrometer.read_spec('cassiopea1.fits',100,(6.45,62.73),'eq')

f = pyfits.open('Calibrate633.fits')
power = f[1].data['auto0_real']
freq = np.fft.fftfreq(len(power))
plt.plot(power)

hdu = fits.open('noise_off.fits')
hdr = hdu[1].header
data = hdu[1].data[0]
plt.plot(data)
Ejemplo n.º 31
0
    retake = False

    if retake:
        for i in range(12):
            _f = dr.c.photo()
            print(_f)
            print(_f.shape)
            strformat = "%d.jpg" % i
            cv.imwrite(strformat, _f)
            print("Successfully saved image %d" % i)
            sleep(3)

images = glob.glob("../calPiCamera/*.jpg")
print("Images globbed")
print(images)
intrinsic, distortion, _, _, err = calibrate.calibrate(images, drawTime=1000)
print(intrinsic, err)

# Clear up dat file
if test:
    id = str(dr.c.id)
else:
    id = 0
f = open("../intrinsic/intrinsic_%s.dat" % id, 'w')
f.close()

with open("../intrinsic/intrinsic_%s.dat" % id, 'w') as f:
    for i in intrinsic:
        for j in i:
            print(j)
            f.write("%s|" % j)
Ejemplo n.º 32
0
                    if timestamp - lasttime > 60:
                        print('no recent', key, 'data. triggering calibration')
                        cali = None
                if timestamp - lasttimeall > 30:
                    print('no reasonable data. triggering calibration')
                    cali = None

        if not cali:
            if not lastcalistart:
                lastcalistart = timestamp
            elif timestamp - lastcalistart > 120:
                print('calibration fails since', timestamp - lastcalistart,
                      'seconds.')
                sleep(300)
                lastcalistart = None
            cali = calibrate(file)
            if cali:
                print('calibration', cali)
                lastcalistart = None
                writeCalibration(cali)
                lasttimes = newTimes(timestamp)
                lastkey = 'tag'

        if not os.path.exists('keepimg'):
            os.remove(file)

except KeyboardInterrupt:
    pass

print('stopping camera')
camera.stop_preview()