def import_demo_images(self):
        """
        导入测试图片
        """
        _index = 1
        for _key in IMPORT_URLS:
            for _url in IMPORT_URLS[_key]:
                # image_doc信息
                _image_doc = {
                    "id": StringTool.fill_fix_string(str(_index), 10, '0'),
                    "url": _url,
                    "path": ''
                }

                try:
                    # 下载图片信息
                    _image = urllib.request.urlopen(_url).read()

                    # 执行导入处理
                    self.search_engine.image_to_search_db(_image,
                                                          _image_doc,
                                                          'DemoSearch',
                                                          init_collection='')
                except:
                    print(traceback.format_exc())

                _index += 1
Beispiel #2
0
            def _replace_var_fun(m):
                _match_str = m.group(0)
                _value = None
                if _match_str.startswith('{$datetime='):
                    # 按格式化字符替换当前的时间
                    _key = _match_str[11:-2]
                    _value = datetime.datetime.now().strftime(_key)
                elif _match_str.startswith('{$uuid='):
                    # 指定uuid字符类型
                    _key = _match_str[7:-2]
                    str(uuid.uuid1())
                    _value = eval('str(uuid.uuid%s())' % _key)
                elif _match_str.startswith('{$random'):
                    # 产生指定两个整数之间的随机数,总位数与最大的数一致,左补零
                    _key = _match_str[8:-2]
                    _args = eval('(%s)' % _key)
                    _value = StringTool.fill_fix_string(
                        str(random.randint(*_args)), len(_args[1]), '0')
                elif _match_str.startswith('{$file_ext='):
                    # 原文件扩展名
                    _value = _file_ext
                elif _match_str.startswith('{$file_name='):
                    # 原文件指定位置的字符
                    _key = _match_str[12:-2]
                    _args = eval('(%s)' % _key)
                    if len(_args) > 1:
                        _value = _old_filename[_args[0]:_args[1]]
                    else:
                        _value = _old_filename[_args[0]:]

                if _value is not None:
                    return str(_value)
                else:
                    return _match_str
    def rename_file_to_num(cls, path: str, start_index: int = 1) -> int:
        """
        重命名文件为数字序号

        @param {str} path - 要处理的文件夹
        @param {int} start_index=1 - 开始序号

        @returns {int} - 返回当前序号
        """
        # 处理当前目录
        _start_index = start_index
        _path = os.path.realpath(path)
        _file_list = FileTool.get_filelist(_path, is_fullname=False)
        for _file in _file_list:
            _ext = FileTool.get_file_ext(_file)
            os.rename(
                os.path.join(_path, _file),
                os.path.join(
                    _path,
                    StringTool.fill_fix_string(str(_start_index), 10, '0') +
                    '.' + _ext))
            _start_index += 1

        # 处理子目录
        _sub_dir_list = FileTool.get_dirlist(_path)
        for _sub_dir in _sub_dir_list:
            _start_index = cls.rename_file_to_num(_sub_dir,
                                                  start_index=_start_index)

        # 返回当前序号值
        return _start_index
Beispiel #4
0
    def labelimg_rename_filename(cls, path: str, fix_len: int = 10):
        """
        重名名labelimg对应目录下的文件名(图片文件和标注文件同步修改)

        @param {str} path - 要修改文件名的路径
        @param {int} fix_len=10 - 文件名长度
        """
        _path = os.path.realpath(path)
        _files = FileTool.get_filelist(path=_path, is_fullname=False)
        _index = 1
        for _file in _files:
            _file_ext = FileTool.get_file_ext(_file)
            if _file_ext == 'xml':
                # 标签文件不处理
                continue

            _file_no_ext = FileTool.get_file_name_no_ext(_file)
            # 获取最新的文件名
            while True:
                _new_name = StringTool.fill_fix_string(str(_index),
                                                       fix_len,
                                                       '0',
                                                       left=True)
                _new_file = _new_name + '.' + _file_ext
                _index += 1
                if os.path.exists(os.path.join(path, _new_file)):
                    # 文件名已存在
                    _index += 1
                    continue

                # 文件名不存在,跳出循环
                break

            # 修改文件名
            os.rename(os.path.join(_path, _file),
                      os.path.join(_path, _new_file))
            if os.path.exists(os.path.join(_path, _file_no_ext + '.xml')):
                # 需要修改标签文件
                _xml_file = _new_name + '.xml'
                os.rename(os.path.join(_path, _file_no_ext + '.xml'),
                          os.path.join(_path, _xml_file))

                # 修改标签文件内容
                _tree = ET.parse(os.path.join(_path, _xml_file))
                _root = _tree.getroot()
                _root.find('filename').text = _new_file
                _root.find('path').text = os.path.join(_path, _new_file)
                _tree.write(os.path.join(_path, _xml_file),
                            encoding='utf-8',
                            method="xml",
                            xml_declaration=None)
Beispiel #5
0
    def default_formula_deal_fun_id(formular_obj, **kwargs):
        """
        默认公式计算函数-格式化id(左补0)

        @param {StructFormula} formular_obj - 要计算的公式
        @param {kwargs} - 处理公式的参数,必须传进来的参数为
            id {int} - 要格式化的id

        """
        if formular_obj.content_string == '':
            formular_obj.formula_value = str(kwargs['id'])
        else:
            formular_obj.formula_value = StringTool.fill_fix_string(
                str(kwargs['id']),
                fix_len=int(formular_obj.content_string),
                fill_char='0')
Beispiel #6
0
    def _help_cmd_dealfun(self,
                          message='',
                          cmd='',
                          cmd_para='',
                          prompt_obj=None,
                          **kwargs):
        """
        帮助命令处理函数

        @param {string} message='' - prompt提示信息
        @param {string} cmd - 执行的命令key值
        @param {string} cmd_para - 传入的命令参数(命令后的字符串,去掉第一个空格)
        @param {PromptPlus} prompt_obj=None - 传入调用函数的PromptPlus对象,可以通过该对象的一些方法控制输出显示
        @param {kwargs} - 传入的主进程的初始化kwargs对象

        @returns {CResult} - 命令执行结果,可通过返回错误码10101通知框架退出命令行, 同时也可以通过CResult对象的
            print_str属性要求框架进行打印处理
        """
        # 命令相关参数
        _CMD_HELP_INFO = self._console_global_para['CMD_HELP_INFO']
        _lang = self._console_global_para['language']

        _cmd_list = PromptPlus.get_cmd_para_list(cmd_para)
        if len(_cmd_list) == 0:
            # 没有传入任何参数,生成命令提示参数并返回
            # 先计算命令的最大长度
            _max_len = 15
            for _key in _CMD_HELP_INFO.keys():
                _max_len = max(_max_len, len(_key))

            _cmd_list_tips = ''
            for _key in _CMD_HELP_INFO.keys():
                _cmd_title = ''
                if _lang in _CMD_HELP_INFO[_key].keys():
                    _cmd_title = _CMD_HELP_INFO[_key][_lang][0]
                elif 'en' in _CMD_HELP_INFO[_key].keys():
                    _cmd_title = _CMD_HELP_INFO[_key]['en'][0]
                else:
                    _cmd_title = _CMD_HELP_INFO[_key][list(
                        _CMD_HELP_INFO[_key].keys())[0]][0]
                _cmd_list_tips = '%s%s%s\n' % (
                    _cmd_list_tips,
                    StringTool.fill_fix_string(
                        _key, _max_len + 1, ' ', left=False),
                    _cmd_title.replace(
                        '{{VERSION}}',
                        self._console_global_para['version']).replace(
                            '{{NAME}}',
                            self._console_global_para['name']).replace(
                                '{{SHELL_CMD_NAME}}',
                                self._console_global_para['shell_cmd_name']))
            # 返回提示信息
            return _cmd_list_tips

        # 处理某个命令的具体帮助信息
        _para_value = ''
        for _item in _cmd_list:
            if _item[0] == '':
                _para_value = _item[1]
                break
            elif _item[0] == '-c' or _item[0] == '-cmd':
                _para_value = _item[1]
                break

        if _para_value in _CMD_HELP_INFO.keys():
            # 显示指定命令帮助
            _help_info = None
            if _lang in _CMD_HELP_INFO[_para_value].keys():
                _help_info = _CMD_HELP_INFO[_para_value][_lang]
            elif 'en' in _CMD_HELP_INFO[_para_value].keys():
                _help_info = _CMD_HELP_INFO[_para_value]['en']
            else:
                _help_info = _CMD_HELP_INFO[_para_value][list(
                    _CMD_HELP_INFO[_para_value].keys())[0]]

            prompt_obj.prompt_print('\n'.join(_help_info).replace(
                '{{VERSION}}', self._console_global_para['version']).replace(
                    '{{NAME}}', self._console_global_para['name']).replace(
                        '{{SHELL_CMD_NAME}}',
                        self._console_global_para['shell_cmd_name']))
        else:
            # 没有匹配到命令
            prompt_obj.prompt_print(
                _("help not support '$1' command\n", (_para_value, )))

        # 返回结果
        return CResult(code='00000')
Beispiel #7
0
    def labelimg_crop_pic_by_flags(cls,
                                   path: str,
                                   dest_path: str,
                                   copy_no_flag_pic: bool = True,
                                   with_sub_dir: bool = True,
                                   fix_len: int = 10):
        """
        根据标注进行图片截图处理

        @param {str} path - 需要处理的目录
        @param {str} dest_path - 截图图片存放目录
        @param {bool} copy_no_flag_pic=True - 直接复制没有标注的图片
        @param {bool} with_sub_dir=True - 是否按原目录结构存储图片
        @param {int} fix_len=10 - 图片重命名的文件名长度

        @returns {iter_list} - 通过yield返回的处理进度信息清单
            [总文件数int, 当前已处理文件数int, 是否成功]
        """
        try:
            # 获取所有要处理的图片清单
            _file_list = cls._get_pic_file_list(path)
            _total = len(_file_list)
            _deal_num = 0

            # 先返回进度情况
            if _total == 0:
                yield [_deal_num, _total, True]
                return

            # 创建复制文件夹
            FileTool.create_dir(dest_path, exist_ok=True)

            # 遍历处理
            _rename_index = 1
            _src_path = os.path.realpath(path)
            _dest_path = os.path.realpath(dest_path)
            for _file in _file_list:
                # 当前进展
                yield [_deal_num, _total, True]

                # 路径处理
                _file_path, _filename = os.path.split(_file)
                if with_sub_dir:
                    # 创建子目录
                    _dest_path = os.path.join(
                        os.path.realpath(dest_path),
                        os.path.realpath(_file_path)[len(_src_path):].strip(
                            '/\\'))
                    FileTool.create_dir(_dest_path, exist_ok=True)

                # 获取标注文件
                _ext = FileTool.get_file_ext(_filename)
                _xml_file = os.path.join(_file_path,
                                         _filename[0:-len(_ext)] + 'xml')

                if not os.path.exists(_xml_file):
                    # 标注文件不存在
                    if copy_no_flag_pic:
                        # 直接复制文件
                        shutil.copy(
                            _file,
                            os.path.join(
                                _dest_path,
                                StringTool.fill_fix_string(
                                    str(_rename_index), fix_len, '0') + '.' +
                                _ext))
                        _rename_index += 1

                    # 下一个
                    _deal_num += 1
                    continue

                # 将图片放入内存
                with open(_file, 'rb') as _fid:
                    _file_bytes = _fid.read()
                    _image = Image.open(BytesIO(_file_bytes))

                # 处理标注
                _tree = ET.parse(_xml_file)
                _root = _tree.getroot()

                for _member in _root.findall('object'):
                    # 逐个标注进行处理
                    _crop_image = _image.crop(
                        (int(_member[4][0].text), int(_member[4][1].text),
                         int(_member[4][2].text), int(_member[4][3].text)))

                    _crop_image.save(os.path.join(
                        _dest_path,
                        StringTool.fill_fix_string(str(_rename_index), fix_len,
                                                   '0') + '.' + _ext),
                                     format='JPEG')

                    _rename_index += 1

                # 下一个
                _deal_num += 1

            # 返回结果
            yield [_total, _total, True]
        except:
            print('labelimg_crop_pic_by_flags error: %s\r\n%s' %
                  (path, traceback.format_exc()))
            yield [-1, -1, False]