Пример #1
0
    def __locate_code_in_project(self, queue_folders, nproject):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue_folders.empty():
            current_dir = QDir(queue_folders.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue_folders.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in nproject.extensions], file_filter)
            #process all files in current dir!
            global files_paths
            for one_file in current_files:
                try:
                    self._grep_file_symbols(one_file.absoluteFilePath(),
                                            one_file.fileName())
                    files_paths[nproject.path].append(
                        one_file.absoluteFilePath())
                except Exception as reason:
                    logger.error(
                        '__locate_code_in_project, error: %r' % reason)
                    logger.error(
                        '__locate_code_in_project fail for file: %r' %
                        one_file.absoluteFilePath())
    def __locate_code_in_project(self, queue_folders, nproject):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not queue_folders.empty():
            current_dir = QDir(queue_folders.get())
            #Skip not readable dirs!
            if not current_dir.isReadable():
                continue

            #Collect all sub dirs!
            current_sub_dirs = current_dir.entryInfoList(dir_filter)
            for one_dir in current_sub_dirs:
                queue_folders.put(one_dir.absoluteFilePath())

            #all files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                ['*{0}'.format(x) for x in nproject.extensions], file_filter)
            #process all files in current dir!
            global files_paths
            for one_file in current_files:
                try:
                    self._grep_file_symbols(one_file.absoluteFilePath(),
                                            one_file.fileName())
                    files_paths[nproject.path].append(
                        one_file.absoluteFilePath())
                except Exception as reason:
                    logger.error('__locate_code_in_project, error: %r' %
                                 reason)
                    logger.error('__locate_code_in_project fail for file: %r' %
                                 one_file.absoluteFilePath())
Пример #3
0
    def get_img_path():
      if self.output_dir == None:
        msgBox = QMessageBox()
        msgBox.setWindowTitle("提示")
        msgBox.setText("请先设置输出目录")
        msgBox.exec()
        return
      f_path, _ = QFileDialog.getOpenFileName(parent=None, caption="Select Image",
                                              filter="Images (*.jpg *.jpeg *.tif *.bmp *.png)",
                                              options=QFileDialog.ReadOnly)
      if f_path != '':
        f_path = Path(f_path)
        input_dir: Path = f_path.parent
        qdir = QDir(input_dir.as_posix())
        qdir.setNameFilters("*.jpg *.jpeg *.tif *.bmp *.png".split(' '))
        f_list = [input_dir / f.fileName() for f in qdir.entryInfoList()]
        self.input_list = ImageFileList(f_path, f_list)
        self.cur_path = self.input_list.curt()
        self.input_lb.setText(self.cur_path.parent.as_posix())
        # 设置进度条
        self.file_pb.setRange(0, self.input_list.size)
        self.file_pb.setValue(self.input_list.idx)
        self.change_matting_image()

      else:
        self.input_lb.setText("请选择输入文件")
Пример #4
0
	def getExportExtensionsList(self):
		extensions = []
		for extsprefix in datadirs:
			extsdir = QDir(extsprefix+'/export-extensions/')
			if extsdir.exists():
				for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'],
				QDir.Files | QDir.Readable):
					extensions.append(self.readExtension(fileInfo.filePath()))
		locale = QLocale.system().name()
		self.extensionActions = []
		for extension in extensions:
			try:
				if ('Name[%s]' % locale) in extension:
					name = extension['Name[%s]' % locale]
				elif ('Name[%s]' % locale.split('_')[0]) in extension:
					name = extension['Name[%s]' % locale.split('_')[0]]
				else:
					name = extension['Name']
				data = {}
				for prop in ('FileFilter', 'DefaultExtension', 'Exec'):
					if 'X-ReText-'+prop in extension:
						data[prop] = extension['X-ReText-'+prop]
					elif prop in extension:
						data[prop] = extension[prop]
					else:
						data[prop] = ''
				action = self.act(name, trig=self.extensionFunction(data))
				if 'Icon' in extension:
					action.setIcon(self.actIcon(extension['Icon']))
				mimetype = extension['MimeType'] if 'MimeType' in extension else None
			except KeyError:
				print('Failed to parse extension: Name is required', file=sys.stderr)
			else:
				self.extensionActions.append((action, mimetype))
Пример #5
0
 def populateProjectDirectoryItem(self, parentItem, repopulate=False):
     """
     Public method to populate a directory item's subtree.
     
     @param parentItem reference to the directory item to be populated
     @param repopulate flag indicating a repopulation (boolean)
     """
     self._addWatchedItem(parentItem)
     
     qdir = QDir(parentItem.dirName())
     
     if Preferences.getUI("BrowsersListHiddenFiles"):
         fileFilter = QDir.Filters(
             QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot)
     else:
         fileFilter = QDir.Filters(
             QDir.AllEntries | QDir.NoDot | QDir.NoDotDot)
     entryInfoList = qdir.entryInfoList(fileFilter)
     
     if len(entryInfoList) > 0:
         if repopulate:
             self.beginInsertRows(self.createIndex(
                 parentItem.row(), 0, parentItem),
                 0, len(entryInfoList) - 1)
         states = {}
         if self.project.vcs is not None:
             for f in entryInfoList:
                 fname = f.absoluteFilePath()
                 states[os.path.normcase(fname)] = 0
             dname = parentItem.dirName()
             self.project.vcs.clearStatusCache()
             states = self.project.vcs.vcsAllRegisteredStates(states, dname)
         
         for f in entryInfoList:
             if f.isDir():
                 node = ProjectBrowserDirectoryItem(
                     parentItem,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     parentItem.getProjectTypes()[0], False)
             else:
                 node = ProjectBrowserFileItem(
                     parentItem,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     parentItem.getProjectTypes()[0])
             if self.project.vcs is not None:
                 fname = f.absoluteFilePath()
                 if (
                     states[os.path.normcase(fname)] ==
                         self.project.vcs.canBeCommitted
                 ):
                     node.addVcsStatus(self.project.vcs.vcsName())
                     self.project.clearStatusMonitorCachedState(
                         f.absoluteFilePath())
                 else:
                     node.addVcsStatus(self.tr("local"))
             else:
                 node.addVcsStatus("")
             self._addItem(node, parentItem)
         if repopulate:
             self.endInsertRows()
Пример #6
0
    def show_video(self):
        directory = QDir(os.getcwd())
        directory.setFilter(QDir.Files | QDir.NoDotDot | QDir.NoDotAndDotDot)
        directory.setSorting(QDir.Time)
        set_filter = ["*.avi"]
        directory.setNameFilters(set_filter)

        for show in directory.entryInfoList():
            print("%s %s" % (show.size(), show.fileName()))
            out = show.fileName()
            break
        # print(1)
        if self.zone_cutted:
            # print(2)
            x1, y1, x2, y2 = get_zone_position()

            clip = VideoFileClip(out)
            cut_video = crop(clip, x1, y1, x2, y2)

            name_of_file = QFileInfo(out).baseName() + "_zone.avi"
            cut_video.write_videofile(name_of_file, codec='mpeg4', audio=False)

        else:
            # print(3)
            name_of_file = out
        # print(4)
        self.mediaPlayer.setMedia(
            QMediaContent(QUrl.fromLocalFile(os.getcwd() + "\\" + name_of_file))
        )
        # print(5)
        # self.mediaPlayer.setPlaybackRate()
        self.play()
Пример #7
0
def pre_process():
    #dirTrain1 = QDir('C:/Users/home/Desktop/mitos dataset/train/mitosis')
    dirTrain2 = QDir(P().saveCutMitosDir)
    imagesFilter = ['*.png', '*.tif', '*.bmp']

    #info1 = dirTrain1.entryInfoList(imagesFilter)
    info2 = dirTrain2.entryInfoList(imagesFilter)
    infoList = []
    #infoList.extend(info1)
    infoList.extend(info2)

    i = 0
    for fileInfo in infoList:
        i += 1
        imagePath = fileInfo.absoluteFilePath()
        basePath = fileInfo.absolutePath() + '/'
        basenameExt = os.path.basename(imagePath)
        baseName, _ = os.path.splitext(basenameExt)
        savePath = P().saveMitosisPreProcessed

        imbase = cv2.imread(imagePath)
        rows, cols, _ = imbase.shape
        imXMirror = cv2.flip(imbase, 1)

        cv2.imwrite(savePath + fileInfo.fileName(), imbase)
        cv2.imwrite(savePath + baseName + '-mirror.png', imXMirror)
        rotateImageAndSave(imbase, baseName, savePath)
        rotateImageAndSave(imXMirror, baseName + '-mirror', savePath)

        print('%d / %d' % (i, len(infoList)))
Пример #8
0
    def show_heatmap(self):
        # print("a")
        directory = QDir(os.getcwd())
        directory.setFilter(QDir.Files | QDir.NoDotDot | QDir.NoDotAndDotDot)
        directory.setSorting(QDir.Time)
        set_filter = ["*.jpg"]
        directory.setNameFilters(set_filter)
        # print("b")
        for show in directory.entryInfoList():
            print("%s %s" % (show.size(), show.fileName()))
            if "heatmap" in show.fileName():
                out = show.fileName()
                break
        # print("c")
        w = self.heatmapLabel.width()
        h = self.heatmapLabel.height()
        # print("d")
        # print("%r", self.zone_cutted)
        if self.zone_cutted:
            x1, y1, x2, y2 = get_zone_position()

            imageObject = Image.open(out)
            cropped = imageObject.crop((x1, y1, x2, y2))
            name_of_file = QFileInfo(out).baseName() + "_zone.jpg"
            cropped.save(name_of_file)

            pixmap = QPixmap(name_of_file)
        else:
            pixmap = QPixmap(out)
        # print("e")
        pixmap = pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio)
        self.heatmapLabel.setPixmap(pixmap)
Пример #9
0
	def getExportExtensionsList(self):
		extensions = []
		for extsprefix in datadirs:
			extsdir = QDir(extsprefix+'/export-extensions/')
			if extsdir.exists():
				for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'],
				QDir.Files | QDir.Readable):
					extensions.append(self.readExtension(fileInfo.filePath()))
		locale = QLocale.system().name()
		self.extensionActions = []
		for extension in extensions:
			try:
				if ('Name[%s]' % locale) in extension:
					name = extension['Name[%s]' % locale]
				elif ('Name[%s]' % locale.split('_')[0]) in extension:
					name = extension['Name[%s]' % locale.split('_')[0]]
				else:
					name = extension['Name']
				data = {}
				for prop in ('FileFilter', 'DefaultExtension', 'Exec'):
					if 'X-ReText-'+prop in extension:
						data[prop] = extension['X-ReText-'+prop]
					elif prop in extension:
						data[prop] = extension[prop]
					else:
						data[prop] = ''
				action = self.act(name, trig=self.extensionFunction(data))
				if 'Icon' in extension:
					action.setIcon(self.actIcon(extension['Icon']))
				mimetype = extension['MimeType'] if 'MimeType' in extension else None
			except KeyError:
				print('Failed to parse extension: Name is required', file=sys.stderr)
			else:
				self.extensionActions.append((action, mimetype))
Пример #10
0
    def _load_mitos(self):
        dir = QDir(self._mitos_folder)
        list = dir.entryInfoList(imagesFilter)

        for entry in list:
            path = entry.absoluteFilePath()
            im = cv2.imread(path)
            im = self._resize(im)
            self._mitos_list.append(self._preprocess(im))
Пример #11
0
def removeDir(dirName):
    d = QDir(dirName)
    if d.exists():
        for info in d.entryInfoList(QDir.Dirs | QDir.Files | QDir.NoDotAndDotDot):
            if info.isDir():
                removeDir(info.absoluteFilePath())
            else:
                d.remove(info.fileName())
        d.rmdir(dirName)
Пример #12
0
 def populateProjectDirectoryItem(self, parentItem, repopulate=False):
     """
     Public method to populate a directory item's subtree.
     
     @param parentItem reference to the directory item to be populated
     @param repopulate flag indicating a repopulation (boolean)
     """
     self._addWatchedItem(parentItem)
     
     qdir = QDir(parentItem.dirName())
     
     if Preferences.getUI("BrowsersListHiddenFiles"):
         filter = QDir.Filters(QDir.AllEntries |
                               QDir.Hidden |
                               QDir.NoDotAndDotDot)
     else:
         filter = QDir.Filters(QDir.AllEntries | QDir.NoDot | QDir.NoDotDot)
     entryInfoList = qdir.entryInfoList(filter)
     
     if len(entryInfoList) > 0:
         if repopulate:
             self.beginInsertRows(self.createIndex(
                 parentItem.row(), 0, parentItem),
                 0, len(entryInfoList) - 1)
         states = {}
         if self.project.vcs is not None:
             for f in entryInfoList:
                 fname = f.absoluteFilePath()
                 states[os.path.normcase(fname)] = 0
             dname = parentItem.dirName()
             self.project.vcs.clearStatusCache()
             states = self.project.vcs.vcsAllRegisteredStates(states, dname)
         
         for f in entryInfoList:
             if f.isDir():
                 node = ProjectBrowserDirectoryItem(
                     parentItem,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     parentItem.getProjectTypes()[0], False)
             else:
                 node = ProjectBrowserFileItem(
                     parentItem,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     parentItem.getProjectTypes()[0])
             if self.project.vcs is not None:
                 fname = f.absoluteFilePath()
                 if states[os.path.normcase(fname)] == \
                         self.project.vcs.canBeCommitted:
                     node.addVcsStatus(self.project.vcs.vcsName())
                     self.project.clearStatusMonitorCachedState(
                         f.absoluteFilePath())
                 else:
                     node.addVcsStatus(self.tr("local"))
             self._addItem(node, parentItem)
         if repopulate:
             self.endInsertRows()
Пример #13
0
 def start_worker(self):
     file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
     dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
     while not self._cancel and not self.queue.empty():
         current_dir = QDir(self.queue.get())
         # Skip not readable dirs!
         if not current_dir.isReadable():
             continue
         # Collect all sub dirs!
         if self.recursive:
             current_sub_dirs = current_dir.entryInfoList(dir_filter)
             for one_dir in current_sub_dirs:
                 self.queue.put(one_dir.absoluteFilePath())
         # All files in sub_dir first apply the filters
         current_files = current_dir.entryInfoList(self.filters,
                                                   file_filter)
         # Process all files in current dir
         for one_file in current_files:
             self._grep_file(one_file.absoluteFilePath(),
                             one_file.fileName())
Пример #14
0
    def start_worker(self):
        file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable
        dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable
        while not self._cancel and not self.queue.empty():
            current_dir = QDir(self.queue.get())
            # Skip not readable dirs!
            if not current_dir.isReadable():
                continue
            # Collect all sub dirs!
            if self.recursive:
                current_sub_dirs = current_dir.entryInfoList(dir_filter)
                for one_dir in current_sub_dirs:
                    self.queue.put(one_dir.absoluteFilePath())
            # All files in sub_dir first apply the filters
            current_files = current_dir.entryInfoList(
                self.filters, file_filter)
            # Process all files in current dir
            for one_file in current_files:
                self._grep_file(
                    one_file.absoluteFilePath(), one_file.fileName())

        self.finished.emit()
Пример #15
0
    def scanDir(self, path: str):
        """
        Scan the image's directory.
        """

        # Stores all files inside the directory.
        imageDir = QDir(path)
        imageDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.Readable)

        # Add files' absolute path to list.
        self.dirImages = [
            file.absoluteFilePath() for file in imageDir.entryInfoList()
            if file.suffix() in SUPPORTED_EXTENSIONS
        ]
Пример #16
0
    def recursive(self, path, search_string, paths):
        directory = QDir(path)
        directory.setFilter(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot)
        directory.setSorting(QDir.DirsLast)

        for entry in directory.entryInfoList():
            entry_path = entry.absoluteFilePath()
            ignored = self.is_ignored(entry_path)
            if not ignored and entry.isFile() and entry_path.endswith('php'):
                current_path = entry_path[len(self.root) + 1:]

                if self.is_fuzzy(current_path, search_string):
                    paths.append(current_path)
            elif not ignored and entry.isDir():
                paths = self.recursive(entry_path, search_string, paths)

        return paths
Пример #17
0
    def show_counting(self):
        directory = QDir(os.getcwd())
        directory.setFilter(QDir.Files | QDir.NoDotDot | QDir.NoDotAndDotDot)
        directory.setSorting(QDir.Time)
        set_filter = ["*.jpg"]
        directory.setNameFilters(set_filter)

        for show in directory.entryInfoList():
            print("%s %s" % (show.size(), show.fileName()))
            if "graph" in show.fileName():
                out = show.fileName()
                break

        w = self.countingLabel.width()
        h = self.countingLabel.height()

        pixmap = QPixmap(out)
        pixmap = pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio)
        self.countingLabel.setPixmap(pixmap)
Пример #18
0
    def ensure_finish(self, dir):
        folder = QDir(dir)
        file_list = folder.entryInfoList(QDir.Files | QDir.CaseSensitive)
        bat_file_name = ''
        with open(self.transcript, 'r') as f:
            content = f.readlines()
            for line in content:
                if 'host' in line:
                    line = line.split()
                    host_name = line[1]
                    pid = line[3]
                    bat_file_name = 'cleanup-fluent-%s-%s.bat' % (host_name,
                                                                  pid)

        for i in file_list:
            if i.fileName() == bat_file_name:
                print('.bat address', i.absoluteFilePath())
                subprocess.call(i.absoluteFilePath(), shell=True)
        print('\nall finished')
        self.quit()
Пример #19
0
def getMetadataForFileList(filenames):
    '''Takes a list of filenames, returns a list of metadata associated with
    all files in that list that are readable tracks'''

    metadata = []
    for filename in filenames:
        info = QFileInfo(filename)
        if info.isDir() and info.isExecutable():
            print(filename)
            dir = QDir(filename)
            print(dir.entryList(QDir.AllEntries | QDir.NoDotAndDotDot))
            metadata.extend(
                getMetadataForFileList([
                    i.filePath()
                    for i in dir.entryInfoList(QDir.AllEntries
                                               | QDir.NoDotAndDotDot)
                ]))
        elif info.isFile() and info.isReadable():
            print(filename)
            metadata.extend(processFile(filename))
    return metadata
Пример #20
0
    def directoryChanged(self, path):
        """
        Public slot to handle the directoryChanged signal of the watcher.
        
        @param path path of the directory (string)
        """
        if path not in self.watchedItems:
            # just ignore the situation we don't have a reference to the item
            return

        if Preferences.getUI("BrowsersListHiddenFiles"):
            filter = QDir.Filters(QDir.AllEntries | QDir.Hidden
                                  | QDir.NoDotAndDotDot)
        else:
            filter = QDir.Filters(QDir.AllEntries | QDir.NoDot | QDir.NoDotDot)

        for itm in self.watchedItems[path]:
            oldCnt = itm.childCount()

            qdir = QDir(itm.dirName())

            entryInfoList = qdir.entryInfoList(filter)

            # step 1: check for new entries
            children = itm.children()
            for f in entryInfoList:
                fpath = Utilities.toNativeSeparators(f.absoluteFilePath())
                childFound = False
                for child in children:
                    if child.name() == fpath:
                        childFound = True
                        children.remove(child)
                        break
                if childFound:
                    continue

                cnt = itm.childCount()
                self.beginInsertRows(self.createIndex(itm.row(), 0, itm), cnt,
                                     cnt)
                if f.isDir():
                    node = ProjectBrowserDirectoryItem(
                        itm,
                        Utilities.toNativeSeparators(f.absoluteFilePath()),
                        itm.getProjectTypes()[0], False)
                else:
                    node = ProjectBrowserFileItem(
                        itm,
                        Utilities.toNativeSeparators(f.absoluteFilePath()),
                        itm.getProjectTypes()[0])
                self._addItem(node, itm)
                if self.project.vcs is not None:
                    self.project.vcs.clearStatusCache()
                    state = self.project.vcs.vcsRegisteredState(node.name())
                    if state == self.project.vcs.canBeCommitted:
                        node.addVcsStatus(self.project.vcs.vcsName())
                    else:
                        node.addVcsStatus(self.tr("local"))
                self.endInsertRows()

            # step 2: check for removed entries
            if len(entryInfoList) != itm.childCount():
                for row in range(oldCnt - 1, -1, -1):
                    child = itm.child(row)
                    childname = Utilities.fromNativeSeparators(child.name())
                    entryFound = False
                    for f in entryInfoList:
                        if f.absoluteFilePath() == childname:
                            entryFound = True
                            entryInfoList.remove(f)
                            break
                    if entryFound:
                        continue

                    self._removeWatchedItem(child)
                    self.beginRemoveRows(self.createIndex(itm.row(), 0, itm),
                                         row, row)
                    itm.removeChild(child)
                    self.endRemoveRows()
Пример #21
0
 def _vcsCheckout(self, export=False):
     """
     Protected slot used to create a local project from the repository.
     
     @param export flag indicating whether an export or a checkout
             should be performed
     """
     if not self.project or not self.project.checkDirty():
         return
     
     vcsSystemsDict = e5App().getObject(
         "PluginManager").getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(vcsSystemsDict.keys())
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         QCoreApplication.translate("VcsProjectHelper", "New Project"),
         QCoreApplication.translate(
             "VcsProjectHelper",
             "Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     
     selectedVcsSystem = None
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             selectedVcsSystem = vcsSystem
             break
     
     if not self.project.closeProject():
         return
     
     vcs = self.project.initVCS(selectedVcsSystem)
     if vcs is not None:
         vcsdlg = vcs.vcsNewProjectOptionsDialog()
         if vcsdlg.exec_() == QDialog.Accepted:
             projectdir, vcsDataDict = vcsdlg.getData()
             # edit VCS command options
             if vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     QCoreApplication.translate(
                         "VcsProjectHelper", "New Project"),
                     QCoreApplication.translate(
                         "VcsProjectHelper",
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     vcs.vcsSetOptions(codlg.getOptions())
             
             # create the project directory if it doesn't exist already
             if not os.path.isdir(projectdir):
                 try:
                     os.makedirs(projectdir)
                 except EnvironmentError:
                     E5MessageBox.critical(
                         self.parent(),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "Create project directory"),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "<p>The project directory <b>{0}</b> could not"
                             " be created.</p>").format(projectdir))
                     self.project.resetVCS()
                     return
             
             # create the project from the VCS
             vcs.vcsSetDataFromDict(vcsDataDict)
             if export:
                 ok = vcs.vcsExport(vcsDataDict, projectdir)
             else:
                 ok = vcs.vcsCheckout(vcsDataDict, projectdir, False)
             if ok:
                 projectdir = os.path.normpath(projectdir)
                 filters = ["*.e4p"]
                 d = QDir(projectdir)
                 plist = d.entryInfoList(filters)
                 if len(plist):
                     if len(plist) == 1:
                         self.project.openProject(
                             plist[0].absoluteFilePath())
                     else:
                         pfilenamelist = d.entryList(filters)
                         pfilename, ok = QInputDialog.getItem(
                             None,
                             QCoreApplication.translate(
                                 "VcsProjectHelper",
                                 "New project from repository"),
                             QCoreApplication.translate(
                                 "VcsProjectHelper",
                                 "Select a project file to open."),
                             pfilenamelist, 0, False)
                         if ok:
                             self.project.openProject(
                                 QFileInfo(d, pfilename).absoluteFilePath())
                     if export:
                         self.project.pdata["VCS"] = 'None'
                         self.project.vcs = self.project.initVCS()
                         self.project.setDirty(True)
                         self.project.saveProject()
                 else:
                     res = E5MessageBox.yesNo(
                         self.parent(),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "New project from repository"),
                         QCoreApplication.translate(
                             "VcsProjectHelper",
                             "The project retrieved from the repository"
                             " does not contain an eric project file"
                             " (*.e4p). Create it?"),
                         yesDefault=True)
                     if res:
                         self.project.ppath = projectdir
                         self.project.opened = True
                         
                         from Project.PropertiesDialog import (
                             PropertiesDialog
                         )
                         dlg = PropertiesDialog(self.project, False)
                         if dlg.exec_() == QDialog.Accepted:
                             dlg.storeData()
                             self.project.initFileTypes()
                             self.project.pdata["VCS"] = selectedVcsSystem
                             self.project.setDirty(True)
                             if self.project.pdata["MAINSCRIPT"]:
                                 ms = os.path.join(
                                     self.project.ppath,
                                     self.project.pdata["MAINSCRIPT"])
                                 if os.path.exists(ms):
                                     self.project.appendFile(ms)
                             else:
                                 ms = ""
                             self.project.newProjectAddFiles(ms)
                             self.project.createProjectManagementDir()
                             self.project.saveProject()
                             self.project.openProject(self.project.pfile)
                             if not export:
                                 res = E5MessageBox.yesNo(
                                     self.parent(),
                                     QCoreApplication.translate(
                                         "VcsProjectHelper",
                                         "New project from repository"),
                                     QCoreApplication.translate(
                                         "VcsProjectHelper",
                                         "Shall the project file be added"
                                         " to the repository?"),
                                     yesDefault=True)
                                 if res:
                                     self.project.vcs.vcsAdd(
                                         self.project.pfile)
             else:
                 E5MessageBox.critical(
                     self.parent(),
                     QCoreApplication.translate(
                         "VcsProjectHelper", "New project from repository"),
                     QCoreApplication.translate(
                         "VcsProjectHelper",
                         """The project could not be retrieved from"""
                         """ the repository."""))
                 self.project.resetVCS()
Пример #22
0
from PyQt5.QtCore import QDir
import os
import cv2

dirTrain1 = QDir('C:/Users/home/Desktop/mitos dataset eval/cutted/mitosis')
dirTrain2 = QDir('C:/Users/home/Desktop/mitos dataset eval/cutted/noMitos')

imagesFilter = ['*.png', '*.tif', '*.bmp']
infoList1 = dirTrain1.entryInfoList(imagesFilter)
infoList2 = dirTrain2.entryInfoList(imagesFilter)

for e in infoList1:
    filePath = e.absoluteFilePath()
    basenameExt = os.path.basename(filePath)
    baseName, _ = os.path.splitext(basenameExt)

    im = cv2.imread(filePath)
    savePath = dirTrain1.absolutePath() + '/' + baseName + '.png'
    cv2.imwrite(savePath, im)

for e in infoList2:
    filePath = e.absoluteFilePath()
    basenameExt = os.path.basename(filePath)
    baseName, _ = os.path.splitext(basenameExt)

    im = cv2.imread(filePath)
    cv2.imwrite(dirTrain2.absolutePath() + '/' + baseName + '.png', im)
Пример #23
0
 def listEntries(self, dir: QDir) -> [str]:
     dir.setNameFilters(["*.md"])
     fileNames = []
     for fileInfo in dir.entryInfoList():
         fileNames.append(fileInfo.completeBaseName())
     return fileNames
Пример #24
0
 def listEntries(self, dir: QDir) -> [str]:
     dir.setFilter(QDir.Dirs | QDir.NoDotAndDotDot)
     folderNames = []
     for fileInfo in dir.entryInfoList():
         folderNames.append(fileInfo.fileName())
     return folderNames
class Widgetss(object):

    #def __init__(self, parent=None):
    #super(Widgets, self).__init__(parent)

    #self.parent = parent

    #self.initUI()

    def setupUi(self, Form, imglist):

        #self.setWindowTitle("Image Gallary")
        #self.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint)
        #self.setFixedSize(682, 573)

        # ======================== WIDGETS ===========================

        framePrincipal = QFrame(Form)
        #framePrincipal.setFrameShape(QFrame.Box)
        #framePrincipal.setFrameShadow(QFrame.Sunken)
        #framePrincipal.setAutoFillBackground(True)
        #framePrincipal.setBackgroundRole(QPalette.Light)
        framePrincipal.setFixedSize(662, 503)
        framePrincipal.move(10, 10)

        frame = QFrame(framePrincipal)
        frame.setFixedSize(640, 480)
        frame.move(10, 10)

        self.labelImagen = QLabel(frame)
        self.labelImagen.setAlignment(Qt.AlignCenter)
        self.labelImagen.setGeometry(0, 0, 640, 480)
        # self.labelImagen.setScaledContents(True)

        self.labelImagenUno = QLabel(frame)
        self.labelImagenUno.setAlignment(Qt.AlignCenter)
        self.labelImagenUno.setGeometry(-650, 0, 640, 480)

        # =================== BOTONES (QPUSHBUTTON) ==================

        self.buttonCargar = QPushButton("Choose Image", Form)
        self.buttonCargar.setCursor(Qt.PointingHandCursor)
        self.buttonCargar.setFixedSize(325, 30)
        self.buttonCargar.move(10, 519)

        self.buttonEliminar = QPushButton("Delete Image", Form)
        self.buttonEliminar.setCursor(Qt.PointingHandCursor)
        self.buttonEliminar.setFixedSize(255, 30)
        self.buttonEliminar.move(345, 519)

        self.buttonAnterior = QPushButton("<", Form)
        self.buttonAnterior.setObjectName("Anterior")
        self.buttonAnterior.setToolTip("Imagen anterior")
        self.buttonAnterior.setCursor(Qt.PointingHandCursor)
        self.buttonAnterior.setFixedSize(30, 30)
        self.buttonAnterior.move(607, 519)

        self.buttonSiguiente = QPushButton(">", Form)
        self.buttonSiguiente.setObjectName("Siguiente")
        self.buttonSiguiente.setToolTip("Imagen siguiente")
        self.buttonSiguiente.setCursor(Qt.PointingHandCursor)
        self.buttonSiguiente.setFixedSize(30, 30)
        self.buttonSiguiente.move(642, 519)

        # ===================== CONECTAR SEÑALES =====================

        self.buttonCargar.clicked.connect(self.Cargar)
        self.buttonEliminar.clicked.connect(self.Eliminar)
        self.buttonAnterior.clicked.connect(self.anteriorSiguiente)
        self.buttonSiguiente.clicked.connect(self.anteriorSiguiente)

        # Establecer los valores predeterminados
        self.position = int
        self.estadoAnterior, self.estadoSiguiente = False, False
        self.carpetaActual = QDir()
        self.imagenesCarpeta = []
        self.imagenesCarpeta = imglist

# ======================= FUNCIONES ==============================

    def bloquearBotones(self, bool):
        self.buttonCargar.setEnabled(bool)
        self.buttonEliminar.setEnabled(bool)
        self.buttonAnterior.setEnabled(bool)
        self.buttonSiguiente.setEnabled(bool)

    def Mostrar(self, label, imagen, nombre, posicionX=650):
        imagen = QPixmap.fromImage(imagen)

        # Escalar imagen a 640x480 si el ancho es mayor a 640 o el alto mayor a 480
        if imagen.width() > 640 or imagen.height() > 480:
            imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio,
                                   Qt.SmoothTransformation)
            #print(str(imagen.width())+" Width ")
            #print(str(imagen.height())+" Height ")

        # Mostrar imagen
        label.setPixmap(imagen)

        # Animación (al finalizar la animación se muestra en la barra de estado el nombre y la extensión de la imagen
        # y se desbloquean los botones).
        self.animacionMostar = QPropertyAnimation(label, b"geometry")
        self.animacionMostar.finished.connect(
            lambda: self.bloquearBotones(True))
        self.animacionMostar.setDuration(200)
        self.animacionMostar.setStartValue(QRect(posicionX, 0, 640, 480))
        self.animacionMostar.setEndValue(QRect(0, 0, 640, 480))
        self.animacionMostar.start(QAbstractAnimation.DeleteWhenStopped)

    def Limpiar(self,
                labelConImagen,
                labelMostrarImagen,
                imagen,
                nombre,
                posicionInternaX,
                posicionX=None):
        def Continuar(estado):
            if estado:
                if posicionX:
                    self.Mostrar(labelMostrarImagen, imagen, nombre, posicionX)
                else:
                    self.Mostrar(labelMostrarImagen, imagen, nombre)

        self.animacionLimpiar = QPropertyAnimation(labelConImagen, b"geometry")
        self.animacionLimpiar.finished.connect(lambda: labelConImagen.clear())
        self.animacionLimpiar.setDuration(200)
        #self.animacionLimpiar.valueChanged.connect(lambda x: print(x))
        self.animacionLimpiar.stateChanged.connect(Continuar)
        self.animacionLimpiar.setStartValue(QRect(0, 0, 640, 480))
        self.animacionLimpiar.setEndValue(QRect(posicionInternaX, 0, 640, 480))
        self.animacionLimpiar.start(QAbstractAnimation.DeleteWhenStopped)

    def Cargar(self):
        """
        nombreImagen, _ = QFileDialog.getOpenFileName(Form, "Seleccionar imagen",
                                                      QDir.currentPath(),
                                                      "Archivos de imagen (*.jpg *.png *.ico *.bmp)")

        print(type(nombreImagen))

        if nombreImagen:
            # Verify that QLabel has an image
            labelConImagen = ""
            if self.labelImagen.pixmap():
                labelConImagen = self.labelImagen
            elif self.labelImagenUno.pixmap():
                labelConImagen = self.labelImagenUno
                
            imagen = QImage(nombreImagen)
            if imagen.isNull():
                if labelConImagen:
                    self.Eliminar()
                    
                QMessageBox.information(self, "Visor de imágenes",
                                        "No se puede cargar %s." % nombreImagen)
                return
            
            # Get path of folder containing selected image
            self.carpetaActual = QDir(QFileInfo(nombreImagen).absoluteDir().path())

            # Get the path and name of the images that are in the folder of
            # the selected image
            imagenes = self.carpetaActual.entryInfoList(["*.jpg", "*.png", "*.ico", "*.bmp"],
                                                        QDir.Files, QDir.Name)


            self.imagenesCarpeta = [imagen.absoluteFilePath() for imagen in imagenes]
            """
        #print(str(self.imagenesCarpeta))
        self.position = self.imagenesCarpeta.index(nombreImagen)
        self.estadoAnterior = True if self.position == 0 else False
        self.estadoSiguiente = True if self.position == len(
            self.imagenesCarpeta) - 1 else False

        # Función encargada de bloquear o desbloquear los botones
        self.bloquearBotones(False)

        # Nombre y extensión de la imagen
        nombre = QFileInfo(nombreImagen).fileName()

        if labelConImagen:
            posicionInternaX = -650
            labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap(
            ) else self.labelImagenUno
            self.Limpiar(labelConImagen, labelMostrarImagen, imagen, nombre,
                         posicionInternaX)
        else:
            self.Mostrar(self.labelImagen, imagen, nombre)

    def Eliminar(self):
        def establecerValores():
            labelConImagen.clear()
            labelConImagen.move(0, 0)

            # Limpiar la barra de estado
            #self.parent.statusBar.clearMessage()

            # Establecer los valores predeterminados
            self.position = int
            self.estadoAnterior, self.estadoSiguiente = False, False
            self.carpetaActual = QDir()
            self.imagenesCarpeta.clear()

            self.bloquearBotones(True)

        # Verificar que QLabel tiene imagen
        labelConImagen = ""
        if self.labelImagen.pixmap():
            labelConImagen = self.labelImagen
        elif self.labelImagenUno.pixmap():
            labelConImagen = self.labelImagenUno

        if labelConImagen:
            self.bloquearBotones(False)

            self.animacionEliminar = QPropertyAnimation(
                labelConImagen, b"geometry")
            self.animacionEliminar.finished.connect(establecerValores)
            self.animacionEliminar.setDuration(200)
            self.animacionEliminar.setStartValue(QRect(0, 0, 640, 480))
            self.animacionEliminar.setEndValue(QRect(-650, 0, 640, 480))
            self.animacionEliminar.start(QAbstractAnimation.DeleteWhenStopped)

    def anteriorSiguiente(self):
        if self.imagenesCarpeta:
            widget = Form.sender().objectName()

            if widget == "Anterior":
                self.estadoAnterior = True if self.position == 0 else False
                self.estadoSiguiente = False

                self.position -= 1 if self.position > 0 else 0
                posicionInternaX, posicionX = 650, -650
            else:
                self.estadoSiguiente = True if self.position == len(
                    self.imagenesCarpeta) - 1 else False
                self.estadoAnterior = False

                self.position += 1 if self.position < len(
                    self.imagenesCarpeta) - 1 else 0
                posicionInternaX, posicionX = -650, 650

            if self.estadoAnterior or self.estadoSiguiente:
                return
            else:
                imagen = self.imagenesCarpeta[self.position]

                # Verificar que la carpeta que contiene la imagene exista
                if not QDir(self.carpetaActual).exists():
                    self.Eliminar()
                    return
                elif not QFile.exists(imagen):
                    # Obtener la ruta y el nombre de las imagenes que se encuentren en la
                    # carpeta de la imagen seleccionada
                    imagenes = self.carpetaActual.entryInfoList(
                        ["*.jpg", "*.png", "*.ico", "*.bmp"], QDir.Files,
                        QDir.Name)

                    if not imagenes:
                        self.Eliminar()
                        return

                    self.imagenesCarpeta = [
                        imagen.absoluteFilePath() for imagen in imagenes
                    ]

                    self.position = randint(0, len(self.imagenesCarpeta) - 1)
                    self.estadoAnterior = True if self.position == 0 else False
                    self.estadoSiguiente = True if self.position == len(
                        self.imagenesCarpeta) - 1 else False
                elif QImage(imagen).isNull():
                    del self.imagenesCarpeta[self.position]

                    if not self.imagenesCarpeta:
                        self.Eliminar()
                        return

                    self.position = randint(0, len(self.imagenesCarpeta) - 1)
                    self.estadoAnterior = True if self.position == 0 else False
                    self.estadoSiguiente = True if self.position == len(
                        self.imagenesCarpeta) - 1 else False

                imagen = self.imagenesCarpeta[self.position]

                if self.labelImagen.pixmap():
                    labelConImagen = self.labelImagen
                elif self.labelImagenUno.pixmap():
                    labelConImagen = self.labelImagenUno

                # Function responsible for locking or unlocking buttons
                self.bloquearBotones(False)

                # Image name and extension
                nombre = QFileInfo(imagen).fileName()

                # Label in which the image will be displayed
                labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap(
                ) else self.labelImagenUno

                # Remove current image and show next
                self.Limpiar(labelConImagen, labelMostrarImagen,
                             QImage(imagen), nombre, posicionInternaX,
                             posicionX)
Пример #26
0
class Widgets(QWidget):

    def __init__(self, parent=None):
        super(Widgets, self).__init__(parent)
        self.parent = parent
        self.initUI()

    def initUI(self):

      # ======================== WIDGETS ===========================

        framePrincipal = QFrame(self)
        framePrincipal.setFrameShape(QFrame.Box)
        framePrincipal.setFrameShadow(QFrame.Sunken)
        framePrincipal.setAutoFillBackground(True)
        framePrincipal.setBackgroundRole(QPalette.Light)
        framePrincipal.setFixedSize(640,480)
        framePrincipal.move(10, 10)
        frame = QFrame(framePrincipal)
        frame.setFixedSize(2000, 2000)
        frame.move(10, 10)

        self.labelImagen = QLabel(frame)
        self.labelImagen.setAlignment(Qt.AlignCenter)
        self.labelImagen.setGeometry(0, 0, 640, 480)        
        self.labelImagenUno = QLabel(frame)
        self.labelImagenUno.setAlignment(Qt.AlignCenter)
        self.labelImagenUno.setGeometry(-650, 0, 640, 480)

      # =================== BOTONES (QPUSHBUTTON) ==================

        self.buttonCargar = QPushButton("Cargar imagen", self)
        self.buttonCargar.setCursor(Qt.PointingHandCursor)
        self.buttonCargar.setFixedSize(100, 30)
        self.buttonCargar.move(10, 519)
        self.buttonEliminar = QPushButton("Eliminar imagen", self)
        self.buttonEliminar.setCursor(Qt.PointingHandCursor)
        self.buttonEliminar.setFixedSize(100, 30)
        self.buttonEliminar.move(120, 519)
        self.buttonAnterior = QPushButton("<", self)
        self.buttonAnterior.setObjectName("Anterior")
        self.buttonAnterior.setToolTip("Imagen anterior")
        self.buttonAnterior.setCursor(Qt.PointingHandCursor)
        self.buttonAnterior.setFixedSize(30, 30)
        self.buttonAnterior.move(230, 519)        
        self.buttonSiguiente = QPushButton(">", self)
        self.buttonSiguiente.setObjectName("Siguiente")
        self.buttonSiguiente.setToolTip("Imagen siguiente")
        self.buttonSiguiente.setCursor(Qt.PointingHandCursor)
        self.buttonSiguiente.setFixedSize(30, 30)
        self.buttonSiguiente.move(265, 519)

        self.buttonCarpeta1= QPushButton("Carpeta 1", self)
        self.buttonCarpeta1.setObjectName("Carpeta1")
        self.buttonCarpeta1.setToolTip("Guardar en Carpeta 1")
        self.buttonCarpeta1.setCursor(Qt.PointingHandCursor)
        self.buttonCarpeta1.setFixedSize(160,30)
        self.buttonCarpeta1.move(300,519)

        self.buttonCarpeta2= QPushButton("Carpeta 2", self)
        self.buttonCarpeta2.setObjectName("Carpeta2")
        self.buttonCarpeta2.setToolTip("Guardar en Carpeta 2")
        self.buttonCarpeta2.setCursor(Qt.PointingHandCursor)
        self.buttonCarpeta2.setFixedSize(160,30)
        self.buttonCarpeta2.move(465,519)

      # ===================== CONECTAR SEÑALES =====================

        self.buttonCargar.clicked.connect(self.Cargar)
        self.buttonEliminar.clicked.connect(self.Eliminar)
        self.buttonAnterior.clicked.connect(self.anteriorSiguiente)
        self.buttonSiguiente.clicked.connect(self.anteriorSiguiente)
        self.buttonCarpeta1.clicked.connect(self.GuardarCarpeta1)
        self.buttonCarpeta2.clicked.connect(self.GuardarCarpeta2)
    

        # Establecer los valores predeterminados

        self.posicion = int
        self.estadoAnterior, self.estadoSiguiente = False, False
        self.carpetaActual = QDir()
        self.imagenesCarpeta = []

  # ======================= FUNCIONES ==============================

    def bloquearBotones(self, bool):
        self.buttonCargar.setEnabled(bool)
        self.buttonEliminar.setEnabled(bool)
        self.buttonAnterior.setEnabled(bool)
        self.buttonSiguiente.setEnabled(bool)
        self.buttonCarpeta1.setEnabled(bool)
        self.buttonCarpeta2.setEnabled(bool)

    def Mostrar (self, label, imagen, nombre, posicionX=650):
        imagen = QPixmap.fromImage(imagen)

        # Escalar imagen a 640x480 si el ancho es mayor a 640 o el alto mayor a 480
        if imagen.width() > 640 or imagen.height() > 480:
            imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        if imagen.width() < 640 or imagen.height() < 480:
            imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio, Qt.SmoothTransformation)

        # Mostrar imagen
        label.setPixmap(imagen)

        # Animación (al finalizar la animación se muestra en la barra de estado el nombre y la extensión de la imagen
        # y se desbloquean los botones).       
        self.animacionMostar = QPropertyAnimation(label, b"geometry")
        self.animacionMostar.finished.connect(lambda: (self.parent.statusBar.showMessage(nombre), self.bloquearBotones(True)))
        self.animacionMostar.setDuration(200)
        self.animacionMostar.setStartValue(QRect(posicionX, 0, 640, 480))
        self.animacionMostar.setEndValue(QRect(0, 0, 640, 480))
        self.animacionMostar.start(QAbstractAnimation.DeleteWhenStopped)

    def Limpiar(self, labelConImagen, labelMostrarImagen, imagen, nombre, posicionInternaX, posicionX=None):

        def Continuar(estado):
            if estado:
                if posicionX:
                    self.Mostrar(labelMostrarImagen, imagen, nombre, posicionX)
                else:
                    self.Mostrar(labelMostrarImagen, imagen, nombre)

        self.animacionLimpiar = QPropertyAnimation(labelConImagen, b"geometry")
        self.animacionLimpiar.finished.connect(lambda: labelConImagen.clear())
        self.animacionLimpiar.setDuration(200)

        # self.animacionLimpiar.valueChanged.connect(lambda x: print(x))
        self.animacionLimpiar.stateChanged.connect(Continuar)
        self.animacionLimpiar.setStartValue(QRect(0, 0, 640, 480))
        self.animacionLimpiar.setEndValue(QRect(posicionInternaX, 0, 640, 480))
        self.animacionLimpiar.start(QAbstractAnimation.DeleteWhenStopped)

    def Cargar(self):
        nombreImagen, _ = QFileDialog.getOpenFileName(self, "Seleccionar imagen", QDir.currentPath(),"Archivos de imagen (*.jpg *.png *.ico *.bmp)")
        if nombreImagen:
            # Verificar que QLabel tiene imagen
            labelConImagen = ""
            if self.labelImagen.pixmap():
                labelConImagen = self.labelImagen
            elif self.labelImagenUno.pixmap():
                labelConImagen = self.labelImagenUno
            # Si no hay imagenes disponibles marcar error
            imagen = QImage(nombreImagen)
            if imagen.isNull():
                if labelConImagen:
                    self.Eliminar()

                QMessageBox.information(self, "Visor de imágenes", "No se puede cargar %s." % nombreImagen)
                return
            # Obtener ruta de la carpeta que contiene la imagen seleccionada
            self.carpetaActual = QDir(QFileInfo(nombreImagen).absoluteDir().path())
            

            # Obtener la ruta y el nombre de las imagenes que se encuentren en la carpeta de
            # la imagen seleccionada
            imagenes = self.carpetaActual.entryInfoList(["*.jpg", "*.png", "*.ico", "*.bmp"], QDir.Files, QDir.Name)
            self.imagenesCarpeta = [imagen.absoluteFilePath() for imagen in imagenes]
            self.posicion = self.imagenesCarpeta.index(nombreImagen)
            self.estadoAnterior = True if self.posicion == 0 else False
            self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False

            # Función encargada de bloquear o desbloquear los botones
            self.bloquearBotones(False)

            # Nombre y extensión de la imagen
            nombre = QFileInfo(nombreImagen).fileName()
            

            
            if labelConImagen:
                posicionInternaX = -650
                labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap() else self.labelImagenUno
                self.Limpiar(labelConImagen, labelMostrarImagen, imagen, nombre, posicionInternaX)

            else:
                self.Mostrar(self.labelImagen, imagen, nombre)
        print(os.path.abspath("Proyecto/Carpeta1"))
        
        print(nombre)
    
    def GuardarCarpeta1(self):
        Destino=os.path.abspath("Proyecto1/Carpeta1")
        i=random.randrange(10000000000)
        if self.labelImagen.pixmap():
            rt=self.labelImagen.pixmap()
            
            if (os.path.exists("Proyecto1/Carpeta1/")):
                rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
                

             
        elif self.labelImagenUno.pixmap():
            rt=self.labelImagenUno.pixmap()
            if (os.path.exists(Destino)):
                rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
            
                

                

            

    def GuardarCarpeta2(self):
        Destino=os.path.abspath("Proyecto1/Carpeta2")
        i=random.randrange(10000000000)
        if self.labelImagen.pixmap():
            rt=self.labelImagen.pixmap()
            if (os.path.exists("Proyecto1/Carpeta2/")):
                rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
                
        elif self.labelImagenUno.pixmap():
            rt=self.labelImagenUno.pixmap()
            if (os.path.exists(Destino)):
                rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)

            
    
        

    def Eliminar(self):
        def establecerValores():
            labelConImagen.clear()
            labelConImagen.move(0, 0)

            # Limpiar la barra de estado
            self.parent.statusBar.clearMessage()

            # Establecer los valores predeterminados
            self.posicion = int
            self.estadoAnterior, self.estadoSiguiente = False, False
            self.carpetaActual = QDir()
            self.imagenesCarpeta.clear()
            self.bloquearBotones(True)

        # Verificar que QLabel tiene imagen
        labelConImagen = ""
        if self.labelImagen.pixmap():
            labelConImagen = self.labelImagen

        elif self.labelImagenUno.pixmap():
            labelConImagen = self.labelImagenUno
        
        if labelConImagen:
            self.bloquearBotones(False)
            self.animacionEliminar = QPropertyAnimation(labelConImagen, b"geometry")
            self.animacionEliminar.finished.connect(establecerValores)
            self.animacionEliminar.setDuration(200)
            self.animacionEliminar.setStartValue(QRect(0, 0, 640, 480))
            self.animacionEliminar.setEndValue(QRect(-650, 0, 640, 480))
            self.animacionEliminar.start(QAbstractAnimation.DeleteWhenStopped)

    def anteriorSiguiente(self):
        if self.imagenesCarpeta:
            widget = self.sender().objectName()

            if widget == "Anterior":
                self.estadoAnterior = True if self.posicion == 0 else False
                self.estadoSiguiente = False
                self.posicion -= 1 if self.posicion > 0 else 0
                posicionInternaX, posicionX = 650, -650 

            else:
                self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
                self.estadoAnterior = False
                self.posicion += 1 if self.posicion < len(self.imagenesCarpeta)-1 else 0
                posicionInternaX, posicionX = -650, 650 

            if self.estadoAnterior or self.estadoSiguiente:
                return
            else:
                imagen = self.imagenesCarpeta[self.posicion]

                # Verificar que la carpeta que contiene la imagene exista
                if not QDir(self.carpetaActual).exists():
                    self.Eliminar()
                    return

                elif not QFile.exists(imagen):
                    # Obtener la ruta y el nombre de las imagenes que se encuentren en la
                    # carpeta de la imagen seleccionada
                    imagenes = self.carpetaActual.entryInfoList(["*.jpg", "*.png", "*.ico", "*.bmp"],QDir.Files, QDir.Name)

                    if not imagenes:
                        self.Eliminar()
                        return

                    self.imagenesCarpeta = [imagen.absoluteFilePath() for imagen in imagenes]
                    self.posicion = randint(0, len(self.imagenesCarpeta)-1)
                    self.estadoAnterior = True if self.posicion == 0 else False
                    self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
                elif QImage(imagen).isNull():
                    del self.imagenesCarpeta[self.posicion]
                    if not self.imagenesCarpeta:
                        self.Eliminar()
                        return

                    self.posicion = randint(0, len(self.imagenesCarpeta)-1)
                    self.estadoAnterior = True if self.posicion == 0 else False
                    self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
                imagen = self.imagenesCarpeta[self.posicion]
                if self.labelImagen.pixmap():
                    labelConImagen = self.labelImagen
                elif self.labelImagenUno.pixmap():
                    labelConImagen = self.labelImagenUno

                # Función encargada de bloquear o desbloquear los botones
                self.bloquearBotones(False)

                # Nombre y extensión de la imagen
                nombre = QFileInfo(imagen).fileName()

                # Label en el que se va a mostrar la imagen
                labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap() else self.labelImagenUno

                # Quitar la imagen actual y mostrar la siguiente
                self.Limpiar(labelConImagen, labelMostrarImagen, QImage(imagen), nombre, posicionInternaX, posicionX)                             
Пример #27
0
 def directoryChanged(self, path):
     """
     Public slot to handle the directoryChanged signal of the watcher.
     
     @param path path of the directory (string)
     """
     if path not in self.watchedItems:
         # just ignore the situation we don't have a reference to the item
         return
     
     if Preferences.getUI("BrowsersListHiddenFiles"):
         filter = QDir.Filters(QDir.AllEntries |
                               QDir.Hidden |
                               QDir.NoDotAndDotDot)
     else:
         filter = QDir.Filters(QDir.AllEntries | QDir.NoDot | QDir.NoDotDot)
     
     for itm in self.watchedItems[path]:
         oldCnt = itm.childCount()
         
         qdir = QDir(itm.dirName())
         
         entryInfoList = qdir.entryInfoList(filter)
         
         # step 1: check for new entries
         children = itm.children()
         for f in entryInfoList:
             fpath = Utilities.toNativeSeparators(f.absoluteFilePath())
             childFound = False
             for child in children:
                 if child.name() == fpath:
                     childFound = True
                     children.remove(child)
                     break
             if childFound:
                 continue
             
             cnt = itm.childCount()
             self.beginInsertRows(
                 self.createIndex(itm.row(), 0, itm), cnt, cnt)
             if f.isDir():
                 node = ProjectBrowserDirectoryItem(
                     itm,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     itm.getProjectTypes()[0],
                     False)
             else:
                 node = ProjectBrowserFileItem(
                     itm,
                     Utilities.toNativeSeparators(f.absoluteFilePath()),
                     itm.getProjectTypes()[0])
             self._addItem(node, itm)
             if self.project.vcs is not None:
                 self.project.vcs.clearStatusCache()
                 state = self.project.vcs.vcsRegisteredState(node.name())
                 if state == self.project.vcs.canBeCommitted:
                     node.addVcsStatus(self.project.vcs.vcsName())
                 else:
                     node.addVcsStatus(self.tr("local"))
             self.endInsertRows()
         
         # step 2: check for removed entries
         if len(entryInfoList) != itm.childCount():
             for row in range(oldCnt - 1, -1, -1):
                 child = itm.child(row)
                 childname = Utilities.fromNativeSeparators(child.name())
                 entryFound = False
                 for f in entryInfoList:
                     if f.absoluteFilePath() == childname:
                         entryFound = True
                         entryInfoList.remove(f)
                         break
                 if entryFound:
                     continue
                 
                 self._removeWatchedItem(child)
                 self.beginRemoveRows(
                     self.createIndex(itm.row(), 0, itm), row, row)
                 itm.removeChild(child)
                 self.endRemoveRows()
Пример #28
0
 def __loadDirectory(self):
     """
     Private slot loading the directory and preparing the listing page.
     """
     dir = QDir(self.url().toLocalFile())
     dirItems = dir.entryInfoList(
         QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot,
         QDir.Name | QDir.DirsFirst)
     
     u = self.url()
     if not u.path().endswith("/"):
         u.setPath(u.path() + "/")
     
     baseUrl = self.url().toString()
     basePath = u.path()
     
     linkClasses = {}
     iconSize = QWebSettings.globalSettings().fontSize(
         QWebSettings.DefaultFontSize)
     
     parent = u.resolved(QUrl(".."))
     if parent.isParentOf(u):
         icon = UI.PixmapCache.getIcon("up.png")
         linkClasses["link_parent"] = \
             self.__cssLinkClass(icon, iconSize).format("link_parent")
         parentStr = self.tr(
             """  <p><a class="link_parent" href="{0}">"""
             """Change to parent directory</a></p>"""
         ).format(parent.toString())
     else:
         parentStr = ""
     
     row = \
         """    <tr class="{0}">"""\
         """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\
         """<td class="size">{4}</td>"""\
         """<td class="modified">{5}</td>"""\
         """</tr>\n"""
     table = self.tr(
         """    <tr>"""
         """<th align="left">Name</th>"""
         """<th>Size</th>"""
         """<th align="left">Last modified</th>"""
         """</tr>\n"""
     )
     
     i = 0
     for item in dirItems:
         name = item.fileName()
         if item.isDir() and not name.endswith("/"):
             name += "/"
         child = u.resolved(QUrl(name.replace(":", "%3A")))
         
         if item.isFile():
             size = item.size()
             unit = 0
             while size:
                 newSize = size // 1024
                 if newSize and unit < len(self.__units):
                     size = newSize
                     unit += 1
                 else:
                     break
             
             sizeStr = self.tr("{0} {1}", "size unit")\
                 .format(size, self.__units[unit])
             linkClass = "link_file"
             if linkClass not in linkClasses:
                 icon = UI.PixmapCache.getIcon("fileMisc.png")
                 linkClasses[linkClass] = \
                     self.__cssLinkClass(icon, iconSize).format(linkClass)
         else:
             sizeStr = ""
             linkClass = "link_dir"
             if linkClass not in linkClasses:
                 icon = UI.PixmapCache.getIcon("dirClosed.png")
                 linkClasses[linkClass] = \
                     self.__cssLinkClass(icon, iconSize).format(linkClass)
         table += row.format(
             i == 0 and "odd" or "even",
             linkClass,
             child.toString(),
             Utilities.html_encode(item.fileName()),
             sizeStr,
             item.lastModified().toString("yyyy-MM-dd hh:mm"),
         )
         i = 1 - i
     
     content = dirListPage_html.format(
         Utilities.html_encode(baseUrl),
         "".join(linkClasses.values()),
         self.tr("Listing of {0}").format(basePath),
         parentStr,
         table
     )
     self.__content = QByteArray(content.encode("utf8"))
     self.__content.append(512 * b' ')
     
     self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
     self.setHeader(
         QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8")
     self.setHeader(
         QNetworkRequest.ContentLengthHeader, self.__content.size())
     self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
     self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
     self.metaDataChanged.emit()
     self.downloadProgress.emit(
         self.__content.size(), self.__content.size())
     self.readyRead.emit()
     self.finished.emit()
Пример #29
0
def listFiles(folderPath, filters=[]):
    folder = QDir(folderPath)
    fileList = folder.entryInfoList(filters)
    return fileList
Пример #30
0
 def _vcsCheckout(self, export=False):
     """
     Protected slot used to create a local project from the repository.
     
     @param export flag indicating whether an export or a checkout
             should be performed
     """
     if not self.project.checkDirty():
         return
     
     vcsSystemsDict = e5App().getObject("PluginManager")\
         .getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(vcsSystemsDict.keys())
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         self.tr("New Project"),
         self.tr("Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             break
     
     if not self.project.closeProject():
         return
     
     self.project.pdata["VCS"] = [vcsSystem]
     self.project.vcs = self.project.initVCS(vcsSystem)
     if self.project.vcs is not None:
         vcsdlg = self.project.vcs.vcsNewProjectOptionsDialog()
         if vcsdlg.exec_() == QDialog.Accepted:
             projectdir, vcsDataDict = vcsdlg.getData()
             self.project.pdata["VCS"] = [vcsSystem]
             self.project.vcs = self.project.initVCS(vcsSystem)
             # edit VCS command options
             if self.project.vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     self.tr("New Project"),
                     self.tr(
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(self.project.vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     self.project.vcs.vcsSetOptions(codlg.getOptions())
             
             # create the project directory if it doesn't exist already
             if not os.path.isdir(projectdir):
                 try:
                     os.makedirs(projectdir)
                 except EnvironmentError:
                     E5MessageBox.critical(
                         self.parent(),
                         self.tr("Create project directory"),
                         self.tr(
                             "<p>The project directory <b>{0}</b> could not"
                             " be created.</p>").format(projectdir))
                     self.project.pdata["VCS"] = ['None']
                     self.project.vcs = self.project.initVCS()
                     return
             
             # create the project from the VCS
             self.project.vcs.vcsSetDataFromDict(vcsDataDict)
             if export:
                 ok = self.project.vcs.vcsExport(vcsDataDict, projectdir)
             else:
                 ok = self.project.vcs.vcsCheckout(vcsDataDict, projectdir,
                                                   False)
             if ok:
                 projectdir = os.path.normpath(projectdir)
                 filters = ["*.e4p"]
                 d = QDir(projectdir)
                 plist = d.entryInfoList(filters)
                 if len(plist):
                     if len(plist) == 1:
                         self.project.openProject(
                             plist[0].absoluteFilePath())
                         self.project.newProject.emit()
                     else:
                         pfilenamelist = d.entryList(filters)
                         pfilename, ok = QInputDialog.getItem(
                             None,
                             self.tr("New project from repository"),
                             self.tr("Select a project file to open."),
                             pfilenamelist, 0, False)
                         if ok:
                             self.project.openProject(
                                 QFileInfo(d, pfilename).absoluteFilePath())
                             self.project.newProject.emit()
                     if export:
                         self.project.pdata["VCS"] = ['None']
                         self.project.vcs = self.project.initVCS()
                         self.project.setDirty(True)
                         self.project.saveProject()
                 else:
                     res = E5MessageBox.yesNo(
                         self.parent(),
                         self.tr("New project from repository"),
                         self.tr(
                             "The project retrieved from the repository"
                             " does not contain an eric project file"
                             " (*.e4p). Create it?"),
                         yesDefault=True)
                     if res:
                         self.project.ppath = projectdir
                         self.project.opened = True
                         
                         from Project.PropertiesDialog import \
                             PropertiesDialog
                         dlg = PropertiesDialog(self.project, False)
                         if dlg.exec_() == QDialog.Accepted:
                             dlg.storeData()
                             self.project.initFileTypes()
                             self.project.setDirty(True)
                             try:
                                 ms = os.path.join(
                                     self.project.ppath,
                                     self.project.pdata["MAINSCRIPT"][0])
                                 if os.path.exists(ms):
                                     self.project.appendFile(ms)
                             except IndexError:
                                 ms = ""
                             self.project.newProjectAddFiles(ms)
                             self.project.createProjectManagementDir()
                             self.project.saveProject()
                             self.project.openProject(self.project.pfile)
                             if not export:
                                 res = E5MessageBox.yesNo(
                                     self.parent(),
                                     self.tr(
                                         "New project from repository"),
                                     self.tr(
                                         "Shall the project file be added"
                                         " to the repository?"),
                                     yesDefault=True)
                                 if res:
                                     self.project.vcs.vcsAdd(
                                         self.project.pfile)
             else:
                 E5MessageBox.critical(
                     self.parent(),
                     self.tr("New project from repository"),
                     self.tr(
                         """The project could not be retrieved from"""
                         """ the repository."""))
                 self.project.pdata["VCS"] = ['None']
                 self.project.vcs = self.project.initVCS()
         else:
             self.project.pdata["VCS"] = ['None']
             self.project.vcs = self.project.initVCS()
Пример #31
0
    def __loadDirectory(self):
        """
        Private slot loading the directory and preparing the listing page.
        """
        dir = QDir(self.url().toLocalFile())
        dirItems = dir.entryInfoList(
            QDir.AllEntries | QDir.Hidden | QDir.NoDotAndDotDot,
            QDir.Name | QDir.DirsFirst)

        u = self.url()
        if not u.path().endswith("/"):
            u.setPath(u.path() + "/")

        baseUrl = self.url().toString()
        basePath = u.path()

        linkClasses = {}
        iconSize = QWebSettings.globalSettings().fontSize(
            QWebSettings.DefaultFontSize)

        parent = u.resolved(QUrl(".."))
        if parent.isParentOf(u):
            icon = UI.PixmapCache.getIcon("up.png")
            linkClasses["link_parent"] = \
                self.__cssLinkClass(icon, iconSize).format("link_parent")
            parentStr = self.tr(
                """  <p><a class="link_parent" href="{0}">"""
                """Change to parent directory</a></p>""").format(
                    parent.toString())
        else:
            parentStr = ""

        row = \
            """    <tr class="{0}">"""\
            """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\
            """<td class="size">{4}</td>"""\
            """<td class="modified">{5}</td>"""\
            """</tr>\n"""
        table = self.tr("""    <tr>"""
                        """<th align="left">Name</th>"""
                        """<th>Size</th>"""
                        """<th align="left">Last modified</th>"""
                        """</tr>\n""")

        i = 0
        for item in dirItems:
            name = item.fileName()
            if item.isDir() and not name.endswith("/"):
                name += "/"
            child = u.resolved(QUrl(name.replace(":", "%3A")))

            if item.isFile():
                size = item.size()
                unit = 0
                while size:
                    newSize = size // 1024
                    if newSize and unit < len(self.__units):
                        size = newSize
                        unit += 1
                    else:
                        break

                sizeStr = self.tr("{0} {1}", "size unit")\
                    .format(size, self.__units[unit])
                linkClass = "link_file"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("fileMisc.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            else:
                sizeStr = ""
                linkClass = "link_dir"
                if linkClass not in linkClasses:
                    icon = UI.PixmapCache.getIcon("dirClosed.png")
                    linkClasses[linkClass] = \
                        self.__cssLinkClass(icon, iconSize).format(linkClass)
            table += row.format(
                i == 0 and "odd" or "even",
                linkClass,
                child.toString(),
                Utilities.html_encode(item.fileName()),
                sizeStr,
                item.lastModified().toString("yyyy-MM-dd hh:mm"),
            )
            i = 1 - i

        content = dirListPage_html.format(
            Utilities.html_encode(baseUrl), "".join(linkClasses.values()),
            self.tr("Listing of {0}").format(basePath), parentStr, table)
        self.__content = QByteArray(content.encode("utf8"))
        self.__content.append(512 * b' ')

        self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
        self.setHeader(QNetworkRequest.ContentTypeHeader,
                       "text/html; charset=UTF-8")
        self.setHeader(QNetworkRequest.ContentLengthHeader,
                       self.__content.size())
        self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
        self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
        self.metaDataChanged.emit()
        self.downloadProgress.emit(self.__content.size(),
                                   self.__content.size())
        self.readyRead.emit()
        self.finished.emit()
Пример #32
0
    ("../Resources/translations", [QTDIR + r'/translations/qt_fr.qm']),
    ("../Resources/translations", [QTDIR + r'/translations/qt_it.qm']),
    ("../Resources/translations", [r"translations/tonino_de.qm"]),
    ("../Resources/translations", [r"translations/tonino_es.qm"]),
    ("../Resources/translations", [r"translations/tonino_fr.qm"]),
    ("../Resources/translations", [r"translations/tonino_it.qm"]),
    ("../Resources/translations", [r"translations/tonino_nl.qm"]),
    ("../Resources", [r"conf/qt.conf"]),
    ("../Resources", [r"includes/mac/avrdude.conf"]),
    ("../Resources", [r"includes/mac/avrdude"]),
    ("../Resources", [r"icons/tonino_doc.icns"]),
  ]
  
# firmware file name
qd_include = QDir(os.path.dirname(os.path.realpath(__file__)) + "/includes/")
firmware_files = qd_include.entryInfoList(["tonino-*.hex"],QDir.Files | QDir.Readable,QDir.SortFlags(QDir.Name | QDir.Reversed))
tiny_firmware_files = qd_include.entryInfoList(["tinyTonino-*.hex"],QDir.Files | QDir.Readable,QDir.SortFlags(QDir.Name | QDir.Reversed))
if len(firmware_files) + len(tiny_firmware_files) > 0:
    if len(firmware_files) > 0:
        firmware_name = str(firmware_files[0].fileName())
        DATA_FILES = DATA_FILES + [("../Resources", [r"includes/" + firmware_name])]
    if len(tiny_firmware_files) > 0:
        tiny_firmware_name = str(tiny_firmware_files[0].fileName())
        DATA_FILES = DATA_FILES + [("../Resources", [r"includes/" + tiny_firmware_name])]
else:
    print("firmware *.hex missing!")
    quit()
  
plist = Plist.fromFile('conf/Info.plist')
plist.update({ 'CFBundleDisplayName': 'Tonino',
                    'CFBundleGetInfoString': 'Tonino, Roast Color Analyzer',
Пример #33
0
class Widgets(QWidget):
    def __init__(self, parent=None):
        super(Widgets, self).__init__(parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        # ======================== WIDGETS ===========================

        framePrincipal = QFrame(self)
        framePrincipal.setFrameShape(QFrame.Box)
        framePrincipal.setFrameShadow(QFrame.Sunken)
        framePrincipal.setAutoFillBackground(True)
        framePrincipal.setBackgroundRole(QPalette.Light)
        framePrincipal.setFixedSize(662, 450)
        framePrincipal.move(10, 10)

        frame = QFrame(framePrincipal)
        frame.setFixedSize(640, 480)
        frame.move(10, 10)

        self.labelEstado = QLabel(self)
        self.labelEstado.setAlignment(Qt.AlignCenter)
        self.labelEstado.setGeometry(0, 250, 640, 480)
        #self.labelEstado.setFixedSize(188, 30)
        #self.labelEstado.move(50, 400)
        self.labelEstado.setFont(QFont('SansSerif', 30))

        self.labelImagen = QLabel(frame)
        self.labelImagen.setAlignment(Qt.AlignCenter)
        self.labelImagen.setGeometry(0, 0, 640, 480)
        # self.labelImagen.setScaledContents(True)

        self.labelImagenUno = QLabel(frame)
        self.labelImagenUno.setAlignment(Qt.AlignCenter)
        self.labelImagenUno.setGeometry(-650, 0, 640, 480)

        # =================== BOTONES (QPUSHBUTTON) ==================

        self.buttonCargar = QPushButton("Cargar imagen", self)
        self.buttonCargar.setCursor(Qt.PointingHandCursor)
        self.buttonCargar.setFixedSize(188, 30)
        self.buttonCargar.move(50, 519)

        self.buttonVerificar = QPushButton("Analizar", self)
        self.buttonVerificar.setCursor(Qt.PointingHandCursor)
        self.buttonVerificar.setFixedSize(188, 30)
        self.buttonVerificar.move(248, 519)

        self.buttonEliminar = QPushButton("Eliminar imagen", self)
        self.buttonEliminar.setCursor(Qt.PointingHandCursor)
        self.buttonEliminar.setFixedSize(188, 30)
        self.buttonEliminar.move(445, 519)

        self.buttonAnterior = QPushButton("<", self)
        self.buttonAnterior.setObjectName("Anterior")
        self.buttonAnterior.setToolTip("Imagen anterior")
        self.buttonAnterior.setCursor(Qt.PointingHandCursor)
        self.buttonAnterior.setFixedSize(30, 30)
        self.buttonAnterior.move(10, 519)

        self.buttonSiguiente = QPushButton(">", self)
        self.buttonSiguiente.setObjectName("Siguiente")
        self.buttonSiguiente.setToolTip("Imagen siguiente")
        self.buttonSiguiente.setCursor(Qt.PointingHandCursor)
        self.buttonSiguiente.setFixedSize(30, 30)
        self.buttonSiguiente.move(643, 519)

        # ===================== CONECTAR SEÑALES =====================

        self.buttonCargar.clicked.connect(self.Cargar)
        self.buttonEliminar.clicked.connect(self.Eliminar)
        self.buttonVerificar.clicked.connect(self.predecir)
        self.buttonAnterior.clicked.connect(self.anteriorSiguiente)
        self.buttonSiguiente.clicked.connect(self.anteriorSiguiente)

        # Establecer los valores predeterminados
        self.posicion = int
        self.estadoAnterior, self.estadoSiguiente = False, False
        self.carpetaActual = QDir()
        self.imagenesCarpeta = []
        self.direccion = ''

# ======================= FUNCIONES ==============================

    def predecir(self):
        print(self.direccion)
        x = load_img(self.direccion, target_size=(longitud, altura))
        x = img_to_array(x)
        x = np.expand_dims(x, axis=0)
        array = cnn.predict(x)
        result = array[0]
        answer = np.argmax(result)
        if answer == 0:
            self.labelEstado.setText("CAPORALES")
            print("pred: caporales")
        elif answer == 1:
            self.labelEstado.setText("DIABLADA")
            print("pred: diablada")
        elif answer == 2:
            self.labelEstado.setText("MORENADA")
            print("pred: morenada")
        elif answer == 3:
            self.labelEstado.setText("SALAY")
            print("pred: salay")
        elif answer == 4:
            self.labelEstado.setText("TINKU")
            print("pred: tinku")
        print(result)
        return answer

    def bloquearBotones(self, bool):
        self.buttonCargar.setEnabled(bool)
        self.buttonEliminar.setEnabled(bool)
        self.buttonVerificar.setEnabled(bool)
        self.buttonAnterior.setEnabled(bool)
        self.buttonSiguiente.setEnabled(bool)

    def Mostrar(self, label, imagen, nombre, posicionX=650):
        imagen = QPixmap.fromImage(imagen)

        # Escalar imagen a 640x480 si el ancho es mayor a 640 o el alto mayor a 480
        if imagen.width() > 640 or imagen.height() > 480:
            imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio,
                                   Qt.SmoothTransformation)

        # Mostrar imagen
        label.setPixmap(imagen)

        # Animación (al finalizar la animación se muestra en la barra de estado el nombre y la extensión de la imagen
        # y se desbloquean los botones).
        self.animacionMostar = QPropertyAnimation(label, b"geometry")
        self.animacionMostar.finished.connect(
            lambda: (self.parent.statusBar.showMessage(nombre),
                     self.bloquearBotones(True)))
        self.animacionMostar.setDuration(200)
        self.animacionMostar.setStartValue(QRect(posicionX, 0, 640, 480))
        self.animacionMostar.setEndValue(QRect(0, 0, 640, 480))
        self.animacionMostar.start(QAbstractAnimation.DeleteWhenStopped)

    def Limpiar(self,
                labelConImagen,
                labelMostrarImagen,
                imagen,
                nombre,
                posicionInternaX,
                posicionX=None):
        def Continuar(estado):
            if estado:
                if posicionX:
                    self.Mostrar(labelMostrarImagen, imagen, nombre, posicionX)
                else:
                    self.Mostrar(labelMostrarImagen, imagen, nombre)

        self.animacionLimpiar = QPropertyAnimation(labelConImagen, b"geometry")
        self.animacionLimpiar.finished.connect(lambda: labelConImagen.clear())
        self.animacionLimpiar.setDuration(200)
        # self.animacionLimpiar.valueChanged.connect(lambda x: print(x))
        self.animacionLimpiar.stateChanged.connect(Continuar)
        self.animacionLimpiar.setStartValue(QRect(0, 0, 640, 480))
        self.animacionLimpiar.setEndValue(QRect(posicionInternaX, 0, 640, 480))
        self.animacionLimpiar.start(QAbstractAnimation.DeleteWhenStopped)

    def Cargar(self):

        nombreImagen, _ = QFileDialog.getOpenFileName(
            self, "Seleccionar imagen", QDir.currentPath(),
            "Archivos de imagen (*.jpg *.png *.ico *.bmp)")
        self.direccion = nombreImagen
        if nombreImagen:
            # Verificar que QLabel tiene imagen
            labelConImagen = ""
            if self.labelImagen.pixmap():
                labelConImagen = self.labelImagen
            elif self.labelImagenUno.pixmap():
                labelConImagen = self.labelImagenUno

            imagen = QImage(nombreImagen)

            if imagen.isNull():
                if labelConImagen:
                    self.Eliminar()

                QMessageBox.information(
                    self, "Visor de imágenes",
                    "No se puede cargar %s." % nombreImagen)
                return

            # Obtener ruta de la carpeta que contiene la imagen seleccionada
            self.carpetaActual = QDir(
                QFileInfo(nombreImagen).absoluteDir().path())

            # Obtener la ruta y el nombre de las imagenes que se encuentren en la carpeta de
            # la imagen seleccionada
            imagenes = self.carpetaActual.entryInfoList(
                ["*.jpg", "*.png", "*.ico", "*.bmp"], QDir.Files, QDir.Name)
            self.imagenesCarpeta = [
                imagen.absoluteFilePath() for imagen in imagenes
            ]

            self.posicion = self.imagenesCarpeta.index(nombreImagen)
            self.estadoAnterior = True if self.posicion == 0 else False
            self.estadoSiguiente = True if self.posicion == len(
                self.imagenesCarpeta) - 1 else False

            # Función encargada de bloquear o desbloquear los botones
            self.bloquearBotones(False)

            # Nombre y extensión de la imagen
            nombre = QFileInfo(nombreImagen).fileName()

            if labelConImagen:
                posicionInternaX = -650
                labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap(
                ) else self.labelImagenUno
                self.Limpiar(labelConImagen, labelMostrarImagen, imagen,
                             nombre, posicionInternaX)
            else:
                self.Mostrar(self.labelImagen, imagen, nombre)

    def Eliminar(self):
        def establecerValores():
            labelConImagen.clear()
            labelConImagen.move(0, 0)

            # Limpiar la barra de estado
            self.parent.statusBar.clearMessage()

            # Establecer los valores predeterminados
            self.posicion = int
            self.estadoAnterior, self.estadoSiguiente = False, False
            self.carpetaActual = QDir()
            self.imagenesCarpeta.clear()

            self.bloquearBotones(True)

        # Verificar que QLabel tiene imagen
        labelConImagen = ""
        if self.labelImagen.pixmap():
            labelConImagen = self.labelImagen
        elif self.labelImagenUno.pixmap():
            labelConImagen = self.labelImagenUno

        if labelConImagen:
            self.bloquearBotones(False)

            self.animacionEliminar = QPropertyAnimation(
                labelConImagen, b"geometry")
            self.animacionEliminar.finished.connect(establecerValores)
            self.animacionEliminar.setDuration(200)
            self.animacionEliminar.setStartValue(QRect(0, 0, 640, 480))
            self.animacionEliminar.setEndValue(QRect(-650, 0, 640, 480))
            self.animacionEliminar.start(QAbstractAnimation.DeleteWhenStopped)

    def anteriorSiguiente(self):

        if self.imagenesCarpeta:
            widget = self.sender().objectName()

            if widget == "Anterior":
                self.estadoAnterior = True if self.posicion == 0 else False
                self.estadoSiguiente = False

                self.posicion -= 1 if self.posicion > 0 else 0
                posicionInternaX, posicionX = 650, -650
            else:
                self.estadoSiguiente = True if self.posicion == len(
                    self.imagenesCarpeta) - 1 else False
                self.estadoAnterior = False

                self.posicion += 1 if self.posicion < len(
                    self.imagenesCarpeta) - 1 else 0
                posicionInternaX, posicionX = -650, 650

            if self.estadoAnterior or self.estadoSiguiente:
                return
            else:
                imagen = self.imagenesCarpeta[self.posicion]
                self.direccion = imagen
                # Verificar que la carpeta que contiene la imagene exista
                if not QDir(self.carpetaActual).exists():
                    self.Eliminar()
                    return
                elif not QFile.exists(imagen):
                    # Obtener la ruta y el nombre de las imagenes que se encuentren en la
                    # carpeta de la imagen seleccionada
                    imagenes = self.carpetaActual.entryInfoList(
                        ["*.jpg", "*.png", "*.ico", "*.bmp"], QDir.Files,
                        QDir.Name)

                    if not imagenes:
                        self.Eliminar()
                        return

                    self.imagenesCarpeta = [
                        imagen.absoluteFilePath() for imagen in imagenes
                    ]

                    self.posicion = randint(0, len(self.imagenesCarpeta) - 1)
                    self.estadoAnterior = True if self.posicion == 0 else False
                    self.estadoSiguiente = True if self.posicion == len(
                        self.imagenesCarpeta) - 1 else False
                elif QImage(imagen).isNull():
                    del self.imagenesCarpeta[self.posicion]

                    if not self.imagenesCarpeta:
                        self.Eliminar()
                        return

                    self.posicion = randint(0, len(self.imagenesCarpeta) - 1)
                    self.estadoAnterior = True if self.posicion == 0 else False
                    self.estadoSiguiente = True if self.posicion == len(
                        self.imagenesCarpeta) - 1 else False

                imagen = self.imagenesCarpeta[self.posicion]

                if self.labelImagen.pixmap():
                    labelConImagen = self.labelImagen
                elif self.labelImagenUno.pixmap():
                    labelConImagen = self.labelImagenUno

                # Función encargada de bloquear o desbloquear los botones
                self.bloquearBotones(False)

                # Nombre y extensión de la imagen
                nombre = QFileInfo(imagen).fileName()

                # Label en el que se va a mostrar la imagen
                labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap(
                ) else self.labelImagenUno

                # Quitar la imagen actual y mostrar la siguiente
                self.Limpiar(labelConImagen, labelMostrarImagen,
                             QImage(imagen), nombre, posicionInternaX,
                             posicionX)