Esempio n. 1
0
 def _getFilePathsFromUrls(self, urls):
     '''
     return a list of all file paths in event.mimeData.urls()
     '''
     l = []
     def _appendRecursive(path):
         if path.isfile():
             #file
             l.append(path)
         else:
             for f in path:
                 #for all files in folder
                 _appendRecursive(path.join(f))
     # one or more files/folders are dropped
     for url in urls:
         if url.isLocalFile():
             path = PathStr(url.toLocalFile().toLocal8Bit().data())
             if path.exists():
                 _appendRecursive(path)
     return l
Esempio n. 2
0
    def _getFilePathsFromUrls(self, urls):
        '''
        return a list of all file paths in event.mimeData.urls()
        '''
        l = []

        def _appendRecursive(path):
            if path.isfile():
                #file
                l.append(path)
            else:
                for f in path:
                    #for all files in folder
                    _appendRecursive(path.join(f))

        # one or more files/folders are dropped
        for url in urls:
            if url.isLocalFile():
                path = PathStr(url.toLocalFile().toLocal8Bit().data())
                if path.exists():
                    _appendRecursive(path)
        return l
Esempio n. 3
0
def equalizeImage(img, save_path=None, name_additive='_eqHist'):
    '''
    Equalize the histogram (contrast) of an image
    works with RGB/multi-channel images
    and flat-arrays
    
    @param img  - image_path or np.array
    @param save_path if given output images will be saved there
    @param name_additive if given this additive will be appended to output images 

    @return output images if input images are numpy.arrays and no save_path is given
    @return None elsewise 
    '''

    if isinstance(img, basestring):
        img = PathStr(img)
        if not img.exists():
            raise Exception("image path doesn't exist")
        img_name = img.basename().replace('.','%s.' %name_additive)
        if save_path is None:
            save_path = img.dirname()
        img = cv2.imread(img)

    
    if img.dtype != np.dtype('uint8'):
        #openCV cannot work with float arrays or uint > 8bit
        eqFn = _equalizeHistogram
    else:
        eqFn = cv2.equalizeHist
    if len(img.shape) == 3:#multi channel img like rgb
        for i in range(img.shape[2]):
            img[:, :, i] = eqFn(img[:, :, i]) 
    else: # grey scale image 
        img = eqFn(img)
    if save_path:
        img_name = PathStr(save_path).join(img_name)
        cv2.imwrite(img_name, img)
    return img
Esempio n. 4
0
def equalizeImage(img, save_path=None, name_additive='_eqHist'):
    '''
    Equalize the histogram (contrast) of an image
    works with RGB/multi-channel images
    and flat-arrays

    @param img  - image_path or np.array
    @param save_path if given output images will be saved there
    @param name_additive if given this additive will be appended to output images

    @return output images if input images are numpy.arrays and no save_path is given
    @return None elsewise
    '''

    if isinstance(img, string_types):
        img = PathStr(img)
        if not img.exists():
            raise Exception("image path doesn't exist")
        img_name = img.basename().replace('.', '%s.' % name_additive)
        if save_path is None:
            save_path = img.dirname()
        img = cv2.imread(img)

    if img.dtype != np.dtype('uint8'):
        # openCV cannot work with float arrays or uint > 8bit
        eqFn = _equalizeHistogram
    else:
        eqFn = cv2.equalizeHist
    if len(img.shape) == 3:  # multi channel img like rgb
        for i in range(img.shape[2]):
            img[:, :, i] = eqFn(img[:, :, i])
    else:  # grey scale image
        img = eqFn(img)
    if save_path:
        img_name = PathStr(save_path).join(img_name)
        cv2.imwrite(img_name, img)
    return img
Esempio n. 5
0
    def _getFilePathsFromUrls(self, urls):
        '''
        return a list of all file paths in event.mimeData.urls()
        '''
        limg, lagenda = [], []

        def _appendRecursive(path):
            if path.isfile():
                if path.filetype() in IMG_FILETYPES:
                    limg.append(path)
                elif path.filetype() == 'csv':
                    lagenda.append(path)
            else:
                for f in path:
                    # for all files in folder
                    _appendRecursive(path.join(f))

        # one or more files/folders are dropped
        for url in urls:
            if url.isLocalFile():
                path = PathStr(url.toLocalFile())
                if path.exists():
                    _appendRecursive(path)
        return limg, lagenda
Esempio n. 6
0
class Launcher(QtWidgets.QMainWindow):
    """
    A graphical starter for *.pyz files created by the save-method from
    appbase.MainWindow

    NEEDS AN OVERHAUL ... after that's done it will be able to:

    * show all *.pyz-files in a filetree
    * show the session specific ...

        * icon
        * description
        * author etc.
    * start, remove, rename, modify a session
    * modify, start a certain state of a session
    """

    def __init__(self,
                 title='PYZ-Launcher',
                 icon=None,
                 start_script=None,
                 left_header=None,
                 right_header=None,
                 file_type='pyz'
                 ):
        self.dialogs = Dialogs()

        _path = PathStr.getcwd()
        _default_text_color = '#3c3c3c'

        if icon is None:
            icon = os.path.join(_path, 'media', 'launcher_logo.svg')
        if start_script is None:
            start_script = os.path.join(_path, 'test_session.py')
        if left_header is None:
            _description = "<a href=%s style='color: %s'>%s</a>" % (
                appbase.__url__, _default_text_color, appbase.__description__)

            left_header = """<b>%s</b><br>
                version&nbsp;&nbsp;
                <a href=%s style='color: %s'>%s</a><br>
                autor&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href=mailto:%s style='color: %s'>%s</a> """ % (  # text-decoration:underline
                _description,
                os.path.join(_path, 'media', 'recent_changes.txt'),
                _default_text_color,
                appbase.__version__,
                appbase.__email__,
                _default_text_color,
                appbase.__author__
            )
        if right_header is None:
            # if no header is given, list all pdfs in folder media as link
            d = _path
            right_header = ''
            for f in os.listdir(os.path.join(d, 'media')):
                if f.endswith('.pdf'):
                    _guidePath = os.path.join(d, 'media', f)
                    right_header += "<a href=%s style='color: %s'>%s</a><br>" % (
                        _guidePath, _default_text_color, f[:-4])
            right_header = right_header[:-4]

        QtWidgets.QMainWindow.__init__(self)

        self._start_script = start_script
        self.setWindowTitle(title)
        self.setWindowIcon(QtGui.QIcon(icon))
        self.resize(900, 500)
        # BASE STRUTURE
        area = QtWidgets.QWidget()
        self.setCentralWidget(area)
        layout = QtWidgets.QVBoxLayout()
        area.setLayout(layout)
        #header = QtWidgets.QHBoxLayout()
        # layout.addLayout(header)
        # grab the default text color of a qlabel to color all links from blue to it:
        # LEFT TEXT
        info = QtWidgets.QLabel(left_header)
        info.setOpenExternalLinks(True)
        # LOGO
        header = QtWidgets.QWidget()
        header.setFixedHeight(70)
        headerlayout = QtWidgets.QHBoxLayout()
        header.setLayout(headerlayout)
        logo = QtSvg.QSvgWidget(icon)
        logo.setFixedWidth(50)
        logo.setFixedHeight(50)
        headerlayout.addWidget(logo)
        headerlayout.addWidget(info)
        layout.addWidget(header)
        # RIGHT_HEADER
        userGuide = QtWidgets.QLabel(right_header)
        userGuide.setOpenExternalLinks(True)
        userGuide.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)
        headerlayout.addWidget(userGuide)
        # ROOT-PATH OF THE SESSIONS
        rootLayout = QtWidgets.QHBoxLayout()
        rootFrame = QtWidgets.QFrame()
        rootFrame.setFrameStyle(
            QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Plain)
        rootFrame.setFixedHeight(45)
        rootFrame.setLineWidth(0)
        rootFrame.setLayout(rootLayout)
        layout.addWidget(rootFrame)
        self.rootDir = QtWidgets.QLabel()
        self.rootDir.setAutoFillBackground(True)
        self.rootDir.setStyleSheet("QLabel { background-color: white; }")

        # FILE-BROWSER
        self.treeView = _TreeView()

        self.fileSystemModel = _FileSystemModel(self.treeView, file_type)
        self.fileSystemModel.setNameFilters(['*.%s' % file_type])
        self.fileSystemModel.setNameFilterDisables(False)
        self.treeView.setModel(self.fileSystemModel)

        treelayout = QtWidgets.QHBoxLayout()
        splitter = QtWidgets.QSplitter(QtCore.Qt.Orientation(1))

        self.fileInfo = _PyzInfo(splitter, self.fileSystemModel, self.treeView)
        self.treeView.clicked.connect(self.fileInfo.update)

        splitter.addWidget(self.treeView)
        splitter.addWidget(self.fileInfo)
        treelayout.addWidget(splitter)

        layout.addLayout(treelayout)

        # get last root-path
        self._path = PathStr('')
        if CONFIG_FILE:
            try:
                self._path = PathStr(
                    open(
                        CONFIG_FILE,
                        'r').read().decode('unicode-escape'))
            except IOError:
                pass  # file not existant
        if not self._path or not self._path.exists():
            msgBox = QtWidgets.QMessageBox()
            msgBox.setText("Please choose your projectDirectory.")
            msgBox.exec_()
            self._changeRootDir()
        self.treeView.setPath(self._path)
        abspath = os.path.abspath(self._path)
        self.rootDir.setText(abspath)
        rootLayout.addWidget(self.rootDir)
        # GO UPWARDS ROOT-PATH BUTTON
        btnUpRootDir = QtWidgets.QPushButton('up')
        btnUpRootDir.clicked.connect(self._goUpRootDir)
        rootLayout.addWidget(btnUpRootDir)
        # DEFINE CURRENT DIR AS ROOT-PATH
        btnDefineRootDir = QtWidgets.QPushButton('set')
        btnDefineRootDir.clicked.connect(self._defineRootDir)
        rootLayout.addWidget(btnDefineRootDir)
        # SELECT ROOT-PATH BUTTON
        buttonRootDir = QtWidgets.QPushButton('select')
        buttonRootDir.clicked.connect(self._changeRootDir)
        rootLayout.addWidget(buttonRootDir)
        # NEW-BUTTON
        if self._start_script:
            newButton = QtWidgets.QPushButton('NEW')
            newButton.clicked.connect(self._openNew)
            layout.addWidget(newButton)

    @staticmethod
    def rootDir():
        try:
            return PathStr(
                open(CONFIG_FILE, 'r').read().decode('unicode-escape'))
        except IOError:  # create starter
            return PathStr.home()

    def _goUpRootDir(self):
        self._setRootDir(self._path.dirname())

    def _defineRootDir(self):
        i = self.treeView.selectedIndexes()
        # if not self.treeView.isIndexHidden(i):
        if i:
            if self.fileSystemModel.isDir(i[0]):
                self._setRootDir(PathStr(self.fileSystemModel.filePath(i[0])))

    def _changeRootDir(self):
        path = self.dialogs.getExistingDirectory()
        if path:
            self._setRootDir(path)

    def _setRootDir(self, path):
        self._path = path
        self.rootDir.setText(self._path)
        root = self.fileSystemModel.setRootPath(self._path)
        self.treeView.setRootIndex(root)
        # save last path to file
        if CONFIG_FILE:
            open(CONFIG_FILE, 'w').write(self._path.encode('unicode-escape'))

    def _openNew(self):
        p = spawn.find_executable("python")
        os.spawnl(os.P_NOWAIT, p, 'python', '%s' % self._start_script)