def main():
    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker(
    ).ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================

    # Parce command line inputs, if any
    filename = 'emg'
    acquisition_len = 10
    if len(sys.argv) > 1:
        acquisition_len = int(sys.argv[1])
    if len(sys.argv) > 2:
        filename = sys.argv[2]

    listener = Collector(acquisition_len * EMG_SAMPLING_RATE)

    print('\rStarted recording EMG for', str(acquisition_len),
          'seconds. Cancel with ctrl-c.')

    with hub.run_in_background(listener.on_event):
        while hub.running:
            time.sleep(0.5)
            print('\rRecording ... %d percent done.' %
                  (100 * listener.emg_data.shape[0] / acquisition_len /
                   EMG_SAMPLING_RATE),
                  end='')
        print()

    with open(filename + '.csv', 'w') as csvfile:
        for row in listener.emg_data:
            csvfile.write(', '.join(map(str, list(row))) + '\n')
Beispiel #2
0
def main():
    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker(
    ).ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================

    # Parce command line inputs, if any. When running this script from command line,
    # you can specify the target data folder:
    # python scriptname.py foldername
    if len(sys.argv) > 1:
        data_folder = sys.argv[1]
    else:
        data_folder = 'data'

    # Setup classification problem and training dataset parameters
    gestures = collections.OrderedDict()
    gestures = ['fist', 'radial', 'ulnar', 'extension', 'flextion',
                'rest']  #, 'pron', 'supi'] # Classes to acquire data for
    trials_n = 3  # Number of trials for each class
    trial_len = 5  # Duration of each trial in seconds

    print('Starting the EMG data collection ... Press ctrl-c to stop.')
    # Get to the dataset folder, if doesn't exist, create it:
    if not os.path.exists(data_folder): os.mkdir(data_folder)
    os.chdir(data_folder)
    # EMG data is acquired in the following order:
    # Class1-Trial1, Class2-Trial1 ... ClassN_Trial1,
    # Class2_Trial2, Class2-Trial2 ... ... ClassN_TrialM.
    for trial in range(1, trials_n + 1):
        for gesture in gestures:
            # For each class, enter or create a specific folder that contains all of its trials:
            if not os.path.exists(gesture): os.mkdir(gesture)
            os.chdir(gesture)
            # Check if such trial for this class was already recorded (useful when continuing an interrupted acquisition)
            if os.path.exists(str(trial) + '.csv'):
                print(
                    'Trial', str(trial),
                    'of class %s already exists, moving forward ...' %
                    gesture.upper())
            else:
                # Make new acquisition:
                emg_data = make_single_acquisition(
                    trial_len,
                    'Start performing %s gesture.' % gesture.upper())
                # ... and save it as Comma-Separated Values (CSV):
                with open(str(trial) + '.csv', 'w') as csvfile:
                    for row in emg_data:
                        csvfile.write(', '.join(map(str, list(row))) + '\n')
            os.chdir('..')

        print('Data acquistion accomplished, signals are saved in',
              data_folder, 'folder.')
    os.chdir('..')
Beispiel #3
0
def main():
    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk') # Compile Python binding to Myo's API
    hub = myo.Hub() # Create a Python instance of MYO API
    if not ConnectionChecker().ok: # Check connection before starting acquisition:
        quit()
    # =========================================================================


    # Setup our custom processor of MYO's events.
    # EmgBuffer will acquire new data in a buffer (queue):
    listener = Buffer(buffer_len = 512) # At sampling rate of 200Hz, 512 samples correspond to ~2.5 seconds of the most recent data.

    # Setup multichannel plotter for visualisation:
    plotter = MultichannelPlot(nchan = 8, xlen = 512) # Number of EMG channels in MYO armband is 8
    #plotter2 = MultichannelPlot(nchan = 8, xlen = 512) 
    N1 = 0
    q = 0
    j = 0
    # Tell MYO API to start a parallel thread that will collect the data and
    # command the MYO to start sending EMG data.
    with hub.run_in_background(listener): # This is the way to associate our listener with the MYO API.
        print('Streaming EMG ... Press shift-c to stop.')
        while hub.running:
            time.sleep(0.040)
            # Pull recent EMG data from the buffer
            emg_data = listener.get_emg_data()
            # Transform it to numpy matrix
            emg_data = np.array([x[1] for x in emg_data])
            
            # q = q+1
            # if q >= 100: 
                # q = 0
                # N = 0
                # for i in range(1,len(emg_data)):
                    # N[j] = N[j] + emg_data[i]                
                # N1[j] = N[j]/(len(emg_data))
                # j = j+1
                # print('\rRecording ... %d percent done.' % N[j], end='\n')  
                
                
            # Plot it
            plotter.update_plot(emg_data.T)
            
            # Plot Moving Mean Average Value
            
            #plotter2.update_plot(N1,j)
            plt.plot(N1,j, color="r", linestyle="-", linewidth=1)
            plt.show()
   
            
            if keyboard.is_pressed('C'):
                print('Stop.')
                break
def main():
    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker(
    ).ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================
    # calculate the Mean Absolute Value
    # Setup our custom processor of MYO's events.
    # EmgBuffer will acquire new data in a buffer (queue):
    listener = Buffer(
        buffer_len=512
    )  # At sampling rate of 200Hz, 512 samples correspond to ~2.5 seconds of the most recent data.

    # Setup multichannel plotter for visualisation:
    plotter = MultichannelPlot(
        nchan=8, xlen=512)  # Number of EMG channels in MYO armband is 8

    # Tell MYO API to start a parallel thread that will collect the data and
    # command the MYO to start sending EMG data.
    with hub.run_in_background(
            listener
    ):  # This is the way to associate our listener with the MYO API.
        print('Streaming EMG ... Press shift-c to stop.')
        while hub.running:
            time.sleep(0.040)
            # Pull recent EMG data from the buffer
            emg_data = listener.get_emg_data()
            # Transform it to numpy matrix
            emg_data = np.array([x[1] for x in emg_data])

            data = []
            mav_data = []

            for i in range(502):
                data = emg_data[i:i + 10, :]
                mav_data[i, :] = MAV(data)
            #
            #data.append(emg_data)
            #data = np.array(data)
            # if (data.shape[1]==512):
            # mav_data = MAV(data)  # 1x8
            # data = np.delete(data, [0], axis=0)

            # Plot it
            #plotter.update_plot(emg_data.T)
            plotter.update_plot(np.array(mav_data).T)
            if keyboard.is_pressed('C'):
                print('Stop.')
                break
Beispiel #5
0
def main():

    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker(
    ).ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================

    # Parce command line inputs, if any
    input_file = 'models/trained_model.pkl'
    if len(sys.argv) > 1:
        input_file = sys.argv[1]

    # Load pickled feature extractor and classification model
    with open(input_file, 'rb') as file:
        model = pickle.load(file)

    # Extract variables from pickled object
    mdl = model['mdl']
    feature_extractor = model['feature_extractor']
    gestures = model['gestures']

    # Set up the buffer that will always contain the most up-to-date readings from the MYO
    emg_buffer = Buffer(feature_extractor.winlen)

    # Set up inference
    with hub.run_in_background(emg_buffer.on_event):
        print('You may start performing gestures. Press ctrl-c to stop.')
        while hub.running:
            time.sleep(0.050)
            # Skip the rest until enough data for feature extraction is acquired
            if len(emg_buffer.emg_data_queue) < feature_extractor.winlen:
                continue

            # Get latest emg data
            emg = emg_buffer.get_emg_data()
            # Convert to a numpy matrix (an Nx8 matrix, each channel is a column):
            emg = np.array([x[1] for x in emg])
            # Extract features from the emg signal:
            feature_vector = feature_extractor.extract_feature_vector(emg)
            # Use classification model to recognise the gesture:
            inference = mdl.predict(feature_vector)
            # Implement majority voting here, if needed:
            # ...

            # Output inference:
            print('\rRecognized gesture: ', gestures[inference[0]], end='')
Beispiel #6
0
def main():
    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker(
    ).ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================
    # calculate the Mean Absolute Value
    # Setup our custom processor of MYO's events.
    # EmgBuffer will acquire new data in a buffer (queue):
    listener = Buffer(
        buffer_len=512
    )  # At sampling rate of 200Hz, 512 samples correspond to ~2.5 seconds of the most recent data.
    calculate = Feature(input_len=512)
    # Setup multichannel plotter for visualisation:
    plotter = MultichannelPlot(
        nchan=8, xlen=512
    )  # Number of EMG channels in MYO armband is 8 , window size is 15 for MAV
    freq = 200
    move = cursor(freq)

    # Tell MYO API to start a parallel thread that will collect the data and
    # command the MYO to start sending EMG data.
    with hub.run_in_background(
            listener
    ):  # This is the way to associate our listener with the MYO API.
        print('Streaming EMG ... Press shift-c to stop.')
        while hub.running:
            time.sleep(0.040)
            # Pull recent EMG data from the buffer
            emg_data = listener.get_emg_data()
            # Transform it to numpy matrix
            emg_data = np.array([x[1] for x in emg_data])

            # avoid len() report error
            if (emg_data.ndim == 2):
                if (emg_data.shape[0] == 512):
                    # calculate MAV of emg data
                    mav_data = calculate.MAV(emg_data)
                    mav_data = np.array(mav_data.T)

                    plotter.update_plot(mav_data)

                    move.move_cursor(mav_data)

            if keyboard.is_pressed('C'):
                print('Stop.')
                break
Beispiel #7
0
import myo
import time, keyboard
import numpy as np
from TwoChannelMyocontrol import TwoChannelMyoControl
from myo_ecn.listeners import Buffer, ConnectionChecker

from Alpes.Prosthesis import AlpesProsthesis, GRASPS

# ================== setup myo-python (do not change) =====================
myo.init(sdk_path='../../myo_sdk')  # Compile Python binding to Myo's API
hub = myo.Hub()  # Create a Python instance of MYO API
if not ConnectionChecker().ok:  # Check connection before starting acquisition:
    quit()
# =========================================================================

EMG_SAMPLING_RATE = 200
winsec = 0.1  # Window duration in seconds
winlen = int(winsec * EMG_SAMPLING_RATE)  # Window length in samples
extensors_chan = 3
flexors_chan = 0
listener = Buffer(buffer_len=winlen)

mc = TwoChannelMyoControl(
    # Absolute values of EMG are spanned between 0 and 127.
    # thresholds are approximately measure as percentage of total muscle contraction.
    # thresholds[0] corresponds to flexors, thresholds[1] correspons to extensors.
    thresholds=[10, 15],
    # cc_lock_duration filters out some unwanted control decisions after a co-contraction.
    # cc_lock_duration is measured in number of 'winlen's (see variable above).
    # Increase cc_lock_duration if unwanted motions appear after co-contraction or if
    # co-contraction gets detected twice instead of once in a short amount of time.
Beispiel #8
0
def keyboard():

    # ================== setup myo-python (do not change) =====================
    myo.init(sdk_path="../../myo_sdk")  # Compile Python binding to Myo's API
    hub = myo.Hub()  # Create a Python instance of MYO API
    if not ConnectionChecker().ok:  # Check connection before starting acquisition:
        quit()
    # =========================================================================

    # Parce command line inputs, if any
    input_file = "../classification/models/trained_model.pkl"
    if len(sys.argv) > 1:
        input_file = sys.argv[1]

    # Load pickled feature extractor and classification model
    with open(input_file, "rb") as file:
        model = pickle.load(file)

    # Extract variables from pickled object
    mdl = model["mdl"]
    feature_extractor = model["feature_extractor"]
    gestures = model["gestures"]

    # Set up the buffer that will always contain the most up-to-date readings from the MYO
    emg_buffer = Buffer(feature_extractor.winlen)

    # Set up inference
    with hub.run_in_background(emg_buffer.on_event):
        print("You may start performing gestures. Press ctrl-c to stop.")
        while hub.running:
            time.sleep(0.050)
            # Skip the rest until enough data for feature extraction is acquired
            if len(emg_buffer.emg_data_queue) < feature_extractor.winlen:
                continue

            # Get latest emg data
            emg = emg_buffer.get_emg_data()
            # Convert to a numpy matrix (an Nx8 matrix, each channel is a column):
            emg = np.array([x[1] for x in emg])
            # Extract features from the emg signal:
            feature_vector = feature_extractor.extract_feature_vector(emg)
            # Use classification model to recognise the gesture:
            inference = mdl.predict(feature_vector)
            # Implement majority voting here, if needed:
            # ...
            # Output inference:
            print("\rRecognized gesture: ", gestures[inference[0]], end="")
            gesture = gestures[inference[0]]
            
            if gesture == 'rest':
                continue
                #pyautogui.press('w')
            elif gesture == 'radial':
                pyautogui.keyDown('a')
            elif gesture == 'ulnar':
                pyautogui.keyDown('d')
            elif gesture == 'flextion':
                pyautogui.keyDown('w')
            elif gesture == 'extension':
                pyautogui.keyDown('s')
            elif gesture == 'fist':
                pyautogui.keyDown('space')