Ejemplo n.º 1
0
def getColors():
    with open('colors.txt') as f:
          colors = f.readlines()
    colors = [[int(x) for x in c[:-1].split(',')] for c in colors]
    #code.interact(local=locals())
    Qcolors = [QtGui.qRgb(c[0], c[1], c[2]) for c in colors]
    return Qcolors
Ejemplo n.º 2
0
Archivo: main.py Proyecto: wsonv/Wonjun
    def __init__(self, parent=None):

        from pyqtgraph import exporters
        exporters.Exporter.register = self.modified_register

        QtGui.QMainWindow.__init__(self, parent)

        self.setWindowIcon(QtGui.QIcon(logo))
        self.setWindowTitle('CIVET')

        self.setGeometry(200, 143, 1574, 740)
        pg.setConfigOption('background', QtGui.QColor(215, 214, 213, 255))
        pg.setConfigOption('foreground', 'k')
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background,
                         QtGui.QColor(215, 214, 213, 255))
        self.setPalette(palette)

        self.mainframe = QtGui.QFrame()

        self.copen = 0
        self.sopen = 0
        self.ropen = 0
        self.gridstate = 0
        self.current_docks = []

        self.loadaction = QtGui.QAction("&Open", self)
        self.loadaction.setShortcut("Ctrl+O")
        self.loadaction.setStatusTip("Open File")
        self.loadaction.triggered.connect(self.loaddata)

        self.exportaction = QtGui.QAction("&Export", self)
        self.exportaction.setShortcut("Ctrl+E")
        self.exportaction.setStatusTip("Export to a folder")
        self.exportaction.triggered.connect(self.exportdata)

        self.viewaction1 = QtGui.QAction("&Grid View 1", self)
        self.viewaction1.setStatusTip("Grid View 1")
        self.viewaction1.triggered.connect(self.grid_view_1)

        self.viewaction2 = QtGui.QAction("&Grid View 2", self)
        self.viewaction2.setStatusTip("Grid View 2")
        self.viewaction2.triggered.connect(self.grid_view_2)

        self.about = QtGui.QAction("&Info", self)
        self.about.setStatusTip("Info")
        self.about.triggered.connect(self.about_info)

        self.mainMenu = self.menuBar()
        self.fileMenu = self.mainMenu.addMenu("&File")
        self.fileMenu.addAction(self.loadaction)
        self.fileMenu.addAction(self.exportaction)

        self.viewMenu = self.mainMenu.addMenu("&Display")
        self.viewMenu.addAction(self.viewaction1)
        self.viewMenu.addAction(self.viewaction2)

        self.aboutMenu = self.mainMenu.addMenu("&About")
        self.aboutMenu.addAction(self.about)

        self.maketoolbar()

        self.area = DockArea()

        self.drho = Dock("\u03c1")
        self.dlamb = Dock("\u03bb")
        self.dalpha = Dock("\u03b1")
        self.dbeta = Dock("\u03b2")
        self.dphase = Dock("Phase")
        self.dcontrols = Dock("Controls")

        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.area)
        self.mainframe.setLayout(self.layout)
        self.mainframe.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Raised)
        self.mainframe.setLineWidth(8)
Ejemplo n.º 3
0
Archivo: main.py Proyecto: wsonv/Wonjun
    def about_info(self):

        self.awindow = QtGui.QMainWindow()
        self.awindow.setWindowIcon(QtGui.QIcon(logo))
        self.awindow.setWindowTitle('About')
        labels = QtGui.QWidget(self.awindow)
        labels_layout = QtGui.QVBoxLayout(labels)
        self.line0 = QtGui.QLabel()
        self.line1 = QtGui.QLabel(
            "CIVET: Current Inspired Visualization and Evaluation of the")
        self.line2 = QtGui.QLabel()
        self.line3 = QtGui.QLabel(
            "Totally asymmetric simple exclusion process (TASEP)")
        self.line4 = QtGui.QLabel()
        self.line5 = QtGui.QLabel("Copyright (c) 2018,")
        self.line6 = QtGui.QLabel()
        self.line7 = QtGui.QLabel(
            "Wonjun Son, Dan D. Erdmann-Pham,  Khanh Dao Duc, Yun S. Song")
        self.line8 = QtGui.QLabel()
        self.line9 = QtGui.QLabel("All rights reserved.")
        self.line10 = QtGui.QLabel()

        for i in range(11):
            eval("self.line" + str(i)).setAlignment(QtCore.Qt.AlignCenter)
            labels_layout.addWidget(eval("self.line" + str(i)))
        self.awindow.setCentralWidget(labels)
        self.awindow.show()
Ejemplo n.º 4
0
    def drawObjects(self, view_manager):

        geom = view_manager._geometry
        for view in view_manager.getViewPorts():
            thisPlane = view.plane()
            self._drawnObjects.append([])
            # First get the hit information:
            numus = self._process.getDataByPlane(thisPlane)

            for i in xrange(len(numus)):

                # draw the slice hits
                slice_hit_v = numus[i].slicehits()
                print('there are %i hits for the full slice' %
                      (len(slice_hit_v)))
                for ih in xrange(len(slice_hit_v)):
                    hit = slice_hit_v[ih]
                    r = QtGui.QGraphicsRectItem(
                        hit.wire(),
                        hit.time() + geom.timeOffsetTicks(view.plane()), 2,
                        2 * hit.rms())

                    opacity = 0.5  # int(128 * hit.charge() / 100.) + 127
                    # Old Way:
                    r.setPen(pg.mkPen(None))
                    r.setBrush(pg.mkColor((0, 0, 0, 200)))  #,opacity))
                    # r.setBrush((0,0,0,opacity))
                    self._drawnObjects[thisPlane].append(r)
                    view._view.addItem(r)

                # draw the hits
                hits_v = numus[i].hits()
                for ic, hits in enumerate(hits_v):
                    print('there are %i hits on plane %i' %
                          (len(hits), thisPlane))
                    for ih in xrange(len(hits)):
                        hit = hits[ih]
                        #print '\t [w,t] -> [%.0f,%.0f]'%(hit.wire(),hit.time())
                        # Draws a rectangle at (x,y,xlength, ylength)
                        r = QtGui.QGraphicsRectItem(
                            hit.wire(),
                            hit.time() + geom.timeOffsetTicks(view.plane()), 2,
                            2 * hit.rms())

                        opacity = 0.5  # int(128 * hit.charge() / 100.) + 127
                        # Old Way:
                        color = self._Colors[ic % len(self._Colors)]
                        r.setPen(pg.mkPen(None))
                        r.setBrush(pg.mkColor(color))  #,opacity))
                        # r.setBrush((0,0,0,opacity))
                        self._drawnObjects[thisPlane].append(r)
                        view._view.addItem(r)

                # Draw the vertex:
                vertex = numus[i].vertex()
                # Draws a circle at (x,y,radius = 0.5cm)
                radBigW = 1 / view_manager._geometry.wire2cm()
                radBigT = (1) / view_manager._geometry.time2cm()

                offset = view_manager._geometry.offset(
                    thisPlane) / view_manager._geometry.time2cm()

                sW = vertex.w / view_manager._geometry.wire2cm()
                sT = vertex.t / view_manager._geometry.time2cm() + offset

                r = QtGui.QGraphicsEllipseItem(sW - radBigW / 2.,
                                               sT - radBigT / 2., 1 * radBigW,
                                               1 * radBigT)

                r.setPen(pg.mkPen(None))
                r.setBrush(pg.mkColor(255, 255, 255, 200))
                self._drawnObjects[thisPlane].append(r)
                view._view.addItem(r)

                # Draw all the tracks:
                tracks = numus[i].tracks()
                for j in xrange(len(numus[i].tracks())):
                    track = tracks[j]
                    # construct a polygon for this track:
                    points = []
                    # Remeber - everything is in cm, but the display is in
                    # wire/time!
                    for pair in track.track():
                        x = pair.first / geom.wire2cm()
                        y = pair.second / geom.time2cm() + offset
                        points.append(QtCore.QPointF(x, y))

                    thisPoly = polyLine(points)

                    #Change the color here:
                    if j == numus[i].muon_index():
                        # Do something special with the muon
                        pen = pg.mkPen((238, 130, 238), width=2)
                    else:
                        pen = pg.mkPen((139, 0, 139), width=2)

                    thisPoly.setPen(pen)
                    # polyLine.draw(view._view)

                    view._view.addItem(thisPoly)

                    self._drawnObjects[view.plane()].append(thisPoly)

                # showers
                showers = numus[i].showers()

                i_color = 0

                for i in xrange(len(showers)):

                    shower = showers[i]

                    color = (252, 127, 0, 100)

                    # construct a polygon for this shower:
                    points = []
                    # Remember - everything is in cm, but the display is in
                    # wire/time!
                    geom = view_manager._geometry
                    offset = geom.offset(view.plane()) / geom.time2cm()
                    x = shower.startPoint().w / geom.wire2cm()
                    y = shower.startPoint().t / geom.time2cm() + offset

                    points.append(QtCore.QPoint(x, y))
                    # next connect the two points at the end of the shower to make
                    # a cone
                    #
                    # We need the vector that's perpendicular to the axis, to make the cone.
                    # Use 3D vectors to allow the cross product:
                    zAxis = TVector3(0, 0, 1)
                    showerAxis = TVector3(
                        shower.endPoint().w - shower.startPoint().w,
                        shower.endPoint().t - shower.startPoint().t, 0.0)
                    perpAxis = zAxis.Cross(showerAxis)

                    length = showerAxis.Mag() * mt.tan(
                        shower.openingAngle() / 2)
                    perpAxis *= length / perpAxis.Mag()


                    x1, y1 = shower.endPoint().w + perpAxis.X(), shower.endPoint().t + \
                        perpAxis.Y()
                    x2, y2 = shower.endPoint().w - perpAxis.X(), shower.endPoint().t - \
                        perpAxis.Y()

                    # Scale everything to wire/time:
                    x1 /= geom.wire2cm()
                    y1 /= geom.time2cm()
                    x2 /= geom.wire2cm()
                    y2 /= geom.time2cm()

                    y1 += offset
                    y2 += offset

                    points.append(QtCore.QPoint(x1, y1))
                    points.append(QtCore.QPoint(x2, y2))

                    thisPolyF = QtGui.QPolygonF(points)

                    self.shower_poly = QtGui.QGraphicsPolygonItem(thisPolyF)
                    self.shower_poly = shower_polygon(thisPolyF)

                    self.shower_poly.setPen(pg.mkPen(None))
                    self.shower_poly.setBrush(pg.mkColor(color))

                    view._view.addItem(self.shower_poly)
                    self._drawnObjects[view.plane()].append(self.shower_poly)
Ejemplo n.º 5
0
def run():
    app = QtGui.QApplication([])
    loader = ExampleLoader()

    app.exec_()
Ejemplo n.º 6
0
    def __init__(self,
                 parent=None,
                 allowTransforms=True,
                 hideCtrl=False,
                 name=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        #self.view = self.ui.view
        self.view = ViewBox()
        self.ui.view.setCentralItem(self.view)
        self.itemList = self.ui.itemList
        self.itemList.setSelectionMode(self.itemList.ExtendedSelection)
        self.allowTransforms = allowTransforms
        self.multiSelectBox = SelectBox()
        self.view.addItem(self.multiSelectBox)
        self.multiSelectBox.hide()
        self.multiSelectBox.setZValue(1e6)
        self.ui.mirrorSelectionBtn.hide()
        self.ui.reflectSelectionBtn.hide()
        self.ui.resetTransformsBtn.hide()

        self.redirect = None  ## which canvas to redirect items to
        self.items = []

        #self.view.enableMouse()
        self.view.setAspectLocked(True)
        self.view.invertY()

        grid = GridItem()
        self.grid = CanvasItem(grid, name='Grid', movable=False)
        self.addItem(self.grid)

        self.hideBtn = QtGui.QPushButton('>', self)
        self.hideBtn.setFixedWidth(20)
        self.hideBtn.setFixedHeight(20)
        self.ctrlSize = 200
        self.sizeApplied = False
        self.hideBtn.clicked.connect(self.hideBtnClicked)
        self.ui.splitter.splitterMoved.connect(self.splitterMoved)

        self.ui.itemList.itemChanged.connect(self.treeItemChanged)
        self.ui.itemList.sigItemMoved.connect(self.treeItemMoved)
        self.ui.itemList.itemSelectionChanged.connect(self.treeItemSelected)
        self.ui.autoRangeBtn.clicked.connect(self.autoRange)
        self.ui.storeSvgBtn.clicked.connect(self.storeSvg)
        self.ui.storePngBtn.clicked.connect(self.storePng)
        self.ui.redirectCheck.toggled.connect(self.updateRedirect)
        self.ui.redirectCombo.currentIndexChanged.connect(self.updateRedirect)
        self.multiSelectBox.sigRegionChanged.connect(
            self.multiSelectBoxChanged)
        self.multiSelectBox.sigRegionChangeFinished.connect(
            self.multiSelectBoxChangeFinished)
        self.ui.mirrorSelectionBtn.clicked.connect(self.mirrorSelectionClicked)
        self.ui.reflectSelectionBtn.clicked.connect(
            self.reflectSelectionClicked)
        self.ui.resetTransformsBtn.clicked.connect(self.resetTransformsClicked)

        self.resizeEvent()
        if hideCtrl:
            self.hideBtnClicked()

        if name is not None:
            self.registeredName = CanvasManager.instance().registerCanvas(
                self, name)
            self.ui.redirectCombo.setHostName(self.registeredName)
Ejemplo n.º 7
0
# -*- coding: utf-8 -*-
"""
Simple example demonstrating a button which displays a colored rectangle
and allows the user to select a new color by clicking on the button.
"""

import initExample  ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

app = QtGui.QApplication([])
win = QtGui.QMainWindow()
btn = pg.ColorButton()
win.setCentralWidget(btn)
win.show()
win.setWindowTitle('pyqtgraph example: ColorButton')


def change(btn):
    print("change", btn.color())


def done(btn):
    print("done", btn.color())


btn.sigColorChanging.connect(change)
btn.sigColorChanged.connect(done)
Ejemplo n.º 8
0
 def updateGradient(self):
     #private
     self.gradient = self.getGradient()
     self.gradRect.setBrush(QtGui.QBrush(self.gradient))
     self.sigGradientChanged.emit(self)
Ejemplo n.º 9
0
    def __init__(self, parent=None):
        super(QtGui.QWidget, self).__init__(parent)

        # Variables.
        self.GUI_main = self.parent()
        self.board = None  # Pycboard class instance.
        self.task = None  # Task currently uploaded on pyboard.
        self.task_hash = None  # Used to check if file has changed.
        self.data_dir = None  # Folder to save data files.
        self.custom_dir = False  # True if data_dir field has been changed from default.
        self.connected = False  # Whether gui is conencted to pyboard.
        self.uploaded = False  # Whether selected task file is on board.
        self.fresh_task = None  # Whether task has been run or variables edited.
        self.running = False
        self.subject_changed = False
        self.variables_dialog = None

        # GUI groupbox.

        self.status_groupbox = QtGui.QGroupBox('Status')

        self.status_text = QtGui.QLineEdit('Not connected')
        self.status_text.setReadOnly(True)

        self.guigroup_layout = QtGui.QHBoxLayout()
        self.guigroup_layout.addWidget(self.status_text)
        self.status_groupbox.setLayout(self.guigroup_layout)

        # Board groupbox

        self.board_groupbox = QtGui.QGroupBox('Setup')

        self.board_select = QtGui.QComboBox()
        self.board_select.addItems(['No setups found'])
        self.board_select.setSizeAdjustPolicy(0)
        self.connect_button = QtGui.QPushButton('Connect')
        self.connect_button.setIcon(QtGui.QIcon("gui/icons/connect.svg"))
        self.connect_button.setEnabled(False)
        self.config_button = QtGui.QPushButton('Config')
        self.config_button.setIcon(QtGui.QIcon("gui/icons/settings.svg"))

        self.boardgroup_layout = QtGui.QHBoxLayout()
        self.boardgroup_layout.addWidget(self.board_select)
        self.boardgroup_layout.addWidget(self.connect_button)
        self.boardgroup_layout.addWidget(self.config_button)
        self.board_groupbox.setLayout(self.boardgroup_layout)

        self.connect_button.clicked.connect(
            lambda: self.disconnect() if self.connected else self.connect())
        self.config_button.clicked.connect(self.open_config_dialog)

        # File groupbox

        self.file_groupbox = QtGui.QGroupBox('Data file')

        self.data_dir_label = QtGui.QLabel('Data dir:')
        self.data_dir_label.setAlignment(QtCore.Qt.AlignRight
                                         | QtCore.Qt.AlignVCenter)
        self.data_dir_text = QtGui.QLineEdit(dirs['data'])
        self.data_dir_button = QtGui.QPushButton()
        self.data_dir_button.setIcon(QtGui.QIcon("gui/icons/folder.svg"))
        self.data_dir_button.setFixedWidth(30)
        self.subject_label = QtGui.QLabel('Subject ID:')
        self.subject_text = QtGui.QLineEdit()

        self.filegroup_layout = QtGui.QGridLayout()
        self.filegroup_layout.addWidget(self.data_dir_label, 0, 0)
        self.filegroup_layout.addWidget(self.data_dir_text, 0, 1)
        self.filegroup_layout.addWidget(self.data_dir_button, 0, 2)
        self.filegroup_layout.addWidget(self.subject_label, 1, 0)
        self.filegroup_layout.addWidget(self.subject_text, 1, 1)
        self.file_groupbox.setLayout(self.filegroup_layout)

        self.data_dir_text.textChanged.connect(self.test_data_path)
        self.data_dir_text.textEdited.connect(
            lambda: setattr(self, 'custom_dir', True))
        self.data_dir_button.clicked.connect(self.select_data_dir)
        self.subject_text.textChanged.connect(self.test_data_path)

        # Task groupbox

        self.task_groupbox = QtGui.QGroupBox('Task')

        self.task_select = TaskSelectMenu('select task')
        self.task_select.set_callback(self.task_changed)
        self.upload_button = QtGui.QPushButton('Upload')
        self.upload_button.setIcon(
            QtGui.QIcon("gui/icons/circle-arrow-up.svg"))
        self.variables_button = QtGui.QPushButton('Variables')
        self.variables_button.setIcon(QtGui.QIcon("gui/icons/filter.svg"))

        self.taskgroup_layout = QtGui.QGridLayout()
        self.taskgroup_layout.addWidget(self.task_select, 0, 0, 1, 2)
        self.taskgroup_layout.addWidget(self.upload_button, 1, 0)
        self.taskgroup_layout.addWidget(self.variables_button, 1, 1)
        self.task_groupbox.setLayout(self.taskgroup_layout)

        self.upload_button.clicked.connect(self.setup_task)

        # Session groupbox.

        self.session_groupbox = QtGui.QGroupBox('Session')

        self.start_button = QtGui.QPushButton('Start')
        self.start_button.setIcon(QtGui.QIcon("gui/icons/play.svg"))
        self.stop_button = QtGui.QPushButton('Stop')
        self.stop_button.setIcon(QtGui.QIcon("gui/icons/stop.svg"))

        self.task_info = TaskInfo()

        self.sessiongroup_layout = QtGui.QGridLayout()
        self.sessiongroup_layout.addWidget(self.task_info.print_label, 0, 1)
        self.sessiongroup_layout.addWidget(self.task_info.print_text, 0, 2, 1,
                                           3)
        self.sessiongroup_layout.addWidget(self.task_info.state_label, 1, 1)
        self.sessiongroup_layout.addWidget(self.task_info.state_text, 1, 2)
        self.sessiongroup_layout.addWidget(self.task_info.event_label, 1, 3)
        self.sessiongroup_layout.addWidget(self.task_info.event_text, 1, 4)
        self.sessiongroup_layout.addWidget(self.start_button, 0, 0)
        self.sessiongroup_layout.addWidget(self.stop_button, 1, 0)
        self.session_groupbox.setLayout(self.sessiongroup_layout)

        self.start_button.clicked.connect(self.start_task)
        self.stop_button.clicked.connect(self.stop_task)

        # Log text and task plots.

        self.log_textbox = QtGui.QTextEdit()
        self.log_textbox.setFont(QtGui.QFont('Courier New', log_font_size))
        self.log_textbox.setReadOnly(True)

        self.task_plot = Task_plot()
        self.data_logger = Data_logger(
            print_func=self.print_to_log,
            data_consumers=[self.task_plot, self.task_info])

        # Main layout

        self.vertical_layout = QtGui.QVBoxLayout()
        self.horizontal_layout_1 = QtGui.QHBoxLayout()
        self.horizontal_layout_2 = QtGui.QHBoxLayout()
        self.horizontal_layout_3 = QtGui.QHBoxLayout()

        self.horizontal_layout_1.addWidget(self.status_groupbox)
        self.horizontal_layout_1.addWidget(self.board_groupbox)
        self.horizontal_layout_2.addWidget(self.task_groupbox)
        self.horizontal_layout_2.addWidget(self.file_groupbox)
        self.horizontal_layout_3.addWidget(self.session_groupbox)
        self.vertical_layout.addLayout(self.horizontal_layout_1)
        self.vertical_layout.addLayout(self.horizontal_layout_2)
        self.vertical_layout.addLayout(self.horizontal_layout_3)
        self.vertical_layout.addWidget(self.log_textbox, 20)
        self.vertical_layout.addWidget(self.task_plot, 80)
        self.setLayout(self.vertical_layout)

        # Create timers

        self.update_timer = QtCore.QTimer(
        )  # Timer to regularly call update() during run.
        self.update_timer.timeout.connect(self.update)

        # Keyboard Shortcuts

        shortcut_dict = {
            't':
            lambda: self.task_select.showMenu(),
            'u':
            lambda: self.setup_task(),
            'Space': (lambda: self.stop_task()
                      if self.running else self.start_task()
                      if self.uploaded else None)
        }

        init_keyboard_shortcuts(self, shortcut_dict)

        # Initial setup.

        self.disconnect()  # Set initial state as disconnected.
Ejemplo n.º 10
0
    def initializeUI(self):
        self.resize(1024, 768)
        self.setWindowTitle(filepath + ' Viewer')

        exit_action = QtGui.QAction('&Exit', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.setStatusTip('Exit application')
        exit_action.triggered.connect(QtGui.QApplication.instance().quit)
        self.addAction(exit_action)

        self.dock_area = pg.dockarea.DockArea()

        roi_logic = self.roi_logic

        rf_image_logic = ImageLogic(self.filepath)
        rf_image_dock = ImageDock(rf_image_logic, roi_logic,
                                  'RF Image', size=(660, 750))
        self.dock_area.addDock(rf_image_dock)

        plots_dock = PlotsDock('Image ROI Content Plots',
                               size=(1000, 500))
        self.dock_area.addDock(plots_dock, 'bottom', rf_image_dock)

        b_mode_image = sitk.Image(rf_image_logic.image)
        array = sitk.GetArrayFromImage(b_mode_image)
        hilbert = scipy.signal.hilbert(array, axis=1)
        envelope = np.abs(hilbert)
        b_mode_image = sitk.GetImageFromArray(envelope)
        b_mode_image.CopyInformation(rf_image_logic.image)
        b_mode_image_logic = ImageLogic()
        b_mode_image_logic.image = b_mode_image
        b_mode_dock = ImageDock(b_mode_image_logic, roi_logic,
                                'B Mode', size=(660, 750))
        self.dock_area.addDock(b_mode_dock, 'right', rf_image_dock)

        rf_plot_roi = rf_image_dock.add_plot_roi()
        labels = {'bottom': 'Time [usec]'}
        plots_dock.add_image_to_plot(rf_plot_roi,
                                     rf_image_logic.image_array,
                                     rf_image_dock.get_full_image_item(),
                                     'RF (time)',
                                     labels,
                                     0)
        labels = {'bottom': 'Frequency [MHz]'}
        plots_dock.add_image_to_plot(rf_plot_roi,
                                     rf_image_logic.image_array,
                                     rf_image_dock.get_full_image_item(),
                                     'RF (spectrum)',
                                     labels,
                                     1,
                                     True)
        b_mode_plot_roi = b_mode_dock.add_plot_roi()
        labels = {'bottom': 'Time (usec)'}
        plots_dock.add_image_to_plot(b_mode_plot_roi,
                                     b_mode_image_logic.image_array,
                                     b_mode_dock.get_full_image_item(),
                                     'B-Mode',
                                     labels,
                                     2)

        self.setCentralWidget(self.dock_area)
        self.show()
Ejemplo n.º 11
0
gamma = []
X = []
Y = []
Z = []
O = []

eeg_warm = []
theta_warm = []
alpha_warm = []
beta_warm = []
gamma_warm = []
X_warm = []
Y_warm = []
Z_warm = []

app = QtGui.QApplication([])
mw = QtGui.QMainWindow()
mw.setMinimumSize(400, 150)
#Create layout to manage widgets size and positions
layout = QtGui.QGridLayout()
timer = PyQt4.QtCore.QTimer(app)

btn_start = QtGui.QPushButton('Start Meditation')
btn_start.setToolTip('This initiates the calibration phase for meditating')
btn_start.setMaximumSize(btn_start.sizeHint())
btn_stop = QtGui.QPushButton('End Session')
btn_stop.setToolTip('Generate a report of your session')
btn_stop.setMaximumSize(btn_start.sizeHint())


def updateUI(state):
Ejemplo n.º 12
0
    cv2.setNumThreads(1)
except:
    print('Open CV is naturally single threaded')

try:
    if __IPYTHON__:
        print(1)
        # This is used for debugging purposes only. Automatically reloads imports if they change
        get_ipython().magic('load_ext autoreload')
        get_ipython().magic('autoreload 2')
except NameError:
    print('Not launched under iPython')

#%%
## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])

## Define a top-level widget to hold everything
w = QtGui.QWidget()

## Create some widgets to be placed inside
hist = pg.HistogramLUTItem()  # Contrast/color control
win = pg.GraphicsLayoutWidget()
win.setMaximumWidth(300)
win.setMinimumWidth(200)
win.addItem(hist)
p1 = pg.PlotWidget()
neuron_action = ParameterTree()
neuron_list = QtGui.QListWidget()

## Create a grid layout to manage the widgets size and position
Ejemplo n.º 13
0
    def showPowSpec(self):
        """Function that shows the plot and its time-frequency spectrum.
           The user is asked for the colours that should be used in the spectrum.
           If Cancel is clicked, the spectrum is displayed in gray scale."""

        #Some more initialisation.
        self.setWindowTitle("vizEEG - Time-frequency Spectrum display")
        self.img = pg.ImageView()
        self.col1.addWidget(self.img)
        self.imgSlider = pg.InfiniteLine(pos=0,
                                         bounds=[0, self.PSData.shape[0]],
                                         movable=True,
                                         pen='y')
        self.img.addItem(self.imgSlider)
        self.plotSlider.sigDragged.connect(self.imgSliderFunc)
        self.imgSlider.sigDragged.connect(self.plotSliderFunc)
        self.r3 = None

        colours, self.ok = self.colourInput(
            "Choose a colouring for time-frequency spectum images or enter a different one in format RRR,GGG,BBB.\n Please, separate colours (2 or 3) with space.\n If Cancel is clicked spectrum will be displayed in gray scale."
        )

        msgBox = QtGui.QMessageBox()
        msgBox.setWindowTitle("vizEEG: Colour Error")

        if self.ok:

            #If the input was without an error, parse the user input.
            parsed = re.findall("\d{0,3},\d{0,3},\d{0,3}", colours)
            if len(parsed) < 2 or len(parsed) > 3:
                self.ok = False
                msgBox.setText(
                    "Colours input in an incorrect format.\nPlease, input 2 or 3 colours in format RRR,GGG,BBB separated by space, where RRR or GGG or BBB are numbers in range 0-255."
                )
                msgBox.exec_()
            else:
                self.r1 = int(parsed[0].split(',')[0])
                self.g1 = int(parsed[0].split(',')[1])
                self.b1 = int(parsed[0].split(',')[2])
                self.r2 = int(parsed[1].split(',')[0])
                self.g2 = int(parsed[1].split(',')[1])
                self.b2 = int(parsed[1].split(',')[2])
                if len(parsed) == 3:
                    self.r3 = int(parsed[2].split(',')[0])
                    self.g3 = int(parsed[2].split(',')[1])
                    self.b3 = int(parsed[2].split(',')[2])

                #Check if the input colours are in a proper format.
                okRange = range(256)
                areColsOk = self.r1 in okRange and self.r2 in okRange and self.g1 in okRange and self.g2 in okRange and self.b1 in okRange and self.b2 in okRange

                if len(parsed) == 3:
                    areColsOk = areColsOk and self.r3 in okRange and self.g3 in okRange and self.b3 in okRange

                if not areColsOk:
                    self.ok = False
                    msgBox.setText(
                        "Colours are out of RGB range. \nPlease, input 2 or 3 colours in format RRR,GGG,BBB separated by space, where RRR or GGG or BBB are numbers in range 0-255."
                    )
                    msgBox.exec_()

        #Create the gray scale image.
        #makeRGBA outputs a tuple (imgArray,isThereAlphaChannel?)
        TFRGBImg = pg.makeRGBA(self.PSData[:, :, self.data[2][0]],
                               levels=[
                                   np.amin(self.PSData[:, :, self.data[2][0]]),
                                   np.amax(self.PSData[:, :, self.data[2][0]])
                               ])[0]

        if self.ok:

            #Colour the image with 2 colours.
            TFRGBCol = np.zeros(TFRGBImg.shape, dtype=TFRGBImg.dtype)
            if self.r3 is None:
                TFRGBCol[:, :, 0] = (TFRGBImg[:, :, 0] / 255.0) * self.r1 + (
                    1 - (TFRGBImg[:, :, 0].astype(int) / 255.0)) * self.r2
                TFRGBCol[:, :, 1] = (TFRGBImg[:, :, 1] / 255.0) * self.g1 + (
                    1 - (TFRGBImg[:, :, 1].astype(int) / 255.0)) * self.g2
                TFRGBCol[:, :, 2] = (TFRGBImg[:, :, 2] / 255.0) * self.b1 + (
                    1 - (TFRGBImg[:, :, 2].astype(int) / 255.0)) * self.b2
                TFRGBCol[:, :, 3] = 255

            else:

                #Colour the image with 3 colours.
                a = ((TFRGBImg[:, :, 0] / 128) *
                     (TFRGBImg[:, :, 0] / 255.0)) + (
                         abs(TFRGBImg[:, :, 0].astype(int) / 128 - 1) *
                         (TFRGBImg[:, :, 0] / 128.0))
                b = ((TFRGBImg[:, :, 0] / 128) * self.r3) + (
                    abs(TFRGBImg[:, :, 0].astype(int) / 128 - 1) * self.r2)
                c = 1 - (((TFRGBImg[:, :, 0] / 128) *
                          (TFRGBImg[:, :, 0] / 255.0)) +
                         (abs(TFRGBImg[:, :, 0].astype(int) / 128 - 1) *
                          (TFRGBImg[:, :, 0] / 128.0)))
                d = ((TFRGBImg[:, :, 0] / 128) * self.r2) + (
                    abs(TFRGBImg[:, :, 0].astype(int) / 128 - 1) * self.r1)
                TFRGBCol[:, :, 0] = (a * b) + (c * d)

                a = ((TFRGBImg[:, :, 1] / 128) *
                     (TFRGBImg[:, :, 1] / 255.0)) + (
                         abs(TFRGBImg[:, :, 1].astype(int) / 128 - 1) *
                         (TFRGBImg[:, :, 1] / 128.0))
                b = ((TFRGBImg[:, :, 1] / 128) * self.g3) + (
                    abs(TFRGBImg[:, :, 1].astype(int) / 128 - 1) * self.g2)
                c = 1 - (((TFRGBImg[:, :, 1] / 128) *
                          (TFRGBImg[:, :, 1] / 255.0)) +
                         (abs(TFRGBImg[:, :, 1].astype(int) / 128 - 1) *
                          (TFRGBImg[:, :, 1] / 128.0)))
                d = ((TFRGBImg[:, :, 1] / 128) * self.g2) + (
                    abs(TFRGBImg[:, :, 1].astype(int) / 128 - 1) * self.g1)
                TFRGBCol[:, :, 1] = (a * b) + (c * d)

                a = ((TFRGBImg[:, :, 2] / 128) *
                     (TFRGBImg[:, :, 2] / 255.0)) + (
                         abs(TFRGBImg[:, :, 2].astype(int) / 128 - 1) *
                         (TFRGBImg[:, :, 2] / 128.0))
                b = ((TFRGBImg[:, :, 2] / 128) * self.b3) + (
                    abs(TFRGBImg[:, :, 2].astype(int) / 128 - 1) * self.b2)
                c = 1 - (((TFRGBImg[:, :, 2] / 128) *
                          (TFRGBImg[:, :, 2] / 255.0)) +
                         (abs(TFRGBImg[:, :, 2].astype(int) / 128 - 1) *
                          (TFRGBImg[:, :, 2] / 128.0)))
                d = ((TFRGBImg[:, :, 2] / 128) * self.b2) + (
                    abs(TFRGBImg[:, :, 2].astype(int) / 128 - 1) * self.b1)
                TFRGBCol[:, :, 2] = (a * b) + (c * d)
                TFRGBCol[:, :, 3] = 255

            self.img.setImage(TFRGBCol)
        else:
            self.img.setImage(TFRGBImg)
    def __init__(self, parent=None):
        super(QtGui.QWidget, self).__init__(parent)

        # Variables
        self.GUI_main = self.parent()
        self.custom_dir = False  # True if data_dir field has been manually edited.

        # Experiment Groupbox
        self.experiment_groupbox = QtGui.QGroupBox('Experiment')
        self.expbox_Vlayout = QtGui.QVBoxLayout(self.experiment_groupbox)
        self.expbox_Hlayout_1 = QtGui.QHBoxLayout()
        self.expbox_Hlayout_2 = QtGui.QHBoxLayout()
        self.expbox_Hlayout_3 = QtGui.QHBoxLayout()
        self.expbox_Vlayout.addLayout(self.expbox_Hlayout_1)
        self.expbox_Vlayout.addLayout(self.expbox_Hlayout_2)
        self.expbox_Vlayout.addLayout(self.expbox_Hlayout_3)

        self.experiment_select = QtGui.QComboBox()

        self.run_button = QtGui.QPushButton('Run')
        self.new_button = QtGui.QPushButton('New')
        self.delete_button = QtGui.QPushButton('Delete')
        self.save_button = QtGui.QPushButton('Save')
        self.name_label = QtGui.QLabel('Experiment name:')
        self.name_text = QtGui.QLineEdit()
        self.task_label = QtGui.QLabel('Task:')
        self.task_select = QtGui.QComboBox()
        self.task_select.setFixedWidth(150)
        self.hardware_test_label = QtGui.QLabel('Hardware test:')
        self.hardware_test_select = QtGui.QComboBox()
        self.hardware_test_select.setFixedWidth(150)
        self.data_dir_label = QtGui.QLabel('Data dir:')
        self.data_dir_text = QtGui.QLineEdit(data_dir)
        self.data_dir_button = QtGui.QPushButton('...')
        self.data_dir_button.setFixedWidth(30)

        self.expbox_Hlayout_1.addWidget(self.experiment_select)
        self.expbox_Hlayout_1.setStretchFactor(self.experiment_select, 2)
        self.expbox_Hlayout_1.addWidget(self.new_button)
        self.expbox_Hlayout_1.addWidget(self.delete_button)
        self.expbox_Hlayout_1.addWidget(self.save_button)
        self.expbox_Hlayout_1.addWidget(self.run_button)
        self.expbox_Hlayout_2.addWidget(self.name_label)
        self.expbox_Hlayout_2.addWidget(self.name_text)
        self.expbox_Hlayout_2.addWidget(self.task_label)
        self.expbox_Hlayout_2.addWidget(self.task_select)
        self.expbox_Hlayout_2.addWidget(self.hardware_test_label)
        self.expbox_Hlayout_2.addWidget(self.hardware_test_select)
        self.expbox_Hlayout_3.addWidget(self.data_dir_label)
        self.expbox_Hlayout_3.addWidget(self.data_dir_text)
        self.expbox_Hlayout_3.addWidget(self.data_dir_button)

        # Subjects Groupbox
        self.subjects_groupbox = QtGui.QGroupBox('Subjects')
        self.subjectsbox_layout = QtGui.QHBoxLayout(self.subjects_groupbox)
        self.subjects_table = SubjectsTable(self)
        self.subjectsbox_layout.addWidget(self.subjects_table)

        # Variables Groupbox
        self.variables_groupbox = QtGui.QGroupBox('Variables')
        self.variablesbox_layout = QtGui.QHBoxLayout(self.variables_groupbox)
        self.variables_table = VariablesTable(self)
        self.variablesbox_layout.addWidget(self.variables_table)

        # Initialise widgets
        self.experiment_select.addItems(['select experiment'])
        self.task_select.addItems(['select task'])
        self.hardware_test_select.addItems([' no hardware test'])

        # Connect signals.
        self.name_text.textChanged.connect(self.name_edited)
        self.data_dir_text.textEdited.connect(
            lambda: setattr(self, 'custom_dir', True))
        self.data_dir_button.clicked.connect(self.select_data_dir)
        self.experiment_select.activated[str].connect(self.experiment_changed)
        self.task_select.activated[str].connect(
            self.variables_table.task_changed)
        self.new_button.clicked.connect(
            lambda: self.new_experiment(dialog=True))
        self.delete_button.clicked.connect(self.delete_experiment)
        self.save_button.clicked.connect(self.save_experiment)
        self.run_button.clicked.connect(self.run_experiment)

        # Main layout
        self.vertical_layout = QtGui.QVBoxLayout(self)
        self.vertical_layout.addWidget(self.experiment_groupbox)
        self.vertical_layout.addWidget(self.subjects_groupbox)
        self.vertical_layout.addWidget(self.variables_groupbox)
Ejemplo n.º 15
0
def main(args):
    logging.basicConfig(level=max(logging.CRITICAL - (10 * args.verbose), 0))

    app = QtGui.QApplication(sys.argv)
    app.setFont(QtGui.QFont("Open Sans", pointSize=20))

    data_lock = threading.RLock()
    data = dict()

    links = (137, 97, 72)
    max_len = links[0] + links[1] + links[2]
    max_x = max_len * 2
    max_y = max_len * 1.2
    plot = LivePlotter2D((max_x, max_y))
    plot.widget.show()

    curve = plot.getPort()

    def live_plot():
        while True:
            curve.put(data)
            time.sleep(0.1)

    threading.Thread(target=live_plot).start()

    class Handler(socketserver.BaseRequestHandler):
        def handle(self):
            req = self.request[0]
            header, msg = parse_packet(req)

            if header.name != "/manipulator":
                return

            with data_lock:
                origin = (max_x / 2, max_y)
                l1, l2, l3, angles = fwd_kinematics(origin, links,
                                                    msg.measured.q1,
                                                    msg.measured.q2,
                                                    msg.measured.q3)
                i1, i2, i3, inputs = fwd_kinematics(origin, links,
                                                    msg.input.q1, msg.input.q2,
                                                    msg.input.q3)

                data["l1"] = {
                    "x": l1[0],
                    "y": l1[1],
                    "w": 15,
                    "h": links[0],
                    "a": angles[0],
                    "color": "cvra",
                    "fill": "cvra",
                }
                data["l2"] = {
                    "x": l2[0],
                    "y": l2[1],
                    "w": 12,
                    "h": links[1],
                    "a": angles[1],
                    "color": "cvra",
                    "fill": "cvra",
                }
                data["l3"] = {
                    "x": l3[0],
                    "y": l3[1],
                    "w": 10,
                    "h": links[2],
                    "a": angles[2],
                    "color": "cvra",
                    "fill": "cvra",
                }
                data["i1"] = {
                    "x": i1[0],
                    "y": i1[1],
                    "w": 15,
                    "h": links[0],
                    "a": inputs[0],
                    "color": "g",
                    "fill": "g",
                }
                data["i2"] = {
                    "x": i2[0],
                    "y": i2[1],
                    "w": 12,
                    "h": links[1],
                    "a": inputs[1],
                    "color": "g",
                    "fill": "g",
                }
                data["i3"] = {
                    "x": i3[0],
                    "y": i3[1],
                    "w": 10,
                    "h": links[2],
                    "a": inputs[2],
                    "color": "g",
                    "fill": "g",
                }

    def udp_listener():
        with socketserver.UDPServer(("0.0.0.0", args.port), Handler) as server:
            server.serve_forever()

    threading.Thread(target=udp_listener).start()

    if (sys.flags.interactive != 1) or not hasattr(QtCore, "PYQT_VERSION"):
        QtGui.QApplication.instance().exec_()
Ejemplo n.º 16
0
    def __init__(self, *args, **kargs):
        """
        Create a new GradientEditorItem. 
        All arguments are passed to :func:`TickSliderItem.__init__ <pyqtgraph.TickSliderItem.__init__>`
        
        ============= =================================================================================
        **Arguments**
        orientation   Set the orientation of the gradient. Options are: 'left', 'right'
                      'top', and 'bottom'.
        allowAdd      Default is True. Specifies whether ticks can be added to the item.
        tickPen       Default is white. Specifies the color of the outline of the ticks.
                      Can be any of the valid arguments for :func:`mkPen <pyqtgraph.mkPen>`
        ============= =================================================================================
        """
        self.currentTick = None
        self.currentTickColor = None
        self.rectSize = 15
        self.gradRect = QtGui.QGraphicsRectItem(
            QtCore.QRectF(0, self.rectSize, 100, self.rectSize))
        self.backgroundRect = QtGui.QGraphicsRectItem(
            QtCore.QRectF(0, -self.rectSize, 100, self.rectSize))
        self.backgroundRect.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern))
        self.colorMode = 'rgb'

        TickSliderItem.__init__(self, *args, **kargs)

        self.colorDialog = QtGui.QColorDialog()
        self.colorDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True)
        self.colorDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog,
                                   True)

        self.colorDialog.currentColorChanged.connect(self.currentColorChanged)
        self.colorDialog.rejected.connect(self.currentColorRejected)

        self.backgroundRect.setParentItem(self)
        self.gradRect.setParentItem(self)

        self.setMaxDim(self.rectSize + self.tickSize)

        self.rgbAction = QtGui.QAction('RGB', self)
        self.rgbAction.setCheckable(True)
        self.rgbAction.triggered.connect(lambda: self.setColorMode('rgb'))
        self.hsvAction = QtGui.QAction('HSV', self)
        self.hsvAction.setCheckable(True)
        self.hsvAction.triggered.connect(lambda: self.setColorMode('hsv'))

        self.menu = QtGui.QMenu()

        ## build context menu of gradients
        l = self.length
        self.length = 100
        global Gradients
        for g in Gradients:
            px = QtGui.QPixmap(100, 15)
            p = QtGui.QPainter(px)
            self.restoreState(Gradients[g])
            grad = self.getGradient()
            brush = QtGui.QBrush(grad)
            p.fillRect(QtCore.QRect(0, 0, 100, 15), brush)
            p.end()
            label = QtGui.QLabel()
            label.setPixmap(px)
            label.setContentsMargins(1, 1, 1, 1)
            act = QtGui.QWidgetAction(self)
            act.setDefaultWidget(label)
            act.triggered.connect(self.contextMenuClicked)
            act.name = g
            self.menu.addAction(act)
        self.length = l
        self.menu.addSeparator()
        self.menu.addAction(self.rgbAction)
        self.menu.addAction(self.hsvAction)

        for t in self.ticks.keys():
            self.removeTick(t)
        self.addTick(0, QtGui.QColor(0, 0, 0), True)
        self.addTick(1, QtGui.QColor(255, 0, 0), True)
        self.setColorMode('rgb')
        self.updateGradient()
Ejemplo n.º 17
0
 def task_changed(self, task=None):
     self.uploaded = False
     self.upload_button.setText('Upload')
     self.upload_button.setIcon(
         QtGui.QIcon("gui/icons/circle-arrow-up.svg"))
     self.start_button.setEnabled(False)
Ejemplo n.º 18
0
    def getColor(self, x, toQColor=True):
        """
        Return a color for a given value.
        
        ============= ==================================================================
        **Arguments** 
        x             Value (position on gradient) of requested color.
        toQColor      If true, returns a QColor object, else returns a (r,g,b,a) tuple.
        ============= ==================================================================
        """
        ticks = self.listTicks()
        if x <= ticks[0][1]:
            c = ticks[0][0].color
            if toQColor:
                return QtGui.QColor(
                    c)  # always copy colors before handing them out
            else:
                return (c.red(), c.green(), c.blue(), c.alpha())
        if x >= ticks[-1][1]:
            c = ticks[-1][0].color
            if toQColor:
                return QtGui.QColor(
                    c)  # always copy colors before handing them out
            else:
                return (c.red(), c.green(), c.blue(), c.alpha())

        x2 = ticks[0][1]
        for i in range(1, len(ticks)):
            x1 = x2
            x2 = ticks[i][1]
            if x1 <= x and x2 >= x:
                break

        dx = (x2 - x1)
        if dx == 0:
            f = 0.
        else:
            f = (x - x1) / dx
        c1 = ticks[i - 1][0].color
        c2 = ticks[i][0].color
        if self.colorMode == 'rgb':
            r = c1.red() * (1. - f) + c2.red() * f
            g = c1.green() * (1. - f) + c2.green() * f
            b = c1.blue() * (1. - f) + c2.blue() * f
            a = c1.alpha() * (1. - f) + c2.alpha() * f
            if toQColor:
                return QtGui.QColor(r, g, b, a)
            else:
                return (r, g, b, a)
        elif self.colorMode == 'hsv':
            h1, s1, v1, _ = c1.getHsv()
            h2, s2, v2, _ = c2.getHsv()
            h = h1 * (1. - f) + h2 * f
            s = s1 * (1. - f) + s2 * f
            v = v1 * (1. - f) + v2 * f
            c = QtGui.QColor()
            c.setHsv(h, s, v)
            if toQColor:
                return c
            else:
                return (c.red(), c.green(), c.blue(), c.alpha())
def bpmrpm():
    count = 0
    rates = []
    video = True

    if video == False:
        cap = cv2.VideoCapture(0)
    else:
        cap = cv2.VideoCapture("video.webm")

    fu = Face_utilities()
    sp = Signal_processing()

    i=0
    last_rects = None
    last_shape = None
    last_age = None
    last_gender = None

    face_detect_on = False
    age_gender_on = False

    t = time.time()

    #for signal_processing
    BUFFER_SIZE = 100

    fps=0 #for real time capture
    video_fps = cap.get(cv2.CAP_PROP_FPS) # for video capture
    #print(video_fps)

    times = []
    data_buffer = []

    # data for plotting
    filtered_data = []

    fft_of_interest = []
    freqs_of_interest = []

    bpm = 0

    #plotting
    app = QtGui.QApplication([])

    win = pg.GraphicsWindow(title="plotting")
    p1 = win.addPlot(title="FFT")
    p2 = win.addPlot(title ="Signal")
    win.resize(1200,600)

    def update():
        p1.clear()
        p1.plot(np.column_stack((freqs_of_interest,fft_of_interest)), pen = 'g')

        p2.clear()
        p2.plot(filtered_data[20:],pen='g')
        app.processEvents()

    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(300)

    while True:
        # grab a frame -> face detection -> crop the face -> 68 facial landmarks -> get mask from those landmarks

        # calculate time for each loop
        t0 = time.time()

        if(i%1==0):
            face_detect_on = True
            if(i%10==0):
                age_gender_on = True
            else:
                age_gender_on = False
        else:
            face_detect_on = False

        ret, frame = cap.read()
        #frame_copy = frame.copy()

        if frame is None:
            #print("End of video")
            cv2.destroyAllWindows()
            timer.stop()
            #sys.exit()
            break

        #display_frame, aligned_face = flow_process(frame)


        ret_process = fu.no_age_gender_face_process(frame, "68")

        if ret_process is None:
            cv2.putText(frame, "No face detected", (30,30), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,0,255),2)
            cv2.imshow("frame",frame)
            #print(time.time()-t0)

            cv2.destroyWindow("face")
            if cv2.waitKey(1) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                timer.stop()
                #sys.exit()
                break
            continue

        rects, face, shape, aligned_face, aligned_shape = ret_process

        (x, y, w, h) = face_utils.rect_to_bb(rects[0])
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

        #overlay_text = "%s, %s" % (gender, age)
        #cv2.putText(frame, overlay_text ,(x,y-15), cv2.FONT_HERSHEY_SIMPLEX, 1,(255,0,0),2,cv2.LINE_AA)

        if(len(aligned_shape)==68):
            cv2.rectangle(aligned_face,(aligned_shape[54][0], aligned_shape[29][1]), #draw rectangle on right and left cheeks
                    (aligned_shape[12][0],aligned_shape[33][1]), (0,255,0), 0)
            cv2.rectangle(aligned_face, (aligned_shape[4][0], aligned_shape[29][1]),
                    (aligned_shape[48][0],aligned_shape[33][1]), (0,255,0), 0)
        else:
            #print(shape[4][1])
            #print(shape[2][1])
            #print(int((shape[4][1] - shape[2][1])))
            cv2.rectangle(aligned_face, (aligned_shape[0][0],int((aligned_shape[4][1] + aligned_shape[2][1])/2)),
                        (aligned_shape[1][0],aligned_shape[4][1]), (0,255,0), 0)

            cv2.rectangle(aligned_face, (aligned_shape[2][0],int((aligned_shape[4][1] + aligned_shape[2][1])/2)),
                        (aligned_shape[3][0],aligned_shape[4][1]), (0,255,0), 0)

        for (x, y) in aligned_shape:
            cv2.circle(aligned_face, (x, y), 1, (0, 0, 255), -1)


        #for signal_processing
        ROIs = fu.ROI_extraction(aligned_face, aligned_shape)
        green_val = sp.extract_color(ROIs)
        #print(green_val)

        data_buffer.append(green_val)

        if(video==False):
            times.append(time.time() - t)
        else:
            times.append((1.0/video_fps)*i)

        L = len(data_buffer)
        #print("buffer length: " + str(L))

        if L > BUFFER_SIZE:
            data_buffer = data_buffer[-BUFFER_SIZE:]
            times = times[-BUFFER_SIZE:]
            #bpms = bpms[-BUFFER_SIZE//2:]
            L = BUFFER_SIZE
        #print(times)
        if L==100:
            fps = float(L) / (times[-1] - times[0])
            cv2.putText(frame, "fps: {0:.2f}".format(fps), (30,int(frame.shape[0]*0.95)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 2)
            #
            detrended_data = sp.signal_detrending(data_buffer)
            #print(len(detrended_data))
            #print(len(times))
            interpolated_data = sp.interpolation(detrended_data, times)

            normalized_data = sp.normalization(interpolated_data)

            fft_of_interest, freqs_of_interest = sp.fft(normalized_data, fps)

            max_arg = np.argmax(fft_of_interest)
            bpm = freqs_of_interest[max_arg]
            cv2.putText(frame, "HR: {0:.2f}".format(bpm), (int(frame.shape[1]*0.8),int(frame.shape[0]*0.95)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 2)
            #print(detrended_data)
            filtered_data = sp.butter_bandpass_filter(interpolated_data, (bpm-20)/60, (bpm+20)/60, fps, order = 3)
            #print(fps)
            #filtered_data = sp.butter_bandpass_filter(interpolated_data, 0.8, 3, fps, order = 3)

        #write to txt file
        with open("a.txt",mode = "a+") as f:

            rates.append(bpm)
            f.write("time: {0:.4f} ".format(times[-1]) + ", HR: {0:.2f} ".format(bpm) + "\n")

        # display

        #cv2.imshow("mask",mask)
        i = i+1
        #print("time of the loop number "+ str(i) +" : " + str(time.time()-t0))
        count = count + 1


    rates = [i for i in rates if i!=0]
    #print(rates)

    avg = sum(rates)/len(rates)
    resp = avg/4.5
    print("Heart Rate: ",avg)
    print("Respiratory Rate: ", resp)
    l=[]
    l.append(avg)
    l.append(resp)
    return l
Ejemplo n.º 20
0
        s.setData(x, y)
        QtGui.QApplication.processEvents()

    return dataOk


# -------------------------    MAIN   -----------------------------------------

# Configurate the serial port
CLIport, Dataport = serialConfig(configFileName)

# Get the configuration parameters from the configuration file
configParameters = parseConfigFile(configFileName)

# START QtAPPfor the plot
app = QtGui.QApplication([])

# Set the plot
pg.setConfigOption('background', 'w')
win = pg.GraphicsWindow(title="2D scatter plot")
p = win.addPlot()
p.setXRange(-0.5, 0.5)
p.setYRange(0, 1.5)
p.setLabel('left', text='Y position (m)')
p.setLabel('bottom', text='X position (m)')
s = p.plot([], [], pen=None, symbol='o')

# Main loop
detObj = {}
frameData = {}
currentIndex = 0
Ejemplo n.º 21
0
# -*- coding: utf-8 -*-
"""
Demonstrates the appearance / interactivity of GradientWidget
(without actually doing anything useful with it)

"""
# import initExample ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

app = QtGui.QApplication([])
w = QtGui.QMainWindow()
w.show()
w.setWindowTitle('pyqtgraph example: GradientWidget')
w.setGeometry(10, 50, 400, 400)
cw = QtGui.QWidget()
w.setCentralWidget(cw)

l = QtGui.QGridLayout()
l.setSpacing(0)
cw.setLayout(l)

w1 = pg.GradientWidget(orientation='top')
w2 = pg.GradientWidget(orientation='right', allowAdd=False)
# w2.setTickColor(1, QtGui.QColor(255,255,255))
w3 = pg.GradientWidget(orientation='bottom')
w4 = pg.GradientWidget(orientation='left')
w4.loadPreset('spectrum')
label = QtGui.QLabel("""
Ejemplo n.º 22
0
    def addItem(self, citem):
        """
        Add an item to the canvas. 
        """

        ## Check for redirections
        if self.redirect is not None:
            name = self.redirect.addItem(citem)
            self.items.append(citem)
            return name

        if not self.allowTransforms:
            citem.setMovable(False)

        citem.sigTransformChanged.connect(self.itemTransformChanged)
        citem.sigTransformChangeFinished.connect(
            self.itemTransformChangeFinished)
        citem.sigVisibilityChanged.connect(self.itemVisibilityChanged)

        ## Determine name to use in the item list
        name = citem.opts['name']
        if name is None:
            name = 'item'
        newname = name

        ## If name already exists, append a number to the end
        ## NAH. Let items have the same name if they really want.
        #c=0
        #while newname in self.items:
        #c += 1
        #newname = name + '_%03d' %c
        #name = newname

        ## find parent and add item to tree
        #currentNode = self.itemList.invisibleRootItem()
        insertLocation = 0
        #print "Inserting node:", name

        ## determine parent list item where this item should be inserted
        parent = citem.parentItem()
        if parent in (None, self.view.childGroup):
            parent = self.itemList.invisibleRootItem()
        else:
            parent = parent.listItem

        ## set Z value above all other siblings if none was specified
        siblings = [
            parent.child(i).canvasItem for i in xrange(parent.childCount())
        ]
        z = citem.zValue()
        if z is None:
            zvals = [i.zValue() for i in siblings]
            if len(zvals) == 0:
                z = 0
            else:
                z = max(zvals) + 10
            citem.setZValue(z)

        ## determine location to insert item relative to its siblings
        for i in range(parent.childCount()):
            ch = parent.child(i)
            zval = ch.canvasItem.graphicsItem().zValue(
            )  ## should we use CanvasItem.zValue here?
            if zval < z:
                insertLocation = i
                break
            else:
                insertLocation = i + 1

        node = QtGui.QTreeWidgetItem([name])
        flags = node.flags(
        ) | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsDragEnabled
        if not isinstance(citem, GroupCanvasItem):
            flags = flags & ~QtCore.Qt.ItemIsDropEnabled
        node.setFlags(flags)
        if citem.opts['visible']:
            node.setCheckState(0, QtCore.Qt.Checked)
        else:
            node.setCheckState(0, QtCore.Qt.Unchecked)

        node.name = name
        #if citem.opts['parent'] != None:
        ## insertLocation is incorrect in this case
        parent.insertChild(insertLocation, node)
        #else:
        #root.insertChild(insertLocation, node)

        citem.name = name
        citem.listItem = node
        node.canvasItem = citem
        self.items.append(citem)

        ctrl = citem.ctrlWidget()
        ctrl.hide()
        self.ui.ctrlLayout.addWidget(ctrl)

        ## inform the canvasItem that its parent canvas has changed
        citem.setCanvas(self)

        ## Autoscale to fit the first item added (not including the grid).
        if len(self.items) == 2:
            self.autoRange()

        #for n in name:
        #nextnode = None
        #for x in range(currentNode.childCount()):
        #ch = currentNode.child(x)
        #if hasattr(ch, 'name'):    ## check Z-value of current item to determine insert location
        #zval = ch.canvasItem.zValue()
        #if zval > z:
        ###print "  ->", x
        #insertLocation = x+1
        #if n == ch.text(0):
        #nextnode = ch
        #break
        #if nextnode is None:  ## If name doesn't exist, create it
        #nextnode = QtGui.QTreeWidgetItem([n])
        #nextnode.setFlags((nextnode.flags() | QtCore.Qt.ItemIsUserCheckable) & ~QtCore.Qt.ItemIsDropEnabled)
        #nextnode.setCheckState(0, QtCore.Qt.Checked)
        ### Add node to correct position in list by Z-value
        ###print "  ==>", insertLocation
        #currentNode.insertChild(insertLocation, nextnode)

        #if n == name[-1]:   ## This is the leaf; add some extra properties.
        #nextnode.name = name

        #if n == name[0]:   ## This is the root; make the item movable
        #nextnode.setFlags(nextnode.flags() | QtCore.Qt.ItemIsDragEnabled)
        #else:
        #nextnode.setFlags(nextnode.flags() & ~QtCore.Qt.ItemIsDragEnabled)

        #currentNode = nextnode
        return citem
Ejemplo n.º 23
0
    def initUI(self, e=None):
        """ Definition and initialisation of the GUI plus staring the measurement.
        """

        self._scanning_logic = self.connector['in']['confocallogic1']['object']
        print("Scanning logic is", self._scanning_logic)

        # setting up the window
        self._mw = QtGui.QMainWindow()
        self._mw.setWindowTitle('qudi: Counter Test GUI')
        self._mw.resize(400, 100)
        self._cw = QtGui.QWidget()
        self._mw.setCentralWidget(self._cw)

        # defining buttons
        self._start_stop_button = QtGui.QPushButton('Start Scan')
        self._start_stop_button.released.connect(self.start_clicked)

        # defining the parameters to edit
        self._x_label = QtGui.QLabel('x:')
        self._x_display = QtGui.QSpinBox()
        self._x_display.setRange(0, 1e3)
        self._x_display.setValue(10)
        self._x_display.valueChanged.connect(self.x_changed)

        self._y_label = QtGui.QLabel('y:')
        self._y_display = QtGui.QSpinBox()
        self._y_display.setRange(0, 1e3)
        self._y_display.setValue(10)
        self._y_display.valueChanged.connect(self.x_changed)

        self._z_label = QtGui.QLabel('z:')
        self._z_display = QtGui.QSpinBox()
        self._z_display.setRange(0, 1e3)
        self._z_display.setValue(10)
        self._z_display.valueChanged.connect(self.x_changed)

        self._a_label = QtGui.QLabel('a:')
        self._a_display = QtGui.QSpinBox()
        self._a_display.setRange(0, 1e3)
        self._a_display.setValue(10)
        self._a_display.valueChanged.connect(self.x_changed)

        # creating a layout for the parameters to live in and aranging it nicely
        self._hbox_layout = QtGui.QHBoxLayout()
        self._hbox_layout.addWidget(self._x_label)
        self._hbox_layout.addWidget(self._x_display)
        self._hbox_layout.addStretch(1)
        self._hbox_layout.addWidget(self._y_label)
        self._hbox_layout.addWidget(self._y_display)
        self._hbox_layout.addStretch(1)
        self._hbox_layout.addWidget(self._z_label)
        self._hbox_layout.addWidget(self._z_display)
        self._hbox_layout.addStretch(1)
        self._hbox_layout.addWidget(self._a_label)
        self._hbox_layout.addWidget(self._a_display)

        # funny gifs
        self.movie_screen = QtGui.QLabel()
        #        self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.movie_screen.setFixedHeight(300)
        self.movie_screen.setFixedWidth(300)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        self.movie_screen.setStyleSheet(
            'QLabel {background-color: white; color: red;}')
        # Add the QMovie object to the label
        self.idle_movie = QtGui.QMovie('artwork/idle_smiley.gif',
                                       QtCore.QByteArray(), self)
        self.idle_movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.idle_movie.setSpeed(100)
        #        self.idle_movie.setBackgroundColor(QtGui.QColor(255,255,255))
        self.idle_movie.start()
        self.active_movie = QtGui.QMovie('artwork/active_smiley.gif',
                                         QtCore.QByteArray(), self)
        self.active_movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.active_movie.setSpeed(100)
        self.active_movie.start()
        self.movie_screen.setMovie(self.idle_movie)

        self._hbox_layout_icon = QtGui.QHBoxLayout()
        self._hbox_layout_icon.addStretch(1)
        self._hbox_layout_icon.addWidget(self.movie_screen)
        self._hbox_layout_icon.addStretch(1)

        # kombining the layouts with the plot
        self._vbox_layout = QtGui.QVBoxLayout()
        self._vbox_layout.addLayout(self._hbox_layout)
        self._vbox_layout.addWidget(self._start_stop_button)
        self._vbox_layout.addStretch(1)
        self._vbox_layout.addLayout(self._hbox_layout_icon)

        # applying all the GUI elements to the window
        self._cw.setLayout(self._vbox_layout)
        self._mw.show()

        # starting the physical measurement
        self._scanning_logic.start_scanner()
        self.signal_start_scan.connect(self._scanning_logic.start_scanning)
        self.signal_stop_scan.connect(self._scanning_logic.stop_scanning)
        self._scanning_logic.signal_scan_updated.connect(self.update_state)
Ejemplo n.º 24
0
Archivo: main.py Proyecto: wsonv/Wonjun
 def alphacheck(self):
     self.alphline = QtGui.QCheckBox('\u03B1 line')
     self.alproxy = QtGui.QGraphicsProxyWidget()
     self.alproxy.setWidget(self.alphline)
     self.win.addItem(self.alphline)
     self.alphline.stateChanged.connect(self.alphstate)
# -*- coding: utf-8 -*-
"""
Use a HistogramLUTWidget to controls the contrast / coloration of an image.
"""

## Add path to library (just for examples; you do not need this)
#import initExample

import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.resize(800, 600)
win.show()
win.setWindowTitle('pyqtgraph example: Histogram LUT')

cw = QtGui.QWidget()
win.setCentralWidget(cw)

l = QtGui.QGridLayout()
cw.setLayout(l)
l.setSpacing(0)

v = pg.GraphicsView()
vb = pg.ViewBox()
vb.setAspectLocked()
v.setCentralItem(vb)
l.addWidget(v, 0, 0, 3, 1)
Ejemplo n.º 26
0
Archivo: main.py Proyecto: wsonv/Wonjun
            # Breaks the loop i
            try:
                temp = []
                while (True):
                    T = f.readline().strip()
                    temp += [[glo_var.lambdas_degree, round(eval(T), 2)]]
                    glo_var.lambdas_degree += 1

            except:
                for x, y in temp:
                    glo_var.lambdas += [[x / (glo_var.lambdas_degree - 1), y]]
            glo_var.l = 1

        else:
            err = QtGui.QMessageBox(self.win)
            err.setIcon(QMessageBox().Warning)
            err.setText("Please select txt or csv file Format")
            err.setWindowTitle("File Format Error")
            err.setStandardButtons(QMessageBox.Ok)
            err.buttonClicked.connect()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    ison = 0
    # window = MainWindow()
    # window.show()
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())
Ejemplo n.º 27
0
# -*- coding: utf-8 -*-
"""
This example demonstrates the use of pyqtgraph's parametertree system. This provides
a simple way to generate user interfaces that control sets of parameters. The example
demonstrates a variety of different parameter types (int, float, list, etc.)
as well as some customized parameter types
"""

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui

import json

app = QtGui.QApplication([])
import pyqtgraph.parametertree.parameterTypes as pTypes
from pyqtgraph.parametertree import Parameter, ParameterTree, ParameterItem, registerParameterType


## test subclassing parameters
## This parameter automatically generates two child parameters which are always reciprocals of each other
class ComplexParameter(pTypes.GroupParameter):
    def __init__(self, **opts):
        opts['type'] = 'bool'
        opts['value'] = True
        pTypes.GroupParameter.__init__(self, **opts)

        self.addChild({
            'name': 'A = 1/B',
            'type': 'float',
            'value': 7,
            'suffix': 'Hz',
Ejemplo n.º 28
0
Archivo: main.py Proyecto: wsonv/Wonjun
    def exportdata(self):
        self.dialog = QtGui.QFileDialog()
        self.dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
        self.dialog.setFileMode(QtGui.QFileDialog.DirectoryOnly)

        folder_name = self.dialog.getSaveFileName(self, "Save Directory")
        filepath = os.path.join(os.path.abspath(os.sep), folder_name)
        if not os.path.exists(filepath):
            makedirs(filepath)

        lambda_data = os.path.join(filepath, "Lambda_data.csv")
        with open(lambda_data, "w") as output:
            try:
                writer = csv.writer(output, lineterminator='\n')
                for val in np.array(glo_var.lambdas)[:, 1]:
                    writer.writerow([val])
            except:
                pass

        summary = os.path.join(filepath, "Summary.csv")
        with open(summary, "w") as output:
            try:
                writer = csv.writer(output,
                                    delimiter='\t',
                                    lineterminator='\n')
                writer.writerow(["alpha", glo_var.alpha])
                writer.writerow(["beta", glo_var.beta])
                writer.writerow(["l", glo_var.l])
                writer.writerow(["Phase", self.phas.pointer.region_aft])
            except:
                pass

        # for name, pitem in self.pltlist:
        # 	self.exportimg(pitem,os.path.join(filepath,name + ".svg"))
        # 	# self.exportimg(pitem,os.path.join(filepath,name + ".png"))

        currentanddensity = os.path.join(filepath, "Current & Density.csv")
        with open(currentanddensity, "w") as output:
            writer = csv.writer(output, delimiter='\t', lineterminator='\n')
            # combine alpha, beta    pre and post. Do it here to lessen the computation
            alpha_x_data = np.concatenate([
                np.array(self.jalph.alphas_pre),
                np.linspace(self.jalph.trans_point, 1, 2)
            ])
            alpha_j_data = np.concatenate(
                [self.jalph.j_l_values,
                 np.array([self.jalph.jpost] * 2)])
            alpha_rho_data = np.array(self.jalph.rho_avg_pre +
                                      self.jalph.rho_avg_post)

            beta_x_data = np.concatenate([
                np.array(self.jbet.betas_pre),
                np.linspace(self.jbet.trans_point, 1, 2)
            ])
            beta_j_data = np.concatenate(
                [self.jbet.j_r_values,
                 np.array([self.jbet.jpost] * 2)])
            beta_rho_data = np.array(self.jbet.rho_avg_pre +
                                     self.jbet.rho_avg_post)

            alpha_data = np.vstack(
                [alpha_x_data, alpha_j_data, alpha_rho_data])
            beta_data = np.vstack([beta_x_data, beta_j_data, beta_rho_data])

            writer.writerow([
                "alpha", "Current", "Average Density", '\t', '\t', "beta",
                "Current", "Average Density"
            ])
            for i in range(len(alpha_x_data)):
                writer.writerow(
                    list(alpha_data[:, i]) + [''] * 2 + list(beta_data[:, i]))
            writer.writerow('\n')
            writer.writerow(
                ['beta', glo_var.beta, '', '', '', 'alpha', glo_var.alpha, ''])
            writer.writerow([
                'transition point', self.jalph.trans_point, '', '', '',
                'transition point', self.jbet.trans_point, ''
            ])

        self.pdfgroup1 = ['Lambda_fig', 'Density_fig']
        self.pdfgroup2 = ['Current_alpha_fig', 'Current_beta_fig']
        for name, pitem in self.pltlist:
            # self.exportimg(pitem,os.path.join(filepath,name + ".png"))
            path = os.path.join(filepath, name + ".svg")
            self.exportimg(pitem, path)
            if name in self.pdfgroup1:
                # self.pltlist = [['Lambda_fig', self.lamb_po.p1], ['Density_fig',self.rh.p2], ['Current_alpha_fig', self.jalph.plotitemtoexport], ['Current_beta_fig',self.jbet.plotitemtoexport], ['Phase_fig',self.phas.p5]]
                self.makepdf(path, os.path.join(filepath, name + ".pdf"), 550,
                             260, 20, 240)
            elif name in self.pdfgroup2:
                self.makepdf(path, os.path.join(filepath, name + ".pdf"), 350,
                             250, 10, 230)
            else:
                self.makepdf(path, os.path.join(filepath, name + ".pdf"), 410,
                             330, 10, 300)
            os.remove(path)
Ejemplo n.º 29
0
            0]  ## using signal proxy turns original arguments into a tuple
        if self.CandlePlot.sceneBoundingRect().contains(pos):
            mousePoint = self.CandlePlot.vb.mapSceneToView(pos)
            index = int(mousePoint.x())
            xLeft = self.candleData[0, 0]
            xRight = self.candleData[len(self.candleData) - 1, 0]
            if index > xLeft and index < xRight:
                self.label.setText(
                    "<span style='font-size: 12pt'>x=%0.1f,   <span style='color: red'>y1=%0.1f</span>,   <span style='color: green'>y2=%0.1f</span>"
                    % (mousePoint.x(), index, index))
            self.vLine.setPos(mousePoint.x())
            self.hLine.setPos(mousePoint.y())


if __name__ == '__main__':
    import os, sys
    dataRoot = os.path.abspath(
        os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
                     'histdata'))
    sys.path.append(dataRoot)
    import dataCenter as dataCenter
    candleData = dataCenter.getCandleData()

    import sys
    app = QtGui.QApplication(sys.argv)
    mw = QtGui.QMainWindow()

    win = pgCandleWidgetCross(dataForCandle=candleData)
    mw.setCentralWidget(win)
    mw.show()
    sys.exit(app.exec_())
Ejemplo n.º 30
0
Archivo: DSSUI.py Proyecto: lext/DSS
 def rem_segment_slot(self):
     mb = QtGui.QMessageBox(self)
     mb.setText("Not implemented!")
     mb.exec_()
Ejemplo n.º 31
0
(displayed at bottom). 


"""

## Add path to library (just for examples; you do not need this)
import initExample

import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg

app = pg.mkQApp("Data Slicing Example")

## Create window with two ImageView widgets
win = QtGui.QMainWindow()
win.resize(800, 800)
win.setWindowTitle('pyqtgraph example: DataSlicing')
cw = QtGui.QWidget()
win.setCentralWidget(cw)
l = QtGui.QGridLayout()
cw.setLayout(l)
imv1 = pg.ImageView()
imv2 = pg.ImageView()
l.addWidget(imv1, 0, 0)
l.addWidget(imv2, 1, 0)
win.show()

roi = pg.LineSegmentROI([[10, 64], [120, 64]], pen='r')
imv1.addItem(roi)