Ejemplo n.º 1
0
def saxsdog():
    """
    This implements the functionality of :ref:`saxsdog`
    """
    (options, args) = saxsdogparseopt()

    if options.profile:
        import cProfile, pstats, StringIO
        pr = cProfile.Profile()
    conf = json.load(open(options.calfilename, "r"))
    cals = []
    directory = args[0]
    if "Masks" in conf:
        for mnumber, mask in enumerate(conf["Masks"]):
            cals.append(calibration.calibration(conf, mask, None))
    if "Slices" in conf:
        for slice in conf["Slices"]:
            cals.append(GISAXSSlices.slice(conf, slice, None))
    imgq = imagequeuelib.imagequeue(cals, options, directory, None)
    if options.profile:
        pr.enable()

    imgq.start()

    if options.profile:
        pr.disable()
        s = StringIO.StringIO()
        sortby = 'cumulative'
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.print_stats()
        print "#####################################"
        print '# Wrote profile to the file "prof". #'
        print '#####################################'
        open("prof", "w").write(s.getvalue())
Ejemplo n.º 2
0
def setup():

    global ret, mtx, dist, rvecs, tvecs
    ret, mtx, dist, rvecs, tvecs = calibration()
    print("Generated calibration data!")

    global warp_matrix, warp_matrix_inverse
    warp_matrix, warp_matrix_inverse = generate_warp_config()
Ejemplo n.º 3
0
def main():
    argvs = sys.argv  # コマンドライン引数を格納したリストの取得
    argc = len(argvs) # 引数の個数
    
    # デバッグプリント
    if (argc != 3):   # 引数が足りない場合は、その旨を表示
        print('Usage: # python %s basedir basename' % argvs[0])
        quit()         # プログラムの終了
        
    calib = calibration.calibration()
    
    #Hページ
    inname = argvs[1] + "\\" + argvs[2] + "_H.csv"
    results_H = np.loadtxt(inname, delimiter=',')
    #Hページの値を処理  
    results_H[:,1] = calib.cranc / results_H[:,1]
    results_H[:,2] = calib.prop / results_H[:,2]
    results_H[:,3] = samplerate * calib.ias1 * results_H[:,3] + calib.ias2
    results_H[:,4] *= calib.alt

    #グラフ描画
    font_path = "C:\Windows\Fonts\meiryo.ttc"
    font_prop = font_manager.FontProperties(fname=font_path)
    font_prop.set_style('normal')
    font_prop.set_weight('light')
    font_prop.set_size('large')
    
    figsize = (24, 13.5)
    fig = plt.figure(figsize=figsize)
    fig.subplots_adjust(hspace=0.001)
    ax1 = fig.add_subplot(111)
    ax1r = ax1.twinx()
    line1 = ax1.plot(results_H[:,0], results_H[:,1], color = 'r', label = u"クランク回転数")
    line2 = ax1.plot(results_H[:,0], results_H[:,2] * 0.5, color = 'g', label = u"プロペラ回転数")
    line3 = ax1r.plot(results_H[:,0], results_H[:,3], color = 'b', label = u"対気速度")
    line4 = ax1r.plot(results_H[:,0], results_H[:,4], color = 'k', label = u"対地高度")
    ax1.set_yticks(np.arange(0.0, 150.1, 50.0))
    ax1.set_ylim(0.0,150.0)
    ax1r.set_yticks(np.arange(0.0, 15.1, 5.0))
    ax1r.set_ylim(0.0,15.0)
    formatter = ticker.FormatStrFormatter('%0.0f')
    ax1.xaxis.set_major_formatter(formatter)
    ax1.set_title(argvs[1] + "\\" + argvs[2], fontproperties=font_prop)
    ax1.set_xlabel(u"GPS時刻[s]", fontproperties=font_prop)
    ax1.set_ylabel(u"クランク回転数[rpm]\nプロペラ回転数[x0.5rpm]", fontproperties=font_prop)
    ax1r.set_ylabel(u"対気速度[m/s]\n対地高度[m]", fontproperties=font_prop)
    ax1.grid(True)
    ax1.legend(prop=font_prop, bbox_to_anchor=(0.885, 1.0), loc=2, borderaxespad=0., frameon = False)
    ax1r.legend(prop=font_prop, bbox_to_anchor=(0.885, 0.935), loc=2, borderaxespad=0., frameon = False)
    
#    canvas = FigureCanvasAgg(fig)  
       
    plt.figure(1, figsize=figsize)
#    figManager = _pylab_helpers.Gcf.get_active()
#    figManager.canvas.figure = fig
    plt.show()
 def clean_shutdown(self):
     # stop the controller and the ROS node
     self.is_stopping = True
     moveit_commander.roscpp_shutdown()
     # Calculate an optimal transformation for the samples
     if self.data_amount > self.optimization_threshold:
         self.calibrated_tf = clb.calibration(
             parent_folder=self.package_dir, realsense=self.realsense)
     else:
         rospy.loginfo('Not enough samples collected: %f', self.data_amount)
     print("\nExiting the rgbd tf calibration!")
Ejemplo n.º 5
0
 def makeCalib(self): #function to call calibration module, using getInfWin to collect user input
     detectorName, maxEv, peaks, ok=getInfWin.getInfWin.getInf(self)
     if ok:
         fileName=QtGui.QFileDialog.getOpenFileName(self,'Open file','/home') #prompts open file explorer for user to select file
         calRes=calibration.calibration(fileName,detectorName) #call calibration object
         calRes.peak=peaks
         calRes.maxEv=float(maxEv)
         calRes.process() 
         impExp.saveToFile(calRes, calRes.fileLoc.replace(".bin",".gaze")) #using pickle, saves calibrated data (calRes) as .gaze file
         self.calibData.append(calRes)
         self.calibName.append(calRes.detName)
Ejemplo n.º 6
0
    def __init__(self):
        #   globls.dump_log("Initiated eye data reader thread")
        self.EyeTrack = None
        self.eye_recording_thread = None
        self.analog_reader_obj = None
        self.calibration = calibration()
        self.eye_check = ValidateVergenceVersion()

        # Initialize based on the recording method selection
        if globls.eye_recording_method == EyeRecordingMethods.EYE_LINK:
            self.digital_reader()
        elif globls.eye_recording_method == EyeRecordingMethods.EYE_COIL:
            self.analog_reader()
Ejemplo n.º 7
0
def saxsdog():
    """
    This implements the functionality of :ref:`saxsdog`
    """
    (options, args)=saxsdogparseopt()
   
    if options.profile: 
        import cProfile, pstats, StringIO
        pr = cProfile.Profile()
    conf=json.load(open(options.calfilename,"r"))
    cals=[]
    directory=args[0]
    if "Masks" in conf:
        for mnumber,mask in enumerate(conf["Masks"]):
            cals.append(calibration.calibration(
                                           conf,
                                            mask,
                                             None))
    if "Slices" in   conf:
        for slice in conf["Slices"]:
            cals.append(GISAXSSlices.slice( conf,slice,None))
    imgq=imagequeuelib.imagequeue(cals,
                options,directory,None)
    if options.profile: 
        pr.enable()
    
    imgq.start()
    
    if options.profile:       
        pr.disable()
        s = StringIO.StringIO()
        sortby = 'cumulative'
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.print_stats()
        print "#####################################"
        print '# Wrote profile to the file "prof". #'
        print '#####################################'
        open("prof","w").write(s.getvalue())
    def control_from_poseset(self):

        #print "waiting for action file: ", os.path.abspath(file_name)
        # while not self.is_stopping:
        for i in self.moving_poses:
            if self.is_stopping:
                break
            self.rate.sleep()
            rospy.loginfo('Moving the end-effector of the left limb to %s ...',
                          i)
            # Move to a new joint pos
            self.moving_arm.move_to_joint_positions(i)
            rospy.sleep(2.0)

            # Clear previous history poses
            self.ar_pose_history_clear()

            # Wait the AR pose recognition for 20 s
            t_end = time.time() + self.ar_pose_waiting_time
            while (not self.is_stopping) and time.time() < t_end:
                self.rate.sleep()
                (pose_reliable, x, y, z, x_o, y_o,
                 z_o) = self.process_ar_pose()
                # pose_reliable = True
                if pose_reliable:
                    # Read tf transformation within 10s
                    try:
                        self.tf_listener.waitForTransform(
                            '/base', self.marker_end, rospy.Time(0),
                            rospy.Duration(self.tf_waiting_time))
                        (trans, rot) = self.tf_listener.lookupTransform(
                            '/base', self.marker_end, rospy.Time(0))
                    except (tf.LookupException, tf.ConnectivityException,
                            tf.ExtrapolationException):
                        continue

                    # Update the pose from /kinect to a AR marker
                    self.update_data_file(self.file_name_k2m,
                                          [x, y, z, x_o, y_o, z_o])

                    # Update the pose from /base to /left_gripper_base
                    b2e_pose = self.quaternion_to_euler([
                        trans[0], trans[1], trans[2], rot[0], rot[1], rot[2],
                        rot[3]
                    ])
                    self.update_data_file(self.file_name_b2e, b2e_pose)

                    self.data_amount = self.data_amount + 1
                    rospy.loginfo('Simples collected: %f', self.data_amount)
                    break

            if not pose_reliable:
                self.eleminated_data_amount = self.eleminated_data_amount + 1
                rospy.loginfo('Simples eliminated: %f',
                              self.eleminated_data_amount)
                self.rename_eliminated_pose()

        # Calculate an optimal transformation for the samples
        if self.data_amount > self.optimization_threshold:
            self.calibrated_tf = clb.calibration(
                parent_folder=self.package_dir, realsense=self.realsense)
        else:
            rospy.loginfo('Not enough samples collected: %f', self.data_amount)
    def control_manually(self):

        #print "waiting for action file: ", os.path.abspath(file_name)
        while not self.is_stopping:
            self.rate.sleep()
            rospy.loginfo(
                'Please manually move the %s limb to desired poses ...',
                self.limb)
            # Wait for the press of Enter
            try:
                input('Move the arm to a desired pose, then press Enter:')
            except SyntaxError:
                pass

            # Clear previous history poses
            self.ar_pose_history_clear()

            # Wait the AR pose recognition for 20 s
            t_end = time.time() + self.ar_pose_waiting_time
            while (not self.is_stopping) and time.time() < t_end:
                self.rate.sleep()
                (pose_reliable, x, y, z, x_o, y_o,
                 z_o) = self.process_ar_pose()

                # pose_reliable = True
                if pose_reliable:
                    # Read tf transformation within 10s
                    try:
                        self.tf_listener.waitForTransform(
                            '/base', self.marker_end, rospy.Time(0),
                            rospy.Duration(self.tf_waiting_time))
                        (trans, rot) = self.tf_listener.lookupTransform(
                            '/base', self.marker_end, rospy.Time(0))
                    except (tf.LookupException, tf.ConnectivityException,
                            tf.ExtrapolationException):
                        continue

                    # Update the pose from /kinect to a AR marker
                    self.update_data_file(self.file_name_k2m,
                                          [x, y, z, x_o, y_o, z_o])

                    # Update the pose from /base to /left_gripper_base
                    b2e_pose = self.quaternion_to_euler([
                        trans[0], trans[1], trans[2], rot[0], rot[1], rot[2],
                        rot[3]
                    ])
                    self.update_data_file(self.file_name_b2e, b2e_pose)

                    # Update the joints pos history of the left arm
                    angles = self.left_arm.joint_angles()
                    self.update_joints_pos_file(self.file_name_left_arm_poses,
                                                self.left_joints, angles)

                    # Update the joints pos history of the right arm
                    angles = self.right_arm.joint_angles()
                    self.update_joints_pos_file(self.file_name_right_arm_poses,
                                                self.right_joints, angles)

                    self.data_amount = self.data_amount + 1
                    rospy.loginfo('Simples collected: %f', self.data_amount)

                    # Real-time caibration, for sample collection reference
                    if self.data_amount > self.optimization_threshold:
                        self.calibrated_tf = clb.calibration(
                            parent_folder=self.package_dir,
                            realsense=self.realsense)

                    break

            if not pose_reliable:
                self.eleminated_data_amount = self.eleminated_data_amount + 1
                rospy.loginfo('Simples eliminated: %f',
                              self.eleminated_data_amount)
                self.rename_eliminated_pose()
Ejemplo n.º 10
0
from sklearn.naive_bayes import BernoulliNB
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import metrics
import warnings
import math
from sklearn import preprocessing

p = "./models/shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(p)

from calibration import calibration
from live import live

#Run Calibration
mean, std = calibration()

print(mean, std)

data, result = live(mean, std)

for D, r in zip(data, result):
    print(D)
    print(r)
    print('\n')
Ejemplo n.º 11
0
def saxsdogcal(options, args):
    """
    Calculate computation matrices from calibration data
    """
    from calibration import calibration
    return calibration(options.calfilename)
def main(date, version='01',
    save_calibrated_data=False):

    datadir = '../data/wind_waves_l2_hres/1999'
    
    # calls waves_rad1_l2_analysis (externally)
    spin_df = process_l2(date, datadir)

    if spin_df is None:
        # all data invalidated - generate empty dataframe

        out_df = generate_empty_dataframe()

    else:
        
        flux_df = cal.calibration(spin_df)
        print(flux_df.columns)
        
        flux_label = 'flux_si'

        if save_calibrated_data:
        
            # 3 minute resolution dataframe with calibrated flux
            out_flux_df = cal.create_calibrated_flux_dataframe(flux_df, flux_label)
            
            calibrated_data_file = '../data/calibrated_data/final/1999'

            calibrated_flux_fp = 'wi_wa_rad1_l3_no_selection_{}.csv'.format(
                date.strftime('%Y%m%d'),
                date.strftime('%j')
            )

            fp = os.path.join(calibrated_data_file, calibrated_flux_fp)

            out_flux_df.to_csv(fp, index=False)

        # if normalise_wind_flux:

        # normalise data (Wind to 1 AU for comparison)
        flux_df['flux_si_1au'] = normalise_flux(flux_df['flux_si'], flux_df['RADIUS'])

        flux_label = 'flux_si_1au'

        out_df = cal.create_calibrated_flux_dataframe(flux_df, flux_label, flux_label)

        # now selection on sigma_z        
        out_df = select_akr(out_df, flux_label, 'akr_flux_si_1au')

        print(out_df.columns)

    # Save output
    out_dir = '../data/masked_flux/1999'
    
    out_fn = 'wi_wa_rad1_l3_akr_{}_v{}.csv'.format(date.strftime('%Y%m%d'),
        version)

    keep_cols = ['datetime_ut', 'freq', 'snr_db', 'akr_flux_si_1au']
    out_df = out_df.loc[:, keep_cols]

    fp = os.path.join(out_dir, out_fn)
    out_df.to_csv(fp, na_rep='-1', index=False)

    return None
Ejemplo n.º 13
0
            self.last_packet_number = packet_number
        gc.collect()
        #print(gc.mem_free())


with uio.open('/flash/configure.json', 'r', encoding="utf-8") as handle:
    psd_json = ujson.load(handle)

p_in_mod = Pin('P12', mode=Pin.IN, pull=Pin.PULL_UP)
p_out_mod = Pin('P11', mode=Pin.OUT)

p_out_mod.value(1)

if p_in_mod() == 0:
    print('[1]MODE_1 selected. Entering sensor zero-point calibration mode...')
    calibration.calibration(1, psd_json["calibration"]["vref"])
    sys.exit()

time.sleep(0.5)

p_in_mod = Pin('P12', mode=Pin.IN, pull=Pin.PULL_UP)

p_out_mod.value(0)
time.sleep(0.5)

if p_in_mod() == 0:
    print('[1]MODE_0 selected. Entering ADC bias calibration mode...')
    calibration.calibration(0, psd_json["calibration"]["vref"])
    sys.exit()

print('[1]MODE_2 selected. Entering normal operation...')
Ejemplo n.º 14
0
def main():
    argvs = sys.argv  # コマンドライン引数を格納したリストの取得
    argc = len(argvs) # 引数の個数
    
    # デバッグプリント
    if (argc != 3):   # 引数が足りない場合は、その旨を表示
        print('Usage: # python %s basedir basename' % argvs[0])
        quit()         # プログラムの終了
        
    calib = calibration.calibration()
    
    if (hpanavi == 1 and tinyfeather == 1):
        basedir1 = argvs[1] + "\\HPANavi\\"
        basedir2 = argvs[1] + "\\TinyFeather\\"
    elif (hpanavi == 1 and tinyfeather == 0):
        basedir1 = argvs[1] + "\\HPANavi\\"
        basedir2 = argvs[1] + "\\HPANavi\\"
    else:        
        basedir1 = argvs[1] + "\\"
        basedir2 = argvs[1] + "\\"
        
    #Gページ    
    inname = basedir2 + argvs[2] + "_G.csv"
    outname = basedir2 + argvs[2] + "_G_out.csv"
    d = np.loadtxt(inname, delimiter=',')
    #GPS時刻を基準にする。ログの切り出し誤差を考慮して最初と最後の1秒ずつは捨てる
    computed_time = np.linspace(d[0,0] + 1.0, d[-1,0] - 1.0, (d[-1,0] - 1.0 - d[0,0] - 1.0) * samplerate + 1)
    results_G = read_page(d, computed_time, "G")
    GS=[]
    for i in range(len(results_G[6])):
        GS.append(math.sqrt(results_G[6][i]*results_G[6][i]+results_G[7][i]*results_G[7][i]))
#    np.savetxt(outname, zip(*results_G), delimiter=',') 
    np.savetxt(outname, np.transpose(results_G), delimiter=',') 

    #Aページ 
    inname = basedir2 + argvs[2] + "_A.csv"
    outname = basedir2 + argvs[2] + "_A_out.csv"
    d = np.loadtxt(inname, delimiter=',')
    results_A = read_page(d, computed_time, "A")
    np.savetxt(outname, np.transpose(results_A), delimiter=',')
    
    #Mページ
    inname = basedir2 + argvs[2] + "_M.csv"
    outname = basedir2 + argvs[2] + "_M_out.csv"
    d = np.loadtxt(inname, delimiter=',') 
    d[:,0] += ( d[:,1] * 0.04)  #indexを処理
    results_M = read_page(d, computed_time, "M")
    np.savetxt(outname, np.transpose(results_M), delimiter=',')
    
    #Hページ
    inname = basedir1 + argvs[2] + "_H.csv"
    outname = basedir1 + argvs[2] + "_H_out.csv"
    d = np.loadtxt(inname, delimiter=',') 
    results_H = read_page(d, computed_time, "H")
    #Hページの値を処理  
    results_H[1] = calib.cranc / results_H[1]
    results_H[2] = calib.prop / results_H[2]
    results_H[3] = samplerate * calib.ias1 * results_H[3] + calib.ias2
    results_H[4] *= calib.alt
    results_H[5] = (results_H[5] - calib.aileron2) / calib.adcmax * calib.encordermax * calib.aileron1
    results_H[6] = -(results_H[6] - calib.rudder2) / calib.adcmax * calib.encordermax * calib.rudder1
    results_H[7] = (results_H[7] - calib.elevetor2) / calib.adcmax * calib.encordermax * calib.elevetor1
    np.savetxt(outname, np.transpose(results_H), delimiter=',')

    #Nページ
    inname = basedir2 + argvs[2] + "_N.csv"
    outname = basedir2 + argvs[2] + "_N_out.csv"    
    d = np.loadtxt(inname, delimiter=',')
    if modifyyaw == 1:
        for i in range(len(d[:,7])):
            if d[i,7] < 0:
                d[i,7] += 360.0
    results_N = read_page(d, computed_time, "N")
    np.savetxt(outname, np.transpose(results_N), delimiter=',')

    #グラフ描画
    font_path = "C:\Windows\Fonts\meiryo.ttc"
    font_prop = font_manager.FontProperties(fname=font_path)
    font_prop.set_style('normal')
    font_prop.set_weight('light')
    font_prop.set_size('large')
    
    figsize = (24, 13.5)
    fig = plt.figure(figsize=figsize)
    fig.subplots_adjust(hspace=0.001)

    ax1 = fig.add_subplot(311)
    ax1r = ax1.twinx()
    line1 = ax1.plot(results_H[0], results_H[1], color = 'r', label = u"クランク回転数")
    line2 = ax1.plot(results_H[0], results_H[2] * 0.5, color = 'g', label = u"プロペラ回転数")
    line3 = ax1r.plot(results_H[0], results_H[3], color = 'b', label = u"対気速度")
    line4 = ax1r.plot(results_G[0], GS, color = 'c', label = u"対地速度")
    line5 = ax1r.plot(results_H[0], results_H[4], color = 'k', label = u"対地高度")
    ax1.set_yticks(np.arange(0.0, 150.1, 50.0))
    ax1.set_ylim(0.0,150.0)
    ax1r.set_yticks(np.arange(0.0, 15.1, 5.0))
    ax1r.set_ylim(0.0,15.0)
    ax1.set_title(argvs[1] + "\\" + argvs[2], fontproperties=font_prop)
    ax1.set_xlabel('')
    ax1.set_ylabel(u"クランク回転数[rpm]\nプロペラ回転数[x0.5rpm]", fontproperties=font_prop)
    ax1r.set_ylabel(u"対気速度[m/s]\n対地高度[m]", fontproperties=font_prop)
    ax1.tick_params(labelbottom = 'off')
    ax1.grid(True)
    ax1.legend(prop=font_prop, bbox_to_anchor=(0.885, 1.0), loc=2, borderaxespad=0., frameon = False)
    ax1r.legend(prop=font_prop, bbox_to_anchor=(0.885, 0.815), loc=2, borderaxespad=0., frameon = False)
    
    ax2 = fig.add_subplot(312)    
    ax2r = ax2.twinx()
    if hpanavi == 0:
        line6 = ax2.plot(results_N[0], results_N[8] + pitch_offset, color = 'r', label = u"ピッチ角")
        line7 = ax2.plot(results_N[0], results_N[9] + roll_offset, color = 'b', label = u"ロール角")
    else:
        line6 = ax2.plot(results_N[0], results_N[9] + pitch_offset, color = 'r', label = u"ピッチ角") 
        line7 = ax2.plot(results_N[0], results_N[8] + roll_offset, color = 'b', label = u"ロール角")       
    line5 = ax2r.plot(results_N[0], results_N[7] + yaw_offset, color = 'g', label = u"ヨー角")
    ax2.set_yticks(np.arange(-25.0, 25.0, 5.0))
    ax2.set_ylim(-25.0,25.0)
    ax2.set_xlabel('')
    ax2.set_ylabel(u"ピッチ角[deg.]\nロール角[deg.]", fontproperties=font_prop)
    ax2r.set_ylabel(u"ヨー角[deg.]", fontproperties=font_prop)
    ax2.tick_params(labelbottom = 'off')
    ax2.grid(True) 
    ax2.legend(prop=font_prop, bbox_to_anchor=(0.885, 1.0), loc=2, borderaxespad=0., frameon = False)
    ax2r.legend(prop=font_prop, bbox_to_anchor=(0.885, 0.815), loc=2, borderaxespad=0., frameon = False)
    
    ax3 = fig.add_subplot(313)    
    line10 = ax3.plot(results_H[0], results_H[7] + elevetor_offset, color = 'r', label = u"エレベータ舵角")
    line8 = ax3.plot(results_H[0], results_H[5] + aileron_offset, color = 'b', label = u"エルロン舵角")
    line9 = ax3.plot(results_H[0], results_H[6] + rudder_offset, color = 'g', label = u"ラダー舵角")
    ax3.set_yticks(np.arange(-25.0, 25.0, 5.0))
    ax3.set_ylim(-25.0, 25.0)
    ax3.set_xlabel(u"GPS時刻[s]", fontproperties=font_prop)
    ax3.set_ylabel(u"エレベータ舵角[deg.]\nエルロン舵角[deg.]\nラダー舵角[deg.]", fontproperties=font_prop)
    ax3.grid(True)
    ax3.legend(prop=font_prop, bbox_to_anchor=(0.885, 1.0), loc=2, borderaxespad=0., frameon = False)
    
    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(argvs[1] + "\\" + argvs[2] + "_out.png", dpi=80)
       
    plt.figure(1, figsize=figsize)
    figManager = _pylab_helpers.Gcf.get_active()
    figManager.canvas.figure = fig
    plt.show()
@author: xumr
"""

import numpy as np
import cv2
from matplotlib import pyplot as plt
from calibration import calibration
import time

start = time.clock()
'''Initialization'''

sample = 'Sample1'

calibration = calibration()
# Arrays to store object points and image points from all the images.
objpoints = []  # 3d point in real world space
imgpoints = {"t_left": [], "t_right": []}  # 2d points in image plane.
image_size = (720L, 480L)
#: Camera matrices (M)
cam_mats = {"t_left": None, "t_right": None}
#: Distortion coefficients (D)
dist_coefs = {"t_left": None, "t_right": None}
rvecs = {"t_left": None, "t_right": None}  #from camer to image?
tvecs = {"t_left": None, "t_right": None}
sides = ['t_left', 't_right']
rect_trans = {"t_left": None, "t_right": None}
proj_mats = {"t_left": None, "t_right": None}
valid_boxes = {"t_left": None, "t_right": None}
map1 = {"t_left": None, "t_right": None}
Ejemplo n.º 16
0
def main():
    while True:

        time = datetime.now()
        hour = int(time.strftime("%-H"))
        month = int(time.now().strftime('%-m'))
        year = int(time.now().strftime('%Y'))

        for i in range(1):
            print('_________Starting new loop___________' + '\n')
            """At the following hours (midnight, midday and 6 pm), perform
               a calibration of the display's colours"""

            if hour is 0 or hour is 12 or hour is 18:
                print('performing calibration for colours now')
                calibration()

            print(
                'Date:',
                time.strftime('%a %-d %b %y') + ', time: ' +
                time.strftime('%H:%M') + '\n')
            """Create a blank white page, for debugging, change mode to
            to 'RGB' and and save the image by uncommenting the image.save
            line at the bottom"""
            image = Image.new('L', (EPD_HEIGHT, EPD_WIDTH), 'white')
            draw = (ImageDraw.Draw(image)).bitmap
            """Draw the icon with the current month's name"""
            image.paste(im_open(mpath + str(time.strftime("%B") + '.jpeg')),
                        monthplace)
            """Draw a line seperating the weather and Calendar section"""
            image.paste(seperator, seperatorplace)
            """Draw the icons with the weekday-names (Mon, Tue...) and
               draw a circle  on the current weekday"""
            if (week_starts_on == "Monday"):
                calendar.setfirstweekday(calendar.MONDAY)
                image.paste(weekmon, weekplace)
                draw(weekdaysmon[(time.strftime("%a"))], weekday)

            if (week_starts_on == "Sunday"):
                calendar.setfirstweekday(calendar.SUNDAY)
                draw(weekplace, weeksun)
                image.paste(weeksun, weekplace)
                draw(weekdayssun[(time.strftime("%a"))], weekday)
            """Using the built-in calendar function, draw icons for each
               number of the month (1,2,3,...28,29,30)"""
            cal = calendar.monthcalendar(time.year, time.month)
            #print(cal) #-uncomment for debugging with incorrect dates

            for numbers in cal[0]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['a' + str(cal[0].index(numbers) + 1)])
            for numbers in cal[1]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['b' + str(cal[1].index(numbers) + 1)])
            for numbers in cal[2]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['c' + str(cal[2].index(numbers) + 1)])
            for numbers in cal[3]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['d' + str(cal[3].index(numbers) + 1)])
            for numbers in cal[4]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['e' + str(cal[4].index(numbers) + 1)])
            try:
                for numbers in cal[5]:
                    image.paste(
                        im_open(dpath + str(numbers) + '.jpeg'),
                        positions['f' + str(cal[5].index(numbers) + 1)])
            except IndexError:
                pass
            """Custom function to display text on the E-Paper.
            Tuple refers to the x and y coordinates of the E-Paper display,
            with (0, 0) being the top left corner of the display."""
            def write_text(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                if (text_width, text_height) > (box_width, box_height):
                    raise ValueError('Sorry, your text is too big for the box')
                else:
                    x = int((box_width / 2) - (text_width / 2))
                    y = int((box_height / 2) - (text_height / 2))
                    space = Image.new('L', (box_width, box_height), color=255)
                    ImageDraw.Draw(space).text((x, y), text, fill=0, font=font)
                    image.paste(space, tuple)

            """ Handling Openweathermap API"""
            print("Connecting to Openweathermap API servers...")
            owm = pyowm.OWM(api_key)
            if owm.is_API_online() is True:
                observation = owm.weather_at_place(location)
                print("weather data:")
                weather = observation.get_weather()
                weathericon = weather.get_weather_icon_name()
                Humidity = str(weather.get_humidity())
                cloudstatus = str(weather.get_clouds())
                weather_description = (str(weather.get_status()))

                if units == "metric":
                    Temperature = str(
                        int(weather.get_temperature(unit='celsius')['temp']))
                    windspeed = str(int(weather.get_wind()['speed']))
                    write_text(50, 35, Temperature + " °C", (334, 0))
                    write_text(100, 35, windspeed + " km/h", (114, 0))

                if units == "imperial":
                    Temperature = str(
                        int(weather.get_temperature('fahrenheit')['temp']))
                    windspeed = str(int(weather.get_wind()['speed'] * 0.621))
                    write_text(50, 35, Temperature + " °F", (334, 0))
                    write_text(100, 35, windspeed + " mph", (114, 0))

                if hours == "24":
                    sunrisetime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunrise_time(
                                timeformat='unix'))).strftime('%-H:%M'))
                    sunsettime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunset_time(
                                timeformat='unix'))).strftime('%-H:%M'))

                if hours == "12":
                    sunrisetime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunrise_time(
                                timeformat='unix'))).strftime('%-I:%M'))
                    sunsettime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunset_time(
                                timeformat='unix'))).strftime('%-I:%M'))

                print('Temperature: ' + Temperature + ' °C')
                print('Humidity: ' + Humidity + '%')
                print('Icon code: ' + weathericon)
                print('weather-icon name: ' + weathericons[weathericon])
                print('Wind speed: ' + windspeed + 'km/h')
                print('Sunrise-time: ' + sunrisetime)
                print('Sunset time: ' + sunsettime)
                print('Cloudiness: ' + cloudstatus + '%')
                print('Weather description: ' + weather_description + '\n')
                """Drawing the fetched weather icon"""
                image.paste(
                    im_open(wpath + weathericons[weathericon] + '.jpeg'),
                    wiconplace)
                """Drawing the fetched temperature"""
                image.paste(tempicon, tempplace)
                """Drawing the fetched humidity"""
                image.paste(humicon, humplace)
                write_text(50, 35, Humidity + " %", (334, 35))
                """Drawing the fetched sunrise time"""
                image.paste(sunriseicon, sunriseplace)
                write_text(50, 35, sunrisetime, (249, 0))
                """Drawing the fetched sunset time"""
                image.paste(sunseticon, sunsetplace)
                write_text(50, 35, sunsettime, (249, 35))
                """Drawing the wind icon"""
                image.paste(windicon, windiconspace)
                """Write a short weather description"""
                write_text(144, 35, weather_description, (70, 35))

            else:
                image.paste(no_response, wiconplace)
            """Filter upcoming events from your iCalendar/s"""
            print('Fetching events from your calendar' + '\n')
            events_this_month = []
            upcoming = []

            for icalendars in ical_urls:
                ical = Calendar(urlopen(icalendars).read().decode())
                for events in ical.events:
                    if time.now().strftime('%-m %Y') == (
                            events.begin).format('M YYYY'):
                        upcoming.append({
                            'date': events.begin.format('D MMM'),
                            'event': events.name
                        })
                        events_this_month.append(
                            int((events.begin).format('D')))
                    if month == 12:
                        if (1, year + 1) == (1, int((events.begin).year)):
                            upcoming.append({
                                'date':
                                events.begin.format('D MMM'),
                                'event':
                                events.name
                            })
                    if month != 12:
                        if (month + 1,
                                year) == (events.begin).format('M YYYY'):
                            upcoming.append({
                                'date':
                                events.begin.format('D MMM'),
                                'event':
                                events.name
                            })

            del upcoming[4:]

            def write_text_left(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                if (text_width, text_height) > (box_width, box_height):
                    raise ValueError('Sorry, your text is too big for the box')
                else:
                    y = int((box_height / 2) - (text_height / 2))
                    space = Image.new('L', (box_width, box_height), color=255)
                    ImageDraw.Draw(space).text((0, y), text, fill=0, font=font)
                    image.paste(space, tuple)

            """Write event dates and names on the E-Paper"""
            for dates in range(len(upcoming)):
                write_text(70, 25, (upcoming[dates]['date']),
                           date_positions['d' + str(dates + 1)])

            for events in range(len(upcoming)):
                write_text_left(314, 25, (upcoming[events]['event']),
                                event_positions['e' + str(events + 1)])
            """Draw smaller squares on days with events"""
            for numbers in events_this_month:
                if numbers in cal[0]:
                    draw(positions['a' + str(cal[0].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[1]:
                    draw(positions['b' + str(cal[1].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[2]:
                    draw(positions['c' + str(cal[2].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[3]:
                    draw(positions['d' + str(cal[3].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[4]:
                    draw(positions['e' + str(cal[4].index(numbers) + 1)],
                         eventicon)
                try:
                    if numbers in cal[5]:
                        draw(positions['f' + str(cal[5].index(numbers) + 1)],
                             eventicon)
                except IndexError:
                    pass
            """Draw a larger square on today's date"""
            today = time.day
            if today in cal[0]:
                draw(positions['a' + str(cal[0].index(today) + 1)], dateicon)
            if today in cal[1]:
                draw(positions['b' + str(cal[1].index(today) + 1)], dateicon)
            if today in cal[2]:
                draw(positions['c' + str(cal[2].index(today) + 1)], dateicon)
            if today in cal[3]:
                draw(positions['d' + str(cal[3].index(today) + 1)], dateicon)
            if today in cal[4]:
                draw(positions['e' + str(cal[4].index(today) + 1)], dateicon)
            try:
                if today in cal[5]:
                    draw(positions['f' + str(cal[5].index(today) + 1)],
                         dateicon)
            except IndexError:
                pass

            print('Initialising E-Paper Display')
            epd.init()
            sleep(5)
            print('Converting image to data and sending it to the display')
            print('This may take a while...' + '\n')
            epd.display_frame(epd.get_frame_buffer(image.rotate(270,
                                                                expand=1)))
            # Uncomment following line to save image
            #image.save(path+'test.png')
            del events_this_month[:]
            del upcoming[:]
            print('Data sent successfully')
            print('Powering off the E-Paper until the next loop' + '\n')
            epd.sleep()

            for i in range(1):
                nexthour = ((60 - int(time.strftime("%-M"))) * 60) - (int(
                    time.strftime("%-S")))
                sleep(nexthour)
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 17 19:05:05 2018

@author: qs
"""

from testCNN import predict
import cv2
import calibration
import numpy as np

GREEN = (0, 255, 0)
RED = (0, 0, 255)

surveillanceFeed1 = calibration.calibration('videoFeed/surveillanceFeed.mp4')
surveillanceFeed1.loadROI('roi/surveillanceFeed1.roi')

parkingSpot = surveillanceFeed1.parkingSpot

parkingSpot = parkingSpot[1:]

out = cv2.VideoWriter('output.mp4', -1, 20.0, (960, 720))

while True:
    _, frame = surveillanceFeed1.video.read()
    rows, cols, ch = frame.shape
    for spot in parkingSpot:

        # get a tilted ractangle box
        rect = cv2.minAreaRect(spot)
Ejemplo n.º 18
0
#DHT22 sensor initialize
sensor = Adafruit_DHT.DHT22
pin = sensorPin

#timer initialize
dataUploadTimer = time.time()
wateringTimer = time.time()

try:
    while True:
        loopTimer = time.time()
        #avoid using time.sleep() for timing out in main thread
        if ((loopTimer - dataUploadTimer) >= dataUploadTimeout):
            humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
            temperature += tempCalibrationOffset
            humidity = calibration(humidity)
            if humidity is not None and temperature is not None:
                print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(
                    temperature, humidity))
                thingSpeakParams = urllib.parse.urlencode({
                    'field1':
                    temperature,
                    'field2':
                    humidity,
                    'key':
                    thingSpeakApiKey
                })
                threadDispatcher('UPLOAD_DATA', thingSpeakParams)
                dataUploadTimer = time.time() + timeCalibration
            if (humidity is not None and
                (humidity < 0.0 or humidity > 100.0)) or (
Ejemplo n.º 19
0
#%% read input data
data = iciData("TB_ICI_test.nc", inChannels, target, batch_size=batchSize)

file = 'qrnn_ici_%s_%s_%s_single.nc' % (depth, width, target)
print(file)
qrnn = QRNN.load(file)

y_pre, y_prior, y0, y, y_pos_mean = S.predict(data, qrnn, add_noise=True)

# calibration plot data with correction greater than 15K

fig, ax = plt.subplots(1, 1, figsize=[8, 8])

im = np.arange(0, y0.size, 1)
a1, a2, a3, a4, a5, a6, intervals = calibration(y_pre, y0, im, quantiles)

(ax.plot(intervals[:], [
    a1 / len(y0[:]), a2 / len(y0[:]), a3 / len(y0[:]), a4 / len(y0[:]),
    a5 / len(y0[:])
],
         'r.-',
         ms=15,
         linewidth=2.5))

im = np.where(np.abs(y_pre[:, iq] - y_prior[:, i183]) >= 10)[0]
a1, a2, a3, a4, a5, a6, intervals = calibration(y_pre, y0, im, quantiles)

(ax.plot(intervals[:], [
    a1 / len(y0[im]), a2 / len(y0[im]), a3 / len(y0[im]), a4 / len(y0[im]),
    a5 / len(y0[im])
Ejemplo n.º 20
0
sFy = 41.0

# wood casing properties
wwidth = 10.0
wthick = 6.0

# Steel Material
E = 29000.0
R0 = 28.
cR1 = 0.94
cR2 = 0.11
a1 = 0.01
a2 = 1.0
a3 = 0.031
a4 = 1.0
si = 0.1

# Pinching Material
pEnvelopeStress = [0.0001, 0.0001, 0.0001, 0.0001]
nEnvelopeStress = [-2.272, -8.938, -16.0936, -27.6648]
pEnvelopeStrain = [0.001, 0.0086, 0.0137, 0.0213]
nEnvelopeStrain = [-0.00017, -0.0068, -0.0123, -0.0212]

rDisp = [0.55, 0.62]
rForce = [0.93, 0.69]
uForce = [0.35, 0.06]

results = calibration(length, lcore, LR_BRB, swidth, sthick, Acore, sFy,
                      wwidth, wthick, E, R0, cR1, cR2, a1, a2, a3, a4, si,
                      pEnvelopeStress, nEnvelopeStress, pEnvelopeStrain,
                      nEnvelopeStrain, rDisp, rForce, uForce, loadtype)
Ejemplo n.º 21
0
Archivo: Server.py Proyecto: isaxs/SAXS
    def start_image_queue(self, object, attachment):
        """
        prepare new image queue
        start processing threads
        """
        self.lasttime = time.time()
        self.lastcount = 0
        self.history = history()
        self.attachments = []
        for attachstr in attachment:
            self.attachments.append(json.loads(attachstr))
        self.calibration = object['argument']['calibration']
        print "abort old queue"
        if self.imagequeue:
            self.queue_abort()
        print "aborted old queue"
        try:
            if object['argument']['calibration'].get("Threads") > 0:
                self.threads = object['argument']['calibration'].get("Threads")
            else:
                self.threads = self.options.threads
            o = atrdict.AttrDict({
                "plotwindow":
                False,
                "threads":
                self.threads,
                "watch":
                self.options.watchdir,
                "watchdir":
                os.sep.join(
                    object['argument']['calibration'].get("Directory")),
                "servermode":
                True,
                "silent":
                True,
                "plotwindow":
                False,
                "walkdirinthreads":
                True,
                "outdir":
                self.options.outdir,
                "relpath":
                self.options.relpath,
                "writesvg":
                False,
                "writepng":
                False,
                "resume":
                False,
                "serverport":
                self.serverport
            })
            cals = []

            dir = os.path.normpath(
                os.path.join(
                    self.args[0],
                    os.sep.join(
                        object['argument']['calibration'].get('Directory'))))
            for mnumber, mask in enumerate(
                    object['argument']['calibration']["Masks"]):
                cals.append(
                    calibration.calibration(object['argument']['calibration'],
                                            mask, self.attachments[mnumber]))
            self.imagequeue = imagequeuelib.imagequeue(cals, o, [dir],
                                                       self.serverconf)
            print "startimgq"
            self.imagequeueprocess = Process(target=self.imagequeue.start)
            self.imagequeueprocess.start()
            print "listening to feeder"
            serverdir = self.args[0]
            self.feederproc = Process(target=subscribeToFileChanges,
                                      args=(self.imagequeue, self.feederurl,
                                            dir, serverdir))
            print "directory to watch " + dir

            self.feederproc.start()

            self.queuestatrtime = time.time()
            self.plotresult = {
                "result": "Empty",
                "data": {
                    "stat": self.stat()
                }
            }

            result = {
                "result": "new queue",
                "data": {
                    "cal": object['argument']['calibration']
                }
            }
        except IOError as e:
            result = {
                "result": "IOError",
                "data": {
                    "Error": str(e).replace("\n", " ")
                }
            }
        except ValueError as e:
            result = {"result": "ValueError", "data": {"Error": str(e)}}
        except Exception as e:
            result = {"result": "Error", "data": {"Error": str(e)}}
            print e
        return result
Ejemplo n.º 22
0
def main():
    while True:

        time = datetime.now()
        hour = int(time.strftime("%-H"))

        for i in range(1):
            """At the following hours (midnight, midday and 6 pm), perform
               a calibration of the display's colours"""
            if (hour is 0) or (hour is 12) or (hour is 18):
                print('performing calibration now')
                calibration()

            print('Current date:', time.strftime('%a %-d %b %y'))
            print('Current time:', time.strftime('%H:%M') + '\n')
            """Create a blank page"""
            image = Image.new('L', (EPD_WIDTH, EPD_HEIGHT), 255)
            draw = (ImageDraw.Draw(image)).bitmap
            """Draw the icon showing the current month"""
            draw(monthplace,
                 Image.open(mpath + str(time.strftime("%B")) + '.bmp'))
            """Draw the 3 lines that seperates the top section"""
            draw(seperatorplace, seperator)
            """Draw the icons with the weekday-names (Mon, Tue...) and
               draw a circle  on the current weekday"""
            if (week_starts_on == "Monday"):
                calendar.setfirstweekday(calendar.MONDAY)
                draw(weekplace, weekmon)
                draw(weekdaysmon[(time.strftime("%a"))], weekday)

            if (week_starts_on == "Sunday"):
                calendar.setfirstweekday(calendar.SUNDAY)
                draw(weekplace, weeksun)
                draw(weekdayssun[(time.strftime("%a"))], weekday)
            """Using the built-in calendar function, draw icons for each
               number of the month (1,2,3,...28,29,30)"""
            cal = calendar.monthcalendar(time.year, time.month)
            #print(cal) #-uncomment for debugging with incorrect dates

            for i in cal[0]:
                draw(positions['a' + str(cal[0].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[1]:
                draw(positions['b' + str(cal[1].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[2]:
                draw(positions['c' + str(cal[2].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[3]:
                draw(positions['d' + str(cal[3].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[4]:
                draw(positions['e' + str(cal[4].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            try:
                for i in cal[5]:
                    draw(positions['f' + str(cal[5].index(i) + 1)],
                         Image.open(dpath + str(i) + '.bmp'))
            except IndexError:
                pass
            """ Handling Openweathermap API"""
            try:
                print("Preparing to fetch data from openweathermap API")
                owm = pyowm.OWM(api_key)
                observation = owm.weather_at_place(location)
                print("Fetching weather data...")
                weather = observation.get_weather()
                weathericon = weather.get_weather_icon_name()

                Temperature = str(
                    int(weather.get_temperature(unit='celsius')['temp']))
                Humidity = str(weather.get_humidity())
                print('temperature: ' + Temperature + ' °C')
                print('humidity: ' + Humidity + '%')
                print('fetched icon code: ' + weathericon)
                print('equivalent to icon: ' + weathericons[weathericon] +
                      '\n')
                """Drawing the fetched weather icon"""
                draw(wiconplace,
                     open(wpath + weathericons[weathericon] + '.bmp'))
                """Drawing the fetched temperature"""
                space2 = Image.new('1', (50, 35), color=255)
                temperature = ImageDraw.Draw(space2)
                temperature.text((2, 8), (Temperature + " °C"),
                                 fill=0,
                                 font=font)
                rotate2 = space2.rotate(270, expand=1)
                image.paste(rotate2, (605, 334))
                """Drawing the fetched humidity"""
                space3 = Image.new('1', (50, 35), color=255)
                humidity = ImageDraw.Draw(space3)
                humidity.text((4, 8), (Humidity + '%'), fill=0, font=font)
                rotate3 = space3.rotate(270, expand=1)
                image.paste(rotate3, (570, 334))

            except Exception as e:
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(ex).__name__, ex.args)
                print(message)
                print("************ OWM DID NOT RESPOND *************")
                print("Drawing the 'no-response' icon on the display now")
                draw(wiconplace, no_response)
                pass
            """Drawing today's date at the top left corner"""
            """Uncomment this section (the following 5 lines) to hide date at top left corner"""
            space1 = Image.new('1', (115, 25), color=255)
            date = ImageDraw.Draw(space1)
            date.text((2, 3), (time.strftime('%a %-d %b %y')),
                      font=font,
                      fill=0)
            rotate1 = space1.rotate(270, expand=1)
            image.paste(rotate1, (595, 20))
            """Sort the Events in your iCalendar"""
            print('Fetching upcoming events from your calendar')
            elist = []
            for events in c.events:
                if time.year <= int((events.begin).format('YYYY')):
                    if time.month == int((events.begin).format('M')):
                        elist.append(int((events.begin).format('D')))
            """Uncomment the next 4 lines to print your events on the console"""
            #                        if time.day <= int((events.begin).format('D')):
            #                           print(events.name+' starts on '+events.begin.format('D '+'MMM '+'YYYY'))
            #                    if time.month < int((events.begin).format('M')):
            #                        print(events.name+' starts on '+events.begin.format('D '+'MMM '+'YYYY'))
            """Draw circles on any days which include an Event"""
            for x in elist:
                if x in cal[0]:
                    draw(positions['a' + str(cal[0].index(x) + 1)], eventicon)
                if x in cal[1]:
                    draw(positions['b' + str(cal[1].index(x) + 1)], eventicon)
                if x in cal[2]:
                    draw(positions['c' + str(cal[2].index(x) + 1)], eventicon)
                if x in cal[3]:
                    draw(positions['d' + str(cal[3].index(x) + 1)], eventicon)
                if x in cal[4]:
                    draw(positions['e' + str(cal[4].index(x) + 1)], eventicon)
                try:
                    if x in cal[5]:
                        draw(positions['f' + str(cal[5].index(x) + 1)],
                             eventicon)
                except IndexError:
                    pass
            """Draw a square with round corners on the today's date"""
            today = time.day
            if today in cal[0]:
                draw(positions['a' + str(cal[0].index(today) + 1)], dateicon)
            if today in cal[1]:
                draw(positions['b' + str(cal[1].index(today) + 1)], dateicon)
            if today in cal[2]:
                draw(positions['c' + str(cal[2].index(today) + 1)], dateicon)
            if today in cal[3]:
                draw(positions['d' + str(cal[3].index(today) + 1)], dateicon)
            if today in cal[4]:
                draw(positions['e' + str(cal[4].index(today) + 1)], dateicon)
            try:
                if today in cal[5]:
                    draw(positions['f' + str(cal[5].index(today) + 1)],
                         dateicon)
            except IndexError:
                pass

            draw(tempplace, tempicon)
            draw(humplace, humicon)

            print('\n' + 'initialising E-Paper Display')
            epd.init()
            sleep(5)
            print('Converting image to data and sending it to the display...' +
                  '\n')
            epd.display_frame(epd.get_frame_buffer(image))

            # delete the list so deleted events can be removed from the list
            del elist[:]
            print('data sent successfully' + '\n')
            print('letting the display sleep until the next hour')
            epd.sleep()

            for i in range(1):
                nexthour = ((60 - int(time.strftime("%-M"))) * 60) - (int(
                    time.strftime("%-S")))
                sleep(nexthour)
Ejemplo n.º 23
0

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-i",
                      "--image",
                      dest="image",
                      help="process image",
                      default="test_images/test1.jpg")
    parser.add_option("-v",
                      "--video",
                      dest="video",
                      help="process video",
                      default="")
    parser.add_option("-s",
                      "--show",
                      dest="show",
                      help="show every step image",
                      default=False)
    (options, args) = parser.parse_args()

    mtx, dist = calibration()

    if (not os.path.exists(options.image)):
        print(f"Input image \"{options.image}\" not exists")
    else:
        process_image(options.image, options.show)

    if (options.video):
        process_video(options.video, options.show)
Ejemplo n.º 24
0
def init_camera():
    global mtx, dist
    ret, mtx, dist, rvecs, tvecs = calibration(cal_chessboard_dir='camera_cal')
Ejemplo n.º 25
0
Archivo: Server.py Proyecto: isaxs/SAXS
 def start_image_queue(self,object,attachment):
     """
     prepare new image queue
     start processing threads
     """
     self.lasttime=time.time()
     self.lastcount=0
     self.history=history()
     self.attachments=[]
     for attachstr in attachment:
         self.attachments.append(json.loads(attachstr))
     self.calibration=object['argument']['calibration']
     print "abort old queue"
     if self.imagequeue:
          self.queue_abort()
     print "aborted old queue"
     try:
         if object['argument']['calibration'].get("Threads")>0:
             self.threads=object['argument']['calibration'].get("Threads")
         else:
             self.threads=self.options.threads
         o=atrdict.AttrDict({"plotwindow":False,"threads":self.threads,
                 		"watch":self.options.watchdir,
                         "watchdir":os.sep.join(object['argument']['calibration'].get("Directory")),
                         "servermode":True,
                         "silent":True,"plotwindow":False,
                         "walkdirinthreads":True,
                 		"outdir":self.options.outdir,
                         "relpath":self.options.relpath,
                 		 "writesvg":False,
                          "writepng":False,"resume":False,
                          "serverport":self.serverport
                          })
         cals=[]
         
         dir=os.path.normpath(
             os.path.join(
                          self.args[0],
                          os.sep.join(object['argument']['calibration'].get('Directory')
                         )))
         for mnumber,mask in enumerate(object['argument']['calibration']["Masks"]):
             cals.append(calibration.calibration(
                                         object['argument']['calibration'],
                                         mask,
                                         self.attachments[mnumber]))
         self.imagequeue=imagequeuelib.imagequeue(cals,
                 o,[ dir],self.serverconf)
         print "startimgq"
         self.imagequeueprocess=Process(target=self.imagequeue.start)
         self.imagequeueprocess.start()
         print "listening to feeder"
         serverdir=self.args[0]
         self.feederproc=Process(target=subscribeToFileChanges,args=
                                 (self.imagequeue,
                                  self.feederurl,
                                 dir,
                                 serverdir
                                 )
                                 )
         print "directory to watch "+dir
     
         self.feederproc.start()
         
         self.queuestatrtime=time.time()
         self.plotresult={"result":"Empty","data":{"stat":self.stat()}}
        
         result={"result":"new queue","data":{"cal":object['argument']['calibration']}}
     except IOError as e: 
         result={"result":"IOError","data":{"Error": str(e).replace("\n"," ")}}
     except ValueError as e:
         result={"result":"ValueError","data":{"Error": str(e)}}
     except Exception as e:
         result={"result":"Error","data":{"Error": str(e)}}
         print e
     return result
Ejemplo n.º 26
0
     GPIO.output(Status1, GPIO.LOW)
     GPIO.output(Status2, GPIO.LOW)            #Turn off LEDs before changing status
     GPIO.output(Status3, GPIO.LOW)
     GPIO.output(Status4, GPIO.LOW)
     GPIO.output(Status5, GPIO.LOW)
     state = buttonStatus(SButton,state)   #state 0=sleep, 2 = calibrate, 4 = search, 6 = position, 8=roast, 10 = return, 12=off, if button hit while sleep, will restart count and calibrate
 
 #time.sleep(1)
 if state ==2:
     GPIO.output(Status1, GPIO.HIGH)
     GPIO.output(Status2, GPIO.LOW)            #LEDs for states
     GPIO.output(Status3, GPIO.LOW)
     GPIO.output(Status4, GPIO.LOW)
     GPIO.output(Status5, GPIO.LOW)
 #    print "calibration begun"
     Cresult = calibration.calibration(state) # returns: 'state':state, 'maxVal1': noAverage1, 'maxVal2':noAverage2,'maxVal3': noAverage3,'minVal1': yesAverage1,'minVal2': yesAverage2,'minVal3': noAverage3
     state= Cresult['state']
     max1= Cresult['maxVal1']
     max2= Cresult['maxVal2']           #Collect average flame sensor readings for the particular environment
     max3= Cresult['maxVal3']
     minAll= Cresult['minVal']
     minTherm = Cresult['minTherm']
     
     time.sleep(1)
     
     #Search for flame until centered in front of robot
 if state == 4:
     GPIO.output(Status1, GPIO.LOW)
     GPIO.output(Status2, GPIO.HIGH)            #LEDs for states
     GPIO.output(Status3, GPIO.LOW)
     GPIO.output(Status4, GPIO.LOW)
Ejemplo n.º 27
0
 def start_image_queue(self,object,attachment):
     """
     prepare new image queue
     start processing threads
     """
     self.lasttime=time.time()
     self.lastcount=0
     self.history=history()
     self.attachments=[]        
     try:
         self._checkdirectorycollision(object['argument']['calibration']['Directory'])
         for attachstr in attachment:
             self.attachments.append(json.loads(attachstr))        
         self.calibration=object['argument']['calibration']
         if object['argument']['calibration'].get("Threads")>0:
             self.threads=object['argument']['calibration'].get("Threads")
         else:
             self.threads=self.options.threads
         self.threads=max(self.threads,2)
         print "abort old queue"
         if self.imagequeue:
              self.queue_abort()
         print "aborted old queue"
         
         o=atrdict.AttrDict({"plotwindow":False,"threads":self.threads,
                 		"watch":self.options.watchdir,
                         "watchdir":os.sep.join(object['argument']['calibration'].get("Directory")),
                         "servermode":True,
                         "silent":True,"plotwindow":False,
                         "walkdirinthreads":True,
                 		"outdir":self.options.outdir,
                         "relpath":self.options.relpath,
                 		"writesvg":False,
                         "writepng":False,"resume":False,
                         "serverport":self.serverport,
                         "nowalk":True,
                         "GISAXSmode":self.calibration["GISAXSmode"],
                         "livefilelist":"xxx",
                         "OverwriteFiles":False
                          })
         cals=[]
         
         dir=os.path.normpath(
             os.path.join(
                           self.serverdir,
                          os.sep.join(object['argument']['calibration'].get('Directory')
                         )))
         if "Masks" in object['argument']['calibration']:
             for mnumber,mask in enumerate(object['argument']['calibration']["Masks"]):
                 cals.append(calibration.calibration(
                                             object['argument']['calibration'],
                                             mask,
                                             self.attachments[mnumber]))
         if "Slices" in   object['argument']['calibration']:
             for slice in object['argument']['calibration']["Slices"]:
                 cals.append(GISAXSSlices.slice(object['argument']['calibration'],slice,self.attachments))
         
         if self.calibration["OverwriteFiles"]:
             o["OverwriteFiles"]=True
         
         '''Create empty file for filelisting'''
         filelist_path="xxx"
         if self.calibration["Live-Filelisting"]:
             filelist_path = os.path.join(os.path.split(dir)[0],"results")
             filelist_name = "filelist_" + os.path.split(dir)[1]+".log"
             filelist_path = os.path.join(filelist_path,filelist_name)
             try:
                 open(filelist_path, "w+").close()
                 o["livefilelist"]=filelist_path
             except:
                 print "Couldn't open " + filelist_path
             
         self.imagequeue=imagequeuelib.imagequeue(cals,
                 o,dir,self.serverconf)
         print "startimgq"
         self.imagequeueprocess=Process(target=self.imagequeue.start)
         self.imagequeueprocess.start()
         print "listening to feeder"
         serverdir= self.serverdir
         self.feederproc=Process(target=subscribeToFileChanges,args=
                                 (self.imagequeue,
                                  self.feederurl,
                                 dir,
                                 serverdir
                                 )
                                 )
         print "directory to watch "+dir
     
         self.feederproc.start()
         
         self.queuestatrtime=time.time()
         self.plotresult={"result":"Empty","data":{"stat":self.stat()}}
        
         result={"result":"new queue","data":{"cal":object['argument']['calibration']}}
     except IOError as e: 
         result={"result":"IOError","data":{"Error": str(e).replace("\n"," ")}}
     except ValueError as e:
         result={"result":"ValueError","data":{"Error": str(e)}}
     except Exception as e:
         result={"result":"Error","data":{"Error": str(e)}}
         print e
     return result
Ejemplo n.º 28
0
def saxsdogcal(options, args):   
    """
    Calculate computation matrices from calibration data
    """
    from calibration import calibration
    return calibration(options.calfilename) 
def main():
    while True:

        time = datetime.now()
        hour = int(time.strftime("%-H"))

        for i in range(1):
            if hour is 0:
                calibration()
            if hour is 12:
                calibration()
            if hour is 18:
                calibration()
            epd.init()
            image = Image.new('L', (EPD_WIDTH, EPD_HEIGHT), 255)
            draw = (ImageDraw.Draw(image)).bitmap

            #background image
            draw(monthplace,
                 Image.open(mpath + str(time.strftime("%B")) + '.bmp'))

            if calendar.firstweekday() == 0:
                #print('Your week starts on Monday') #->debug
                draw(weekplace, weekmon)

            if calendar.firstweekday() == 6:
                #print('Your week starts on Sunday') #->debug
                draw(weekplace, weeksun)

            draw(barplace, bar)

            cal = calendar.monthcalendar(time.year, time.month)

            for i in cal[0]:
                draw(positions['a' + str(cal[0].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[1]:
                draw(positions['b' + str(cal[1].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[2]:
                draw(positions['c' + str(cal[2].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[3]:
                draw(positions['d' + str(cal[3].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            for i in cal[4]:
                draw(positions['e' + str(cal[4].index(i) + 1)],
                     open(dpath + str(i) + '.bmp'))
            try:
                for i in cal[5]:
                    draw(positions['f' + str(cal[5].index(i) + 1)],
                         Image.open(dpath + str(i) + '.bmp'))
            except IndexError:
                pass

            # openweathermap api
            owm = pyowm.OWM(api_key)
            observation = owm.weather_at_place(location)
            weather = observation.get_weather()
            weathericon = weather.get_weather_icon_name()
            Temperature = str(
                int(weather.get_temperature(unit='celsius')['temp']))
            Humidity = str(weather.get_humidity())
            #print('temp: '+Temperature +'°C') #->debug
            #print('humidity: '+Humidity+'%') #->debug
            #print(weathericon)              #->debug

            #weather icon handler
            draw(wiconplace, open(wpath + weathericons[weathericon] + '.bmp'))

            # date writing function
            space1 = Image.new('1', (115, 25), color=255)
            measure1 = ImageDraw.Draw(space1)
            date = ImageDraw.Draw(space1)
            date.text((2, 3), (time.strftime('%a %-d %b %y')),
                      font=font,
                      fill=0)
            rotate1 = space1.rotate(270, expand=1)
            image.paste(rotate1, (595, 20))

            # temperature writing function
            space2 = Image.new('1', (50, 35), color=255)
            measure2 = ImageDraw.Draw(space2)
            temperature = ImageDraw.Draw(space2)
            temperature.text((2, 8), (Temperature + " °C"), fill=0, font=font)
            rotate2 = space2.rotate(270, expand=1)
            image.paste(rotate2, (605, 334))

            # humidity writing function
            space3 = Image.new('1', (50, 35), color=255)
            measure3 = ImageDraw.Draw(space3)
            humidity = ImageDraw.Draw(space3)
            humidity.text((4, 8), (Humidity + '%'), fill=0, font=font)
            rotate3 = space3.rotate(270, expand=1)
            image.paste(rotate3, (570, 334))

            # weekday handler
            if calendar.firstweekday() == 0:
                draw(weekdaysmon[(time.strftime("%a"))], weekday)

            if calendar.firstweekday() == 6:
                draw(weekdayssun[(time.strftime("%a"))], weekday)

            print('It is currently:', time.strftime('%a %-d %b %y'))  #--debug
            print('The current time is:', time.strftime('%H:%M'))  #--debug

            elist = []
            for events in c.events:
                if str(time.year) in str((events.begin).format('YYYY')):
                    if str(time.month) in str((events.begin).format('M')):
                        elist.append(int((events.begin).format('D')))

            print('In this month, you have', len(elist), 'Events')

            for x in elist:
                if x in cal[0]:
                    draw(positions['a' + str(cal[0].index(x) + 1)], eventicon)
                if x in cal[1]:
                    draw(positions['b' + str(cal[1].index(x) + 1)], eventicon)
                if x in cal[2]:
                    draw(positions['c' + str(cal[2].index(x) + 1)], eventicon)
                if x in cal[3]:
                    draw(positions['d' + str(cal[3].index(x) + 1)], eventicon)
                if x in cal[4]:
                    draw(positions['e' + str(cal[4].index(x) + 1)], eventicon)
                try:
                    if x in cal[5]:
                        draw(positions['f' + str(cal[5].index(x) + 1)],
                             eventicon)
                except IndexError:
                    pass

            today = time.day
            if today in cal[0]:
                draw(positions['a' + str(cal[0].index(today) + 1)], dateicon)
            if today in cal[1]:
                draw(positions['b' + str(cal[1].index(today) + 1)], dateicon)
            if today in cal[2]:
                draw(positions['c' + str(cal[2].index(today) + 1)], dateicon)
            if today in cal[3]:
                draw(positions['d' + str(cal[3].index(today) + 1)], dateicon)
            if today in cal[4]:
                draw(positions['e' + str(cal[4].index(today) + 1)], dateicon)
            try:
                if today in cal[5]:
                    draw(positions['f' + str(cal[5].index(today) + 1)],
                         dateicon)
            except IndexError:
                pass

            draw(tempplace, tempicon)
            draw(humplace, humicon)
            epd.display_frame(epd.get_frame_buffer(image))

            # delete the list so deleted events can be removed from the list
            del elist[:]
            epd.sleep()

            for i in range(1):
                nexthour = ((60 - int(time.strftime("%-M"))) * 60) - (int(
                    time.strftime("%-S")))
                sleep(nexthour)
Ejemplo n.º 30
0
from solving import solution_sudoku, afficher
from calibration import calibration

import cv2
import numpy as np
import time
import math
import picamera
from impl_pwm import *

TAILLE_IMAGE_GRILLE = 9 * 64

# Generation d'une matrice temporaire tant que calibration support pas effectuée
# MCalibPWM = np.float32([[1,0,0],[0,1,0],[0,0,1]])
# np.save('MCalibPWM.npy',MCalibPWM)
calibration()
MCalibPWM = np.load('MCalibPWM.npy')

camera = picamera.PiCamera()
camera.capture('1_initiale.jpg')
im = cv2.imread('1_initiale.jpg', 0)

img = cv2.warpPerspective(im, MCalibPWM, (1000, 665))

#img = cv2.imread('sudoku90.png',0)
listeGrilles, listeQuadris, listeCells, listeMOCR = FindGridsAndUnwarp(
    img, TAILLE_IMAGE_GRILLE)

for g in range(len(listeGrilles)):
    print('Traitement de la grille ' + str(g))
    cv2.imshow('grille', listeGrilles[g])
Ejemplo n.º 31
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct  3 16:59:59 2020

@author: khyeon
"""

import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from calibration import calibration, cal_undistort, unwarp
image = mpimg.imread('test_images/test1.jpg')
matrix, distortion = calibration()

sobel_x_thresh_min = 10
sobel_x_thresh_max = 100
sobel_y_thresh_min = 10
sobel_y_thresh_max = 100

mag_thresh_min = 10
mag_thresh_max = 15
dir_thresh_min = 0.7
dir_thresh_max = 1.3

H_thresh = (10, 100)
L_thresh = (0, 60)
S_thresh = (85, 255)
R_thresh = (200, 255)
Ejemplo n.º 32
0
def main():
    calibration_countdown = 'initial'
    while True:
        time = datetime.now()
        hour = int(time.strftime("%-H"))
        month = int(time.now().strftime('%-m'))
        year = int(time.now().strftime('%Y'))
        mins = int(time.strftime("%M"))
        seconds = int(time.strftime("%S"))

        for i in range(1):
            print('_________Starting new loop___________'+'\n')

            """Start by printing the date and time for easier debugging"""
            print('Date:', time.strftime('%a %-d %b %y'), 'Time: '+time.strftime('%H:%M')+'\n')

            """At the hours specified in the settings file,
            calibrate the display to prevent ghosting"""
            if hour in calibration_hours:
                if calibration_countdown is 'initial':
                    calibration_countdown = 0
                    calibration()
                else:
                    if calibration_countdown % (60 // int(update_interval)) is 0:
                        calibration()
                        calibration_countdown = 0

            """Create a blank white page first"""
            image = Image.new('RGB', (EPD_HEIGHT, EPD_WIDTH), 'white')

            """Add the icon with the current month's name"""
            image.paste(im_open(mpath+str(time.strftime("%B")+'.jpeg')), monthplace)

            """Add the line seperating the weather and Calendar section"""
            image.paste(seperator, seperatorplace)

            """Add weekday-icons (Mon, Tue...) and draw a circle on the
            current weekday"""
            if (week_starts_on is "Monday"):
                calendar.setfirstweekday(calendar.MONDAY)
                image.paste(weekmon, weekplace)
                image.paste(weekday, weekdaysmon[(time.strftime("%a"))], weekday)

            """For those whose week starts on Sunday, change accordingly"""
            if (week_starts_on is "Sunday"):
                calendar.setfirstweekday(calendar.SUNDAY)
                image.paste(weeksun, weekplace)
                image.paste(weekday, weekdayssun[(time.strftime("%a"))], weekday)

            """Using the built-in calendar function, draw icons for each
               number of the month (1,2,3,...28,29,30)"""
            cal = calendar.monthcalendar(time.year, time.month)

            for numbers in cal[0]:
                image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['a'+str(cal[0].index(numbers)+1)])
            for numbers in cal[1]:
                image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['b'+str(cal[1].index(numbers)+1)])
            for numbers in cal[2]:
                image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['c'+str(cal[2].index(numbers)+1)])
            for numbers in cal[3]:
                image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['d'+str(cal[3].index(numbers)+1)])
            for numbers in cal[4]:
                image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['e'+str(cal[4].index(numbers)+1)])
            if len(cal) is 6:
                for numbers in cal[5]:
                    image.paste(im_open(dpath+str(numbers)+'.jpeg'), positions['f'+str(cal[5].index(numbers)+1)])

            """Custom function to display text on the E-Paper.
            Tuple refers to the x and y coordinates of the E-Paper display,
            with (0, 0) being the top left corner of the display."""
            def write_text(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                if (text_width, text_height) > (box_width, box_height):
                    raise ValueError('Sorry, your text is too big for the box')
                else:
                    x = int((box_width / 2) - (text_width / 2))
                    y = int((box_height / 2) - (text_height / 2))
                    space = Image.new('RGB', (box_width, box_height), color='white')
                    ImageDraw.Draw(space).text((x, y), text, fill='black', font=font)
                    image.paste(space, tuple)

            """Connect to Openweathermap API to fetch weather data"""
            print("Connecting to Openweathermap API servers...")
            if owm.is_API_online() is True:
                observation = owm.weather_at_place(location)
                print("weather data:")
                weather = observation.get_weather()
                weathericon = weather.get_weather_icon_name()
                Humidity = str(weather.get_humidity())
                cloudstatus = str(weather.get_clouds())
                weather_description = (str(weather.get_status()))

                if units is "metric":
                    Temperature = str(int(weather.get_temperature(unit='celsius')['temp']))
                    windspeed = str(int(weather.get_wind()['speed']))
                    write_text(50, 35, Temperature + " °C", (334, 0))
                    write_text(100, 35, windspeed+" km/h", (114, 0))

                if units is "imperial":
                    Temperature = str(int(weather.get_temperature('fahrenheit')['temp']))
                    windspeed = str(int(weather.get_wind()['speed']*0.621))
                    write_text(50, 35, Temperature + " °F", (334, 0))
                    write_text(100, 35, windspeed+" mph", (114, 0))

                if hours is "24":
                    sunrisetime = str(datetime.fromtimestamp(int(weather.get_sunrise_time(timeformat='unix'))).strftime('%-H:%M'))
                    sunsettime = str(datetime.fromtimestamp(int(weather.get_sunset_time(timeformat='unix'))).strftime('%-H:%M'))

                if hours is "12":
                    sunrisetime = str(datetime.fromtimestamp(int(weather.get_sunrise_time(timeformat='unix'))).strftime('%-I:%M'))
                    sunsettime = str(datetime.fromtimestamp(int(weather.get_sunset_time(timeformat='unix'))).strftime('%-I:%M'))

                print('Temperature: '+Temperature+' °C')
                print('Humidity: '+Humidity+'%')
                #print('Icon code: '+weathericon)
                print('weather-icon name: '+weathericons[weathericon])
                print('Wind speed: '+windspeed+'km/h')
                print('Sunrise-time: '+sunrisetime)
                print('Sunset time: '+sunsettime)
                print('Cloudiness: ' + cloudstatus+'%')
                print('Weather description: '+weather_description+'\n')

                """Add the weather icon at the top left corner"""
                image.paste(im_open(wpath+weathericons[weathericon]+'.jpeg'), wiconplace)

                """Add the temperature icon at it's position"""
                image.paste(tempicon, tempplace)

                """Add the humidity icon and display the humidity"""
                image.paste(humicon, humplace)
                write_text(50, 35, Humidity + " %", (334, 35))

                """Add the sunrise icon and display the sunrise time"""
                image.paste(sunriseicon, sunriseplace)
                write_text(50, 35, sunrisetime, (249, 0))

                """Add the sunset icon and display the sunrise time"""
                image.paste(sunseticon, sunsetplace)
                write_text(50, 35, sunsettime, (249, 35))

                """Add the wind icon at it's position"""
                image.paste(windicon, windiconspace)

                """Add a short weather description"""
                write_text(144, 35, weather_description, (70, 35))

            else:
                """If no response was received from the openweathermap
                api server, add the cloud with question mark"""
                image.paste(no_response, wiconplace)

            """Algorithm for filtering and sorting events from your
            iCalendar/s"""
            print('Fetching events from your calendar'+'\n')
            events_this_month = []
            upcoming = []
            today = date.today()

            """Create a time span using the events_max_range value (in days)
            to filter events in that range"""
            time_span = today + timedelta(days=int(events_max_range))

            for icalendars in ical_urls:
                decode = str(urlopen(icalendars).read().decode())
                beginAlarmIndex = 0
                while beginAlarmIndex >= 0:
                    beginAlarmIndex = decode.find('BEGIN:VALARM')
                    if beginAlarmIndex >= 0:
                        endAlarmIndex = decode.find('END:VALARM')
                        decode = decode[:beginAlarmIndex] + decode[endAlarmIndex+12:]
                ical = Calendar(decode)
                for events in ical.events:
                   if re.search('RRULE',str(events)) is not None:
                           r = re.search('RRULE:(.+?)\n',str(events))
                           r_start = re.search('DTSTART:(.+?)\n',str(events))
                           if r_start is not None: # if r_start is None the format of DTSTART is not recognized
                               if time.now().month == 12:
                                   r_string=(r.group(1).rstrip()+';UNTIL='+'%04d%02d%02d'+'T000000Z') % (time.now().year+1, 1, 1)
                               else:
                                   r_string=(r.group(1).rstrip()+';UNTIL='+'%04d%02d%02d'+'T000000Z') % (time.now().year, time.now().month+1, 1)
                               rule=rrulestr(r_string,dtstart=parse(r_start.group(1)))
                               for i in rule:
                                   if i.year == time.now().year and i.month == time.now().month and i.day >= time.now().day:
                                       upcoming.append({'date':str(time.now().year) + " " + time.now().strftime('%m')+ " " + str(i.day).zfill(2), 'event':events.name})
                                       if i.day not in events_this_month:
                                          events_this_month.append(i.day)
                                   # uncomment this line to see fetched recurring events
                                   #print ("Appended recurring event: " + events.name + " on " + str(time.now().year) + " " + time.now().strftime('%m')+ " " + str(i.day).zfill(2))
                   else:
                       if events.begin.date().month == today.month:
                          if int((events.begin).format('D')) not in events_this_month:
                             events_this_month.append(int((events.begin).format('D')))
                       if today <= events.begin.date() <= time_span:
                          upcoming.append({'date':events.begin.format('YYYY MM DD'), 'event':events.name})


            def takeDate(elem):
                return elem['date']

            upcoming.sort(key=takeDate)

            #print('Upcoming events:',upcoming) #Display fetched events

            def write_text_left(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                while (text_width, text_height) > (box_width, box_height):
                    text=text[0:-1]
                    text_width, text_height = font.getsize(text)
                y = int((box_height / 2) - (text_height / 2))
                space = Image.new('RGB', (box_width, box_height), color='white')
                ImageDraw.Draw(space).text((0, y), text, fill='black', font=font)
                image.paste(space, tuple)

            """Write event dates and names on the E-Paper"""
            if additional_feature is "events":
                if len(cal) is 5:
                    del upcoming[6:]

                    for dates in range(len(upcoming)):
                        readable_date = datetime.strptime(upcoming[dates]['date'], '%Y %m %d').strftime('%-d %b')
                        write_text(70, 25, readable_date, date_positions['d'+str(dates+1)])
                    for events in range(len(upcoming)):
                        write_text_left(314, 25, (upcoming[events]['event']), event_positions['e'+str(events+1)])

                if len(cal) is 6:
                    del upcoming[4:]

                    for dates in range(len(upcoming)):
                        readable_date = datetime.strptime(upcoming[dates]['date'], '%Y %m %d').strftime('%-d %b')
                        write_text(70, 25, readable_date, date_positions['d'+str(dates+3)])
                    for events in range(len(upcoming)):
                        write_text_left(314, 25, (upcoming[events]['event']), event_positions['e'+str(events+3)])

            """Add rss-feeds at the bottom section of the Calendar"""
            if additional_feature is "rss":

                def multiline_text(text, max_width):
                    lines = []
                    if font.getsize(text)[0] <= max_width:
                        lines.append(text)
                    else:
                        words = text.split(' ')
                        i = 0
                        while i < len(words):
                            line = ''
                            while i < len(words) and font.getsize(line + words[i])[0] <= max_width:
                                line = line + words[i] + " "
                                i += 1
                            if not line:
                                line = words[i]
                                i += 1
                            lines.append(line)
                    return lines

                rss_feed = []
                for feeds in rss_feeds:
                    text = feedparser.parse(feeds)
                    for posts in text.entries:
                        rss_feed.append(posts.title)

                random.shuffle(rss_feed)
                news = []

                if len(cal) is 5:
                    del rss_feed[6:]

                if len(cal) is 6:
                    del rss_feed[4:]

                for title in range(len(rss_feeds)):
                    news.append(multiline_text(rss_feed[title], 384))

                news = [j for i in news for j in i]

                if len(cal) is 5:
                    if len(news) > 6:
                        del news[6:]
                    for lines in range(len(news)):
                        write_text_left(384, 25, news[lines], rss_places['line_'+str(lines+1)])

                if len(cal) is 6:
                    if len(news) > 4:
                        del news[4:]
                    for lines in range(len(news)):
                        write_text_left(384, 25, news[lines], rss_places['line_'+str(lines+3)])

            """Draw smaller squares on days with events"""
            for numbers in events_this_month:
                if numbers in cal[0]:
                    image.paste(eventicon, positions['a'+str(cal[0].index(numbers)+1)], eventicon)
                if numbers in cal[1]:
                    image.paste(eventicon, positions['b'+str(cal[1].index(numbers)+1)], eventicon)
                if numbers in cal[2]:
                    image.paste(eventicon, positions['c'+str(cal[2].index(numbers)+1)], eventicon)
                if numbers in cal[3]:
                    image.paste(eventicon, positions['d'+str(cal[3].index(numbers)+1)], eventicon)
                if numbers in cal[4]:
                    image.paste(eventicon, positions['e'+str(cal[4].index(numbers)+1)], eventicon)
                if len(cal) is 6:
                    if numbers in cal[5]:
                        image.paste(eventicon, positions['f'+str(cal[5].index(numbers)+1)], eventicon)

            """Draw a larger square on today's date"""
            today = time.day
            if today in cal[0]:
                image.paste(dateicon, positions['a'+str(cal[0].index(today)+1)], dateicon)
            if today in cal[1]:
                image.paste(dateicon, positions['b'+str(cal[1].index(today)+1)], dateicon)
            if today in cal[2]:
                image.paste(dateicon, positions['c'+str(cal[2].index(today)+1)], dateicon)
            if today in cal[3]:
                image.paste(dateicon, positions['d'+str(cal[3].index(today)+1)], dateicon)
            if today in cal[4]:
                image.paste(dateicon, positions['e'+str(cal[4].index(today)+1)], dateicon)
            if len(cal) is 6:
                if today in cal[5]:
                    image.paste(dateicon, positions['f'+str(cal[5].index(today)+1)], dateicon)

            """
            Map all pixels of the generated image to red, white and black
            so that the image can be displayed 'correctly' on the E-Paper
            """
            buffer = np.array(image)
            r,g,b = buffer[:,:,0], buffer[:,:,1], buffer[:,:,2]
            if display_colours is "bwr":
                buffer[np.logical_and(r > 240, g > 240)] = [255,255,255] #white
                buffer[np.logical_and(r > 240, g < 240)] = [255,0,0] #red
                buffer[np.logical_and(r != 255, r == g )] = [0,0,0] #black

            if display_colours is "bw":
                buffer[np.logical_and(r > 240, g > 240)] = [255,255,255] #white
                buffer[g < 255] = [0,0,0] #black
            
            improved_image = Image.fromarray(buffer).rotate(270, expand=True)
            print('Initialising E-Paper Display')
            epd.init()
            sleep(5)
            print('Converting image to data and sending it to the display')
            epd.display_frame(epd.get_frame_buffer(improved_image))
            print('Data sent successfully')
            print('______Powering off the E-Paper until the next loop______'+'\n')
            epd.sleep()

            del events_this_month
            del upcoming

            if additional_feature is "rss":
                del rss_feed
                del news

            del buffer
            del image
            del improved_image
            gc.collect()

            if calibration_countdown is 'initial':
                    calibration_countdown = 0
            calibration_countdown += 1

            for i in range(1):
                timings = []
                updates_per_hour = 60//int(update_interval)

                for updates in range(updates_per_hour):
                    timings.append(60 - int(update_interval)*updates)

                for update_times in timings:
                    if update_times >= mins:
                        sleep_for_minutes = update_times - mins
                
                next_update_countdown = sleep_for_minutes*60 + (60-seconds)

                print(sleep_for_minutes,'Minutes and ', (60-seconds),'Seconds left until next loop')

                del timings
                sleep(next_update_countdown)