Пример #1
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)
Пример #2
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()
Пример #3
0
    def copyFiles(self, src, dst, names=None, overwrite=True):
        """ Copy files from src directory to dst directory. Subfolders are ignored.
        If names is provided, copies only files matching those names. Symlinks are not
        copied """
        moDebug("Copying files from {} to {}. Names: {}".format(
            src, dst, names))
        srcDir = QDir(src, "", QDir.IgnoreCase, QDir.Files | QDir.NoSymLinks)
        dstDir = QDir(dst)

        if not srcDir.exists() or not dstDir.exists():
            moWarn("Failed to copy files with non-existant directories")
            return False

        success = True
        if names:
            srcDir.setNameFilters(names)
        fileNames = srcDir.entryList()
        for name in fileNames:
            if dstDir.exists(name):
                if not overwrite:
                    continue
                dstDir.remove(name)
            success = QFile.copy(srcDir.filePath(name), dstDir.filePath(name))
            if not success:
                moWarn('Failed to copy "{}" from "{}" to "{}"'.format(
                    name, src, dst))
        return success
Пример #4
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("请选择输入文件")
Пример #5
0
class DataAnalysisWindows(QMainWindow, AQMainWindow.Ui_MainWindow):
    opendir = ''
    csvDataFrame = ''
    checkMap = {}

    def __init__(self, parent=None):
        super(DataAnalysisWindows, self).__init__(parent)
        self.setupUi(self)
        self.chooseDirToolButton.clicked.connect(self.openWindow)
        self.lodefilePushButton.clicked.connect(self.loadfile)

        children = self.checkGroupBox.children()
        count = len(self.checkGroupBox.children())
        print('check box count {0}'.format(count))
        for child in children:
            if child.staticMetaObject.className() == 'QCheckBox':
                self.checkMap[child.text()] = child.isChecked()

        print('checkMap {0}'.format(self.checkMap))

    def openWindow(self):
        dirpath = QFileDialog.getExistingDirectory(
            self, self.tr(u'打开目录'), "~/",
            QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
        self.dirPathLabel.setText(dirpath)

        filters = ['*.csv']

        self.opendir = QDir(dirpath)
        self.opendir.setNameFilters(filters)
        print('open dir is {0}, dirpath is {1}'.format(self.opendir.path(),
                                                       dirpath))

        model = QStringListModel()
        model.setStringList(self.opendir.entryList())

        self.fileListView.setModel(model)

    # 读取csv文件,到主窗口显示
    def loadfile(self):
        path = os.path.join(self.opendir.path(),
                            self.fileListView.currentIndex().data())
        print('file path is {0}'.format(path))
        self.csvDataFrame = CSVFilter.readCsv(path)
        self.updateCVSDisplay()

    def updateCVSDisplay(self):
        role = {u'搜索人气': [1000, 10000000], u'在线商品数': [1, 5000]}
        dataframe = CSVFilter.filtterRow(self.csvDataFrame, role)

        list = []
        for key in self.checkMap:
            if self.checkMap[key]:
                list.append(key)

        data_frame_column_by_name = dataframe.loc[:, list]
        print('display list {0}'.format(list))

        self.dataTableView.setModel(PandasModel(data_frame_column_by_name))
Пример #6
0
def related_file(FBTS, filename, encoding=None):
    qd = QDir( FBTS.folderpath() )
    qd.setFilter(QDir.Files | QDir.Readable)
    qd.setSorting(QDir.Type | QDir.Reversed)
    qd.setNameFilters( [filename] ) # literal name or 'foo*.*'
    names = qd.entryList()
    if names : # list is not empty, open the first
        a_file = QFile( qd.absoluteFilePath(names[0]) )
        return _qfile_to_stream(a_file, QIODevice.ReadOnly, encoding)
    return None
Пример #7
0
def related_file(FBTS, filename, encoding=None):
    qd = QDir(FBTS.folderpath())
    qd.setFilter(QDir.Files | QDir.Readable)
    qd.setSorting(QDir.Type | QDir.Reversed)
    qd.setNameFilters([filename])  # literal name or 'foo*.*'
    names = qd.entryList()
    if names:  # list is not empty, open the first
        a_file = QFile(qd.absoluteFilePath(names[0]))
        return _qfile_to_stream(a_file, QIODevice.ReadOnly, encoding)
    return None
Пример #8
0
 def run(self):
     #   Lists ISO files in local directory
     root=QDir(self.destination)
     root.setFilter(QDir.AllDirs|QDir.NoDot|QDir.NoDotDot)
     dirs=root.entryList()
     for dir in dirs:
         sub=QDir(self.destination+'/'+dir)
         sub.setNameFilters(["*.iso"])
         sub.setFilter(QDir.Files)
         local=sub.entryList()
         if len(local)!=0:
             for iso in local:
                 isoSize=QFileInfo(sub.absolutePath()+'/' +iso).size()
                 self.localList.append([dir,iso,isoSize])
     #   List the remote directory
     commande = ['rsync', '-avHP', '--list-only',str(self.path)]
     try:
         if self.password != "":
             envir = os.environ.copy()
             envir['RSYNC_PASSWORD']=str(self.password)
             process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE, env=envir)
         else:
             process = Popen(commande, shell=False, stdout=PIPE, stderr=PIPE)
     except OSError as e:
         self.lvM.emit(self.tr("Command rsync not found: ")+str(e))
         self.endSignal.emit(1)
         return
     except ValueError as e:
         self.lvM.emit(self.tr("Error in rsync parameters: ")+str(e))
         self.endSignal.emit(2)
         return
     except Exception as e:
         # Unknown error in rsync
         self.lvM.emit(self.tr("Error in rsync: ")+str(e))
         self.endSignal.emit(3)
         return
     process.poll()
     while True :
         item=process.stdout.readline().rstrip().decode('unicode_escape')
         self.lvM.emit(item)
         if str(item.lower()).endswith('.iso') :
             words=item.split()
             self.list.append(words[-1])
         process.poll()
         if process.returncode != None:
             break
     self.endSignal.emit(0)
Пример #9
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)
Пример #10
0
def main():
    facesDir = QDir("/home/syndicate/PycharmProjects/Iris/assets/faces/")

    faceFolders = facesDir.entryList()
    normalizer = FaceNormalizer()

    for folder in faceFolders:
        temp = QDir("/home/syndicate/PycharmProjects/Iris/assets/faces/" +
                    folder)
        temp.setNameFilters(["*.png"])

        images = temp.entryList()
        for image in images:
            path = temp.absoluteFilePath(image)
            image = cv2.imread(path, 0)
            cv2.imshow("image", image)
            print(path)
            frame = Face(image)
            normalized = frame.normalize()
            cv2.imwrite(path, normalized)

            if cv2.waitKey(10) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                exit(1)
Пример #11
0
    def _perform_migrations(self):
        qry = self.getQuery()
        d = self.getDatabase()

        # check if we can query a version of
        # the schema_changes table, if not possible
        # we likely need to create a completly new db
        if qry.exec(
                "SELECT version FROM schema_changes ORDER BY version DESC LIMIT 1"
        ) and qry.next():
            db_version = int(qry.value(0))
            print(f"Found Database Version to be {db_version}")
        else:
            db_version = -1
            print(
                "Could not determine database version, will create new schema from scratch..."
            )

        # check to see if we can find any migration files
        # we will prefer the ones in sql/*.sql on disk over the ones
        # bundled with qrc for easier development, but the release version
        # will likely use the ones bundled with the applications ressources
        files = glob.glob("sql/*.sql")
        if len(files) == 0:
            # could not find any files on disk in sql subdir
            if QDir(":/sql").exists():
                dir_ = QDir(":/sql")
                dir_.setNameFilters(["*.sql"])
                # in QDir.entryList files will be stripped of path
                # and we also need to append :
                files = [
                    ":/sql/" + x for x in dir_.entryList(filters=QDir.Files)
                ]

        # if the number of files is still zero we could not find any migrations
        # this would be a bug and we can terminate
        if len(files) == 0:
            print(
                "Could not find any Schema Files in sql/*.sql - Please reinstall application."
            )
            print("Exiting now ...")
            sys.exit(1)
        else:
            # next we sort the files in the correct order
            files = sorted(files,
                           key=lambda x: float(re.findall(r"(\d+)", x)[0]))
            # next up, we check the highest migration file version number
            # this should be the last list entry
            # if thats higher than db version we migrate
            # otherwise we return early doing nothing
            highvers = self._get_migrationfile_version(
                os.path.basename(files[-1]))
            if highvers <= db_version:
                print(
                    f"Found highest Version of migration files is {highvers}")
                print("Nothing needs to be migrated.")
                return

            print("Performing outstanding Database migrations...")
            qry.exec(
                "SELECT version, apply_date FROM schema_changes ORDER BY version ASC"
            )
            all_migrations = dict()
            while qry.next():
                all_migrations[qry.value(0)] = qry.value(1)

            d.transaction()
            for file in files:
                scriptname: str = os.path.basename(file)
                file_version = self._get_migrationfile_version(scriptname)

                # if the database version is already higher then the version in the filename
                # we may skip this sql file
                if db_version >= file_version:
                    print(
                        f"Skipping {scriptname}, because migration {file_version} was already applied on {all_migrations.get(file_version, 'NULL')}"
                    )
                else:
                    # otherwise we will execute the sql code and apply the migration
                    try:
                        if file.startswith(":"):
                            fd = QFile(file)
                            fd.open(QFile.ReadOnly | QFile.Text)
                            sql = QTextStream(fd).readAll()
                        else:
                            with open(file, 'rt', encoding='utf-8') as fd:
                                sql = fd.read()
                    except OSError:
                        print(f"Could not open file for reading: {file}")
                        sys.exit(1)
                    finally:
                        if file.startswith(":"):
                            fd.close()

                    # We will have to use sqlparser to split our migration files
                    # into atomic statements since the sqlite qt driver does not
                    # work with multiple stmts in one exec call and offers itself
                    # no alternative like the sqlite3.executescript() that comes
                    # with python3... :(
                    for stmt in sqlparse.split(sql):
                        if not qry.exec(stmt):
                            print(f"Applying {scriptname} to schema failed")
                            print(
                                f"The error appeared with the following statement:"
                            )
                            print(stmt)
                            print(qry.lastError().text())
                            d.rollback()
                            sys.exit(1)

                    if not qry.exec(f"""
                            INSERT INTO schema_changes 
                                (version, scriptname, apply_date)
                            VALUES
                                ({file_version}, '{scriptname}', DATETIME('now'))
                            """):
                        print(qry.lastError().text())
                        d.rollback()
                        sys.exit(1)
                    else:
                        print(f"Successfully applied {scriptname} to schema")

            # if we come this far we've applied all outstanding migrations
            # and can commit all changes to disk
            d.commit()
            print(f"All outstanding db migrations were applied")
            print(f"Database schema is now at version: {file_version}")
Пример #12
0
 def listEntries(self, dir: QDir) -> [str]:
     dir.setNameFilters(["*.md"])
     fileNames = []
     for fileInfo in dir.entryInfoList():
         fileNames.append(fileInfo.completeBaseName())
     return fileNames