예제 #1
0
    def emotiv(self):
        headset = Emotiv()
        gevent.spawn(headset.setup)
        print("Serial Number: %s" % headset.serial_number)

        self.num_blocks = len(self.content)
        cont_block = 0
        cont_seconds = 0
        temp_t = 0
        tag = self.content[0][1]
        #Se define el escritor de las lecturas en el archivo CSV
        writer = csv.writer(open(self.filename, 'w'),
                            delimiter=',',
                            quotechar='"',
                            lineterminator='\n')
        row = ["Image/Color"]
        row.append("Time")
        row.append("Exact Time")
        for sensor in self.sensors:
            row.append(sensor)
            row.append(sensor + "_Quality")
        row.append("Emotion")
        row.append("Selected Emotion")
        writer.writerow(row)
        try:
            t0 = time.time()
            tnow = time.time()
            while True:
                t = int(time.time() - t0)
                if temp_t != t:
                    cont_seconds += 1

                if cont_seconds > self.time_block:
                    cont_seconds = 0
                    cont_block += 1
                    if cont_block == self.num_blocks:
                        headset.close()
                        break
                    else:
                        tag = self.content[cont_block][1]
                        #display images
                        if cont_block >= self.contColors:
                            self.time_block = 5
                            self.panel1.configure(
                                image=self.images[cont_block -
                                                  self.contColors])
                            print "Display: " + str(cont_block -
                                                    self.contColors)
                            self.display = self.images[cont_block -
                                                       self.contColors]
                            self.panel1.pack(side=tk.TOP,
                                             fill=tk.BOTH,
                                             expand=tk.YES)
                        else:
                            color = Color(self.content[cont_block - 1][0])
                            colors = list(
                                color.range_to(
                                    Color(self.content[cont_block][0]),
                                    self.difColorSize))
                            now = time.time()
                            for color in colors:
                                self.root.configure(background=color)
                            #self.root.configure(background=self.content[cont_block][0])

                row = [self.content[cont_block][0]]
                row.append(str(t))
                row.append(time.time())
                try:
                    for sensor in self.sensors:
                        row.append(str(headset.sensors[sensor]['value']))
                        row.append(str(headset.sensors[sensor]['quality']))
                except:
                    print "Sensor incorrecto"
                    headset.close()
                row.append(tag)
                row.append(self.selectedEmotion)
                if self.selectedEmotion != '':
                    self.selectedEmotion = ''
                # Se exporta a csv
                writer.writerow(row)
                #print row
                temp_t = t
                gevent.sleep(0)
        except KeyboardInterrupt:
            headset.close()
        finally:
            headset.close()
예제 #2
0
        updated = False
        for packet in emotiv.dequeue():
            updated = True
            if abs(packet.gyroX) > 1:
                curX -= packet.gyroX - 1
            if abs(packet.gyroY) > 1:
                curY += packet.gyroY
            curX = max(0, min(curX, width))
            curY = max(0, min(curY, height))

        if updated:
            screen.move_mouse(curX, curY)
        time.sleep(1.0 / 60)


emotiv = None

try:
    logger = logging.getLogger('emotiv')
    logger.setLevel(logging.INFO)
    log_handler = logging.StreamHandler()
    logger.addHandler(log_handler)

    emotiv = Emotiv()

    main(*sys.argv[1:])

finally:
    if emotiv:
        emotiv.close()
예제 #3
0
def main():
    """
    Creates pygame window and graph drawing workers for each sensor.
    """
    global gheight
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    graphers = []
    recordings = []
    recording = False
    record_packets = []
    updated = False
    cursor_x, cursor_y = 400, 300
    for name in "AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4".split(" "):
        graphers.append(Grapher(screen, name, len(graphers)))
    fullscreen = False
    emotiv = Emotiv(display_output=True)
    gevent.spawn(emotiv.setup)
    gevent.sleep(0)
    while emotiv.running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                emotiv.close()
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    emotiv.close()
                    return
                elif event.key == pygame.K_f:
                    if fullscreen:
                        screen = pygame.display.set_mode((800, 600))
                        fullscreen = False
                    else:
                        screen = pygame.display.set_mode((800, 600), FULLSCREEN, 16)
                        fullscreen = True
                elif event.key == pygame.K_r:
                    if not recording:
                        record_packets = []
                        recording = True
                    else:
                        recording = False
                        recordings.append(list(record_packets))
                        record_packets = None
        packets_in_queue = 0
        try:
            while packets_in_queue < 8:
                packet = emotiv.dequeue()
                if abs(packet.gyro_x) > 1:
                    cursor_x = max(0, min(cursor_x, 800))
                    cursor_x -= packet.gyro_x
                if abs(packet.gyro_y) > 1:
                    cursor_y += packet.gyro_y
                    cursor_y = max(0, min(cursor_y, 600))
                map(lambda x: x.update(packet), graphers)
                if recording:
                    record_packets.append(packet)
                updated = True
                packets_in_queue += 1
        except Exception, ex:
            print ex

        if updated:
            screen.fill((75, 75, 75))
            map(lambda x: x.draw(), graphers)
            pygame.draw.rect(screen, (255, 255, 255), (cursor_x - 5, cursor_y - 5, 10, 10), 0)
            pygame.display.flip()
            updated = False
        gevent.sleep(0)
예제 #4
0
파일: gui.py 프로젝트: emotrix/Emotrix
    def emotiv(self):
        headset = Emotiv()
        gevent.spawn(headset.setup)
        print("Serial Number: %s" % headset.serial_number)

        self.num_blocks = len(self.content)
        cont_seconds = 0
        temp_t = 0
        tag = self.content[0][1]
        #Se define el escritor de las lecturas en el archivo CSV
        writer = csv.writer(open(self.filename, 'w'),
                            delimiter=',',
                            quotechar='"',
                            lineterminator='\n')
        row = ["Audio"]
        row.append("Time")
        row.append("Exact Time")
        for sensor in self.sensors:
            row.append(sensor)
            row.append(sensor + "_Quality")
        row.append("Emotion")
        row.append("Selected Emotion")
        writer.writerow(row)
        try:
            t0 = time.time()
            time_block = 300
            index_actual = 0
            while True:
                t = int(time.time() - t0)
                if temp_t != t:
                    cont_seconds += 1
                if cont_seconds >= time_block:
                    cont_seconds = 0
                    index_actual += 1
                    #self.player.next_source()
                if cont_seconds >= 300:
                    time_block = 15
                if t > 720:
                    headset.close()
                    self.player.pause()
                    break
                if t < 180:
                    tag = 'NON-RELAX'
                elif (t >= 180):
                    tag = self.emotions[index_actual]
                row = [self.content[index_actual][0].split('.')[0]]
                row.append(str(t))
                row.append(time.time())
                try:
                    for sensor in self.sensors:
                        row.append(str(headset.sensors[sensor]['value']))
                        row.append(str(headset.sensors[sensor]['quality']))
                except:
                    print "Sensor incorrecto"
                    headset.close()
                row.append(tag)
                row.append(self.selectedEmotion)
                if self.selectedEmotion != '':
                    self.selectedEmotion = ''
                # Se exporta a csv
                writer.writerow(row)
                #print row
                temp_t = t
                gevent.sleep(0)
        except KeyboardInterrupt:
            headset.close()
        finally:
            headset.close()
예제 #5
0
파일: render.py 프로젝트: AshBT/emokit
def main(debug=False):
    global gheight
    pygame.init()
    screen = pygame.display.set_mode((1600, 900))
    graphers = []
    recordings = []
    recording = False
    record_packets = []
    updated = False
    curX, curY = 400, 300

    for name in 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' '):
        graphers.append(Grapher(screen, name, len(graphers)))
    fullscreen = False
    emotiv = Emotiv(displayOutput=False)
    gevent.spawn(emotiv.setup)
    gevent.sleep(1)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                emotiv.close()
                return
            if (event.type == pygame.KEYDOWN):
                if (event.key == pygame.K_ESCAPE):
                    emotiv.close()
                    return
                elif (event.key == pygame.K_f):
                    if fullscreen:
                        screen = pygame.display.set_mode((1600, 900))
                        fullscreen = False
                    else:
                        screen = pygame.display.set_mode((1600,900), FULLSCREEN, 16)
                        fullscreen = True
                elif (event.key == pygame.K_r):
                    if not recording:
                        record_packets = []
                        recording = True
                    else:
                        recording = False
                        recordings.append(list(record_packets))
                        record_packets = None
        packetsInQueue = 0
        try:
            while packetsInQueue < 8:
                packet = emotiv.dequeue()
                if abs(packet.gyroX) > 1:
                    curX = max(0, min(curX, 1600))
                    curX -= packet.gyroX
                if abs(packet.gyroY) > 1:
                    curY += packet.gyroY
                    curY = max(0, min(curY, 900))
                map(lambda x: x.update(packet), graphers)
                if recording:
                    record_packets.append(packet)
                updated = True
                packetsInQueue += 1
        except Exception, e:
            print e

        if updated:
            screen.fill((75, 75, 75))
            map(lambda x: x.draw(), graphers)
            pygame.draw.rect(screen, (255, 255, 255), (curX - 5, curY - 5, 10, 10), 0)
            pygame.display.flip()
            updated = False
        gevent.sleep(0)
예제 #6
0
        curX, curY = width / 2, height / 2
        while True:
            updated = False
            packet = emotiv.dequeue()
            if abs(packet.gyroX) > 1:
                curX -= packet.gyroX
                updated = True
            if abs(packet.gyroY) > 1:
                curY += packet.gyroY
                updated = True
            curX = max(0, min(curX, width))
            curY = max(0, min(curY, height))
            if updated:
                screen.move_mouse(curX, curY)
            gevent.sleep(0)


emotiv = None
if __name__ == "__main__":
    try:
        emotiv = Emotiv()
        gevent.spawn(emotiv.setup)
        gevent.sleep(1)
        main(*sys.argv[1:])

    finally:
        if emotiv:
            emotiv.close()


예제 #7
0
파일: render.py 프로젝트: acm-uiuc/emokit
def main(outfile='eegout.csv', debug=False):
    global gheight
    pygame.init()
    screen = pygame.display.set_mode((800, 450))
    graphers = []
    recordings = []
    recording = False
    record_packets = []
    updated = False
    curX, curY = 400, 300
    pause = False

    features = 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' ')

    for name in features:
        graphers.append(Grapher(screen, name, len(graphers)))
    fullscreen = False
    emotiv = Emotiv(displayOutput=False)
    gevent.spawn(emotiv.setup)
    gevent.sleep(1)

    labels = 'down up'.split(' ')
    classifier = RandomizedTrees(labels)
    testsize = 0
    train = 0

    csvfile = open(outfile, 'wb')
    csvwriter = csv.writer(csvfile, delimiter = ',')
    # first row = attribute names
    csvwriter.writerow(features);

    # for displaying testing instructions
    font = pygame.font.Font(None, 36)
    text = 'next: ' + labels[train / 2]

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                emotiv.close()
                return
            if (event.type == pygame.KEYDOWN):
                if (event.key == pygame.K_ESCAPE):
                    emotiv.close()
                    return
                elif (event.key == pygame.K_f):
                    if fullscreen:
                        screen = pygame.display.set_mode((800, 450))
                        fullscreen = False
                    else:
                        # Don't actually do full-screen. You might be unable to
                        # undo...
                        screen = pygame.display.set_mode((1600,900))
                        fullscreen = True
                elif (event.key == pygame.K_r):
                    if not recording:
                        record_packets = []
                        recording = True
                    else:
                        recording = False
                        recordings.append(list(record_packets))
                        record_packets = None
                elif (event.key == pygame.K_RETURN):
                    train = train + 1
                    # print the next concept to train
                    if train < 2 * len(labels):
                      if train % 2 == 0:
                        text = 'next: ' + labels[train / 2]
                      else:
                        text = 'current: ' + labels[train / 2]
                    else:
                        text = ''
                elif (event.key == pygame.K_p):
                  pause = not pause
                  
        packetsInQueue = 0
        try:
            while packetsInQueue < 8:
                packet = emotiv.dequeue()

                # update cursor position based on gyros
#                if abs(packet.gyroX) > 1:
#                    curX = max(0, min(curX, 1600))
#                    curX -= packet.gyroX
#                if abs(packet.gyroY) > 1:
#                    curY += packet.gyroY
#                    curY = max(0, min(curY, 900))
                
                sensors = packet.sensors
                csvrow = []
                for i in range(len(features)):
                  csvrow.append(sensors[features[i]]['value'])
                print csvrow
                csvwriter.writerow(csvrow);

                if train == 0:
                  print 'doing nothing'

                elif train < 2 * len(labels):
                  if train % 2 == 1:
                    classifier.AddTrainExample(csvrow, labels[train / 2])
                    testsize = testsize + 1
                    print labels[train / 2]

                elif train == 2 * len(labels):
                  classifier.Train()
                  train = train + 1

                else:
                  (label, score) = classifier.Classify(csvrow)
                  print "label:"
                  print label
                  print "classification score:"
                  print score
                  # Update cursor (top left if (0, 0)):
                  #   Suggested pairings:
                  #   right hand up = right
                  #   left hand up = left
                  #   both hands up = up
                  #   rest up = down
                  if pause == False:
                    if label == 'right':
                      curX += 1
                      x, y = screen.get_size()
                      if curX > x:
                        curX = x
                    elif label == 'left':
                      curX -= 1
                      if curX < 0:
                        curX = 0
                    elif label == 'down':
                      curY += 1
                      x, y = screen.get_size()
                      if curY > y:
                        curY = y
                    elif label == 'up':
                      curY -= 1
                      if curY < 0:
                        curY = 0


                map(lambda x: x.update(packet), graphers)
                if recording:
                    record_packets.append(packet)
                updated = True
                packetsInQueue += 1
        except Exception, e:
            print e

        if updated:
            screen.fill((75, 75, 75))
            map(lambda x: x.draw(), graphers)
            pygame.draw.rect(screen, (255, 255, 255), (curX - 5, curY - 5, 10, 10), 0)  
            # r for 'to render'
            rtext = font.render(text, 1, (0, 255, 0))
            screen.blit(rtext, (0, 0))
            pygame.display.flip()
            updated = False
        gevent.sleep(0)
예제 #8
0
    def start(self, sequence=None, time_block=7, filename='data.csv'):
        self.time_block = time_block
        self.filename = filename
        #Se define el objeto EMOTIV, utilizando la libreria EMOKIT
        headset = Emotiv()
        gevent.spawn(headset.setup)
        gevent.sleep(0)
        print("Serial Number: %s" % headset.serial_number)

        if sequence is not None:
            self.sequence = sequence
            self.num_blocks = len(self.sequence)
        i = 0
        cont_block = 0
        cont_seconds = 0
        temp_t = 0
        tag = self.sequence[0]

        #Se define el escritor de las lecturas en el archivo CSV
        writer = csv.writer(open(self.filename, 'w'),
                            delimiter='\t',
                            quotechar='"')
        try:
            t0 = time.time()
            while True:
                t = int(time.time() - t0)
                #t = int(time.time())
                if temp_t != t:
                    cont_seconds += 1

                if cont_seconds > self.time_block:
                    cont_seconds = 0
                    cont_block += 1
                    if cont_block == self.num_blocks:
                        headset.close()
                        break
                    else:
                        tag = self.sequence[cont_block]

                # Se obtiene el paquete de datos, utilizando EMOKIT
                packet = headset.dequeue()
                #print packet.sensors
                # Se construye la informacion a guardar
                row = [
                    str(t), "F3:" + str(packet.sensors['F3']['quality']) +
                    "," + str(packet.sensors['F3']['value']),
                    "F4:" + str(packet.sensors['F4']['quality']) + "," +
                    str(packet.sensors['F4']['value']),
                    "AF3:" + str(packet.sensors['AF3']['quality']) + "," +
                    str(packet.sensors['AF3']['value']),
                    "AF4:" + str(packet.sensors['AF4']['quality']) + "," +
                    str(packet.sensors['AF4']['value']),
                    "O1:" + str(packet.sensors['O1']['quality']) + "," +
                    str(packet.sensors['O1']['value']),
                    "O2:" + str(packet.sensors['O2']['quality']) + "," +
                    str(packet.sensors['O2']['value']), tag
                ]
                # Se exporta a csv
                writer.writerow(row)
                print row
                temp_t = t
                gevent.sleep(0)
        except KeyboardInterrupt:
            headset.close()
        finally:
            headset.close()
        i += 1
예제 #9
0
                    dataP2[head] = packet.sensors['P8']['value']
                    head = (head + 1) % fsa
                    tail = (head + 1) % fsa
                    count = 0 
                    #print packet.battery

                    while tail != head :
                        # print "@"
                        data2P1[count] = dataP1[tail-1]
                        data2O1[count] = dataO1[tail-1]
                        data2O2[count] = dataO2[tail-1]
                        data2P2[count] = dataP2[tail-1]
                        tail = (tail + 1)%fsa
                        count = count + 1
                    data2P1[count] = dataP1[(tail-1)]#%fsa]
                    data2O1[count] = dataO1[(tail-1)]
                    data2O2[count] = dataO2[(tail-1)]
                    data2P2[count] = dataP2[(tail-1)] 

        #print "#print "6"
        RunMain.get()
        RunMain.close()        

    except KeyboardInterrupt:
        headset.close()
        #os.system('clear')
    finally:
        headset.close()
        #os.system('clear')
    
예제 #10
0
    def start(self, sequence=None, sensors=None, time_block=7):
        self.time_block = time_block
        #Se define el objeto EMOTIV, utilizando la libreria EMOKIT
        headset = Emotiv()
        gevent.spawn(headset.setup)

        print("Serial Number: %s" % headset.serial_number)

        if sequence is not None:
            self.sequence = sequence
            self.num_blocks = len(self.sequence)
        i = 0
        cont_block = 0
        cont_seconds = 0
        temp_t = 0
        tag = self.sequence[0]

        #Se define el escritor de las lecturas en el archivo CSV
        # writer = csv.writer(open(self.filename, 'w'), delimiter=',', quotechar='"', lineterminator='\n') #windows
        writer = csv.writer(open(self.filename, 'w'),
                            delimiter=',',
                            quotechar='"')  #linux
        try:
            row = ["Time"]
            for sensor in sensors:
                row.append(sensor)
                row.append(sensor + "_Quality")
            row.append("Tag")

            writer.writerow(row)

            t0 = time.time()
            while True:
                t = int(time.time() - t0)

                if temp_t != t:
                    cont_seconds += 1

                if cont_seconds > self.time_block:
                    cont_seconds = 0
                    cont_block += 1
                    if cont_block == self.num_blocks:
                        headset.close()
                        break
                    else:
                        tag = self.sequence[cont_block]

                # Se construye la informacion a guardar
                row = [str(t)]
                try:
                    for sensor in sensors:
                        row.append(str(headset.sensors[sensor]['value']))
                        row.append(str(headset.sensors[sensor]['quality']))

                except:
                    print "Sensor incorrecto"
                    headset.close()
                row.append(tag)

                # Se exporta a csv
                writer.writerow(row)
                print row
                temp_t = t
                gevent.sleep(0)
        except KeyboardInterrupt:
            headset.close()
        finally:
            headset.close()
        i += 1
예제 #11
0
def main(debug=False):
    global gheight
    pygame.init()
    screen = pygame.display.set_mode((1600, 900))
    graphers = []
    recordings = []
    recording = False
    record_packets = []
    updated = False
    curX, curY = 400, 300

    for name in 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' '):
        graphers.append(Grapher(screen, name, len(graphers)))
    fullscreen = False
    emotiv = Emotiv(displayOutput=False)
    gevent.spawn(emotiv.setup)
    gevent.sleep(1)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                emotiv.close()
                return
            if (event.type == pygame.KEYDOWN):
                if (event.key == pygame.K_ESCAPE):
                    emotiv.close()
                    return
                elif (event.key == pygame.K_f):
                    if fullscreen:
                        screen = pygame.display.set_mode((1600, 900))
                        fullscreen = False
                    else:
                        screen = pygame.display.set_mode((1600, 900),
                                                         FULLSCREEN, 16)
                        fullscreen = True
                elif (event.key == pygame.K_r):
                    if not recording:
                        record_packets = []
                        recording = True
                    else:
                        recording = False
                        recordings.append(list(record_packets))
                        record_packets = None
        packetsInQueue = 0
        try:
            while packetsInQueue < 8:
                packet = emotiv.dequeue()
                if abs(packet.gyroX) > 1:
                    curX = max(0, min(curX, 1600))
                    curX -= packet.gyroX
                if abs(packet.gyroY) > 1:
                    curY += packet.gyroY
                    curY = max(0, min(curY, 900))
                map(lambda x: x.update(packet), graphers)
                if recording:
                    record_packets.append(packet)
                updated = True
                packetsInQueue += 1
        except Exception, e:
            print e

        if updated:
            screen.fill((75, 75, 75))
            map(lambda x: x.draw(), graphers)
            pygame.draw.rect(screen, (255, 255, 255),
                             (curX - 5, curY - 5, 10, 10), 0)
            pygame.display.flip()
            updated = False
        gevent.sleep(0)
예제 #12
0
def main():
    """
    Creates pygame window and graph drawing workers for each sensor.
    """
    global gheight
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    graphers = []
    recordings = []
    recording = False
    record_packets = []
    updated = False
    cursor_x, cursor_y = 400, 300
    for name in 'AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4'.split(' '):
        graphers.append(Grapher(screen, name, len(graphers)))
    fullscreen = False
    emotiv = Emotiv(display_output=True)
    gevent.spawn(emotiv.setup)
    gevent.sleep(0)
    while emotiv.running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                emotiv.close()
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    emotiv.close()
                    return
                elif event.key == pygame.K_f:
                    if fullscreen:
                        screen = pygame.display.set_mode((800, 600))
                        fullscreen = False
                    else:
                        screen = pygame.display.set_mode((800, 600),
                                                         FULLSCREEN, 16)
                        fullscreen = True
                elif event.key == pygame.K_r:
                    if not recording:
                        record_packets = []
                        recording = True
                    else:
                        recording = False
                        recordings.append(list(record_packets))
                        record_packets = None
        packets_in_queue = 0
        try:
            while packets_in_queue < 8:
                packet = emotiv.dequeue()
                if abs(packet.gyro_x) > 1:
                    cursor_x = max(0, min(cursor_x, 800))
                    cursor_x -= packet.gyro_x
                if abs(packet.gyro_y) > 1:
                    cursor_y += packet.gyro_y
                    cursor_y = max(0, min(cursor_y, 600))
                map(lambda x: x.update(packet), graphers)
                if recording:
                    record_packets.append(packet)
                updated = True
                packets_in_queue += 1
        except Exception, ex:
            print ex

        if updated:
            screen.fill((75, 75, 75))
            map(lambda x: x.draw(), graphers)
            pygame.draw.rect(screen, (255, 255, 255),
                             (cursor_x - 5, cursor_y - 5, 10, 10), 0)
            pygame.display.flip()
            updated = False
        gevent.sleep(0)