50 Commits
Author SHA1 Message Date
Yao Fang 1545ed83ea optimise algorithm 2021-04-13 15:12:14 +08:00
Yao Fang 646fa5fa4e 提高cpu识别准确度 2021-04-12 11:58:20 +08:00
Yao Fang 26c6ee0f82 update readme 2021-04-12 11:27:59 +08:00
Yao Fang 1912a7e0bc update readm e 2021-04-12 11:25:20 +08:00
Yao Fang b0700b8b8e minor 2021-04-12 10:48:20 +08:00
Yao Fang d42796b99e minor 2021-04-12 10:47:10 +08:00
Yao Fang 28ba185604 m inor 2021-04-12 10:45:38 +08:00
Yao Fang 742d3c6e0d minor 2021-04-12 10:38:34 +08:00
Yao Fang b65e0c9f29 update readme_en 2021-04-12 10:31:08 +08:00
Yao Fang 061bdc62c6 Update demo.gif 2021-04-09 20:55:09 +08:00
Yao Fang 4d5e672195 Create demo.gif 2021-04-09 20:48:06 +08:00
Yao Fang 268b7f9b0e Update README.md 2021-04-09 20:18:02 +08:00
Yao Fang 3cda7a6608 Update README.md 2021-04-09 19:48:27 +08:00
Yao Fang cb24e18c22 Update requirements.txt 2021-04-09 19:25:44 +08:00
Yao Fang 9fc2aaeb5f Update requirements_gpu.txt 2021-04-09 19:25:30 +08:00
Yao Fang 7f4240a363 Update README.md 2021-04-09 19:24:45 +08:00
Yao Fang daa6888eb2 minor 2021-04-09 17:09:53 +08:00
Yao Fang 78da31da08 新增多线程防止主线程阻塞 2021-04-09 16:38:06 +08:00
Yao Fang 7788c5b442 update readme 2021-04-09 15:15:34 +08:00
Yao Fang 7c7f3941f2 update readme 2021-04-09 14:54:42 +08:00
Yao Fang c3a571cb18 update requirements 2021-04-09 14:15:29 +08:00
Yao Fang bab0a5de24 Merge pull request #6 from YaoFANGUK/dev-gui
新增图形化界面gui
2021-04-09 13:23:15 +08:00
Yao Fang 27d8ef4fb0 minor 2021-04-09 13:21:53 +08:00
Yao Fang dc1e2d13c0 add gui 2021-04-09 13:06:19 +08:00
Yao Fang 4d8c37d20f add few code 2021-04-08 19:16:45 +08:00
Yao Fang 697e00d6d4 修改GUI文件 2021-04-08 17:16:15 +08:00
Yao Fang 821ae87ac2 add gui 2021-04-08 10:18:01 +08:00
Yao Fang e4bfb324dc add light/fast model 2021-04-08 09:13:15 +08:00
Yao Fang 7c5849ebe5 add google_colab.ipynb 2021-04-01 15:29:23 +08:00
Yao Fang 5b40900933 Delete google_colab.ipynb 2021-04-01 15:28:47 +08:00
Yao Fang 0ed6e6ab52 Merge pull request #5 from YaoFANGUK/add-license-1
Create LICENSE
2021-03-31 17:29:37 +08:00
Yao Fang d5bf96a764 Create LICENSE 2021-03-31 17:29:21 +08:00
Yao Fang cfa711ba9a update readme 2021-03-30 14:39:04 +08:00
Yao Fang fe82dd8605 建议白嫖colab的gpu提取字幕 2021-03-30 13:10:24 +08:00
Yao Fang f36733ee3e Update README.md 2021-03-30 11:58:17 +08:00
Yao Fang c9c4eddac6 Update requirements_gpu.txt 2021-03-30 11:57:52 +08:00
Yao Fang 048302b38b Rename requirements(gpu).txt to requirements_gpu.txt 2021-03-30 11:47:44 +08:00
Yao Fang 217c523092 add requirements(gpu) file 2021-03-30 11:44:19 +08:00
Yao Fang 0f60c36eed add cache delete func 2021-03-29 17:57:45 +08:00
Yao Fang 6789a49b9d Merge pull request #4 from YaoFANGUK/dev
improve performance
2021-03-28 14:39:03 +08:00
方耀 4c2182cd86 improve performance 2021-03-28 14:38:08 +08:00
方耀 6f642d3961 add minor function 2021-03-28 09:38:56 +08:00
方耀 5a5ad32769 fix minor bug 2021-03-27 03:50:35 +08:00
方耀 56703ea78f compatible for windows 2021-03-27 03:38:30 +08:00
Yao Fang b592e9d60d add some gui component 2021-03-26 19:26:20 +08:00
Yao Fang f0b45846db add UI design graph 2021-03-26 17:08:58 +08:00
Yao Fang 4a700ccd1c update readme.md 2021-03-26 16:23:41 +08:00
Yao Fang f7d93ef1e3 update main.py 2021-03-26 15:56:31 +08:00
Yao Fang af17b54a76 update gitignore 2021-03-26 15:52:13 +08:00
Yao Fang 531c36427d update requirements 2021-03-26 11:11:58 +08:00
62 changed files with 5928 additions and 199 deletions

No files matched your search

+3
View File
@@ -349,3 +349,6 @@ $RECYCLE.BIN/
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/intellij+all,python,pycharm+all,macos,windows
/backend/models/ch_rec/inference.pdiparams
/output/
/test.py
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+80 -26
View File
@@ -1,23 +1,59 @@
简体中文 | [English](README_en.md)
## 项目简介
![License](https://img.shields.io/badge/License-Apache%202-red.svg)
![python version](https://img.shields.io/badge/Python-3.7+-blue.svg)
![support os](https://img.shields.io/badge/OS-Windows/macOS/Linux-green.svg)
video-subtitle-extractor是一款将视频中的硬字幕提取为外挂字幕文件(srt格式)的软件。
主要实现了以下功能:
- 提取视频中的关键帧
- 检测视频帧中文本的所在位置
- 识别视频帧中文本的内容
- 过滤非字幕区域的文本
- 去除重复字幕行,去除水印(台标)文本
- 生成srt字幕文件
## 项目特色
- 提取视频中的字幕,生成字幕文件,将水印(台标)等文本信息去除
- 采用PaddleOCR,无需设置调用任何API,不需要接入百度、阿里等OCR服务即可本地完成文本识别
- 无需用户手动设置字幕区域,该项目引入Paddle文本检测模型自动检测字幕区域
- 采用本地进行OCR识别,无需设置调用任何API,不需要接入百度、阿里等在线OCR服务即可本地完成文本识别
- 支持GPU加速,GPU加速后可以获得更高的准确率与更快的提取速度
- (CLI版本) 无需用户手动设置字幕区域,项目通过文本检测模型自动检测字幕区域
- (GUI版本) 图形化界面
<img src="https://z3.ax1x.com/2021/04/09/cNrA1A.png">
点击【打开】后选择视频文件,调整字幕区域,点击【运行】
> **有任何改进意见请在ISSUES中提出**
## 演示视频 (CLI版)
- GUI版:
<div align="center">
<img src="design/demo.gif"/>
</div>
- CLI版:
[![Demo Video](https://s1.ax1x.com/2020/10/05/0JWVeJ.png)](https://www.bilibili.com/video/BV1t5411h78J "Demo Video")
## 在线运行
- 使用**Google Colab Notebook**(免费GPU): <a href="https://colab.research.google.com/github/YaoFANGUK/video-subtitle-extractor/blob/main/google_colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
> PS: Google Colab只能运行CLI版本
## 使用说明
- 下载项目文件,将工作目录切换到项目文件所在目录
```shell
cd video-subtitle-extractor
```
#### 1. 下载安装Anaconda
#### 1. (推荐) 下载安装Anaconda
<a href="https://www.anaconda.com/products/individual">https://www.anaconda.com/products/individual#Downloads</a>
#### 2. 使用conda创建项目虚拟环境并激活环境 (建议创建虚拟环境运行,也可以不用conda)
#### 2. (推荐) 使用conda创建项目虚拟环境并激活环境 (建议创建虚拟环境运行,以免后续出现问题)
```shell
conda create --name videoEnv python=3.7
@@ -26,35 +62,53 @@ conda activate videoEnv
#### 3. 使用pip安装依赖文件
- mac用户, cpu用户:
如果没有安装Anaconda,请确保你已经安装 python 3.7
- mac用户, CPU用户:
```shell
pip install -r requirements.txt
```
- gpu用户:(使用cuda版本10.2)
- 有N卡的GPU用户: **要达到高精度的识别率请使用GPU版**
```shell
pip install -r requirements(gpu).txt
pip install -r requirements_gpu.txt
```
#### 4. 运行程序
> 对于gpu用户:
> 请将config.py中第48行 USE_GPU = False 改为:
```python
USE_GPU = True
```
> 运行
- 运行图形化界面版本(GUI)
```shell
python gui.py
```
- 运行命令行版本(CLI)
```shell
python main.py
```
## 演示视频
## Debug
[![Demo Video](https://s1.ax1x.com/2020/10/05/0JWVeJ.png)](https://www.bilibili.com/video/BV1t5411h78J "Demo Video")
- Windows下出现geos_c.dll错误
```integrationperformancetest
_lgeos = CDLL(os.path.join(sys.prefix, 'Library', 'bin', 'geos_c.dll'))
File "C:\Users\Flavi\anaconda3\envs\subEnv\lib\ctypes\__init__.py", line 364, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] 找不到指定的模块。
```
解决方案:
1) 卸载Shapely
```shell
pip uninstall Shapely -y
```
2) 使用conda重新安装Shapely
```shell
conda install Shapely
```
+117
View File
@@ -0,0 +1,117 @@
[简体中文](README.md) | English
## Introduction
![License](https://img.shields.io/badge/license-Apache%202-red.svg)
![python version](https://img.shields.io/badge/python-3.7+-blue.svg)
![support os](https://img.shields.io/badge/OS-Windows/macOS/Linux-green.svg)
video-subtitle-extractor is used to extract hard-coded subtitles and generate **srt** file. It includes the following implementations:
- detect and extract subtitle frames (and keyframes using traditional graphic method)
- detect the position (i.e. coordinates) of subtitles (as well as scene text if you want) (using deep learning method)
- recognise the content of subtitles (i.e. converting graphic text into plain-text) (using deep learning method)
- filter non-subtitle text
- remove duplicated subtitle line
- generate srt file
## Features
- You don't need to do any preprocessing to get an ideal result.
- This is an offline project. You don't need to make any API call from Internet service provider in order to get results.
- For Command Line Interface(CLI) version, you don't need to manually set the location of subtitle. This program will automatically detect the subtitle area for you.
- GPU support is available. You can install CUDA and cuDNN to speed up the detection and recognition process and even get more accurate results.
## Demo
- Graphic User Interface:
<img src="https://z3.ax1x.com/2021/04/09/cNrA1A.png">
<div align="center">
<img src="design/demo.gif"/>
</div>
- Command Line Interface:
[![Demo Video](https://s1.ax1x.com/2020/10/05/0JWVeJ.png)](https://www.bilibili.com/video/BV1t5411h78J "Demo Video")
## Getting Started
#### 1. (Optional) Download and Install Anaconda
<a href="https://www.anaconda.com/products/individual">https://www.anaconda.com/products/individual#Downloads</a>
#### 2. (Optional) create and activate a conda virtual environment
```shell
conda create --name videoEnv python=3.7
conda activate videoEnv
```
#### 3. Install dependencies via pip
make sure you have python 3.7 installed
- for macOS users and users who have CPU only:
```shell
pip install -r requirements.txt
```
- for users who have Nvidia graphic card:
```shell
pip install -r requirements_gpu.txt
```
#### 4. Running the program
- Run GUI version
```shell
python gui.py
```
- Run CLI version
```shell
python main.py
```
## Run on Google Colab
- **Google Colab Notebook with free GPU**: <a href="https://colab.research.google.com/github/YaoFANGUK/video-subtitle-extractor/blob/main/google_colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
## Debug
- For Windows users, if you encounter errors related to "geos_c.dll"
```text
_lgeos = CDLL(os.path.join(sys.prefix, 'Library', 'bin', 'geos_c.dll'))
File "C:\Users\Flavi\anaconda3\envs\subEnv\lib\ctypes\__init__.py", line 364, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found。
```
Solution:
1) Uninstall Shapely
```shell
pip uninstall Shapely -y
```
2) Reinstall Shapely via conda (make sure you have anaconda or miniconda installed)
```shell
conda install Shapely
```
@@ -0,0 +1,134 @@
Global:
use_gpu: true
epoch_num: 1200
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/ch_db_mv3/
save_epoch_step: 1200
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [3000, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/MobileNetV3_large_x0_5_pretrained
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_en/img_10.jpg
save_res_path: ./output/det_db/predicts_db.txt
Architecture:
model_type: det
algorithm: DB
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
disable_se: True
Neck:
name: DBFPN
out_channels: 96
Head:
name: DBHead
k: 50
Loss:
name: DBLoss
balance_loss: true
main_loss_type: DiceLoss
alpha: 5
beta: 10
ohem_ratio: 3
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
warmup_epoch: 2
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: DBPostProcess
thresh: 0.3
box_thresh: 0.6
max_candidates: 1000
unclip_ratio: 1.5
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- IaaAugment:
augmenter_args:
- { 'type': Fliplr, 'args': { 'p': 0.5 } }
- { 'type': Affine, 'args': { 'rotate': [-10, 10] } }
- { 'type': Resize, 'args': { 'size': [0.5, 3] } }
- EastRandomCropData:
size: [960, 960]
max_tries: 50
keep_ratio: true
- MakeBorderMap:
shrink_ratio: 0.4
thresh_min: 0.3
thresh_max: 0.7
- MakeShrinkMap:
shrink_ratio: 0.4
min_text_size: 8
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'threshold_map', 'threshold_mask', 'shrink_map', 'shrink_mask'] # the order of the dataloader list
loader:
shuffle: True
drop_last: False
batch_size_per_card: 8
num_workers: 4
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
# image_shape: [736, 1280]
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
@@ -0,0 +1,133 @@
Global:
use_gpu: true
epoch_num: 1200
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/ch_db_res18/
save_epoch_step: 1200
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [3000, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/ResNet18_vd_pretrained
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_en/img_10.jpg
save_res_path: ./output/det_db/predicts_db.txt
Architecture:
model_type: det
algorithm: DB
Transform:
Backbone:
name: ResNet
layers: 18
disable_se: True
Neck:
name: DBFPN
out_channels: 256
Head:
name: DBHead
k: 50
Loss:
name: DBLoss
balance_loss: true
main_loss_type: DiceLoss
alpha: 5
beta: 10
ohem_ratio: 3
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
warmup_epoch: 2
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: DBPostProcess
thresh: 0.3
box_thresh: 0.6
max_candidates: 1000
unclip_ratio: 1.5
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- IaaAugment:
augmenter_args:
- { 'type': Fliplr, 'args': { 'p': 0.5 } }
- { 'type': Affine, 'args': { 'rotate': [-10, 10] } }
- { 'type': Resize, 'args': { 'size': [0.5, 3] } }
- EastRandomCropData:
size: [960, 960]
max_tries: 50
keep_ratio: true
- MakeBorderMap:
shrink_ratio: 0.4
thresh_min: 0.3
thresh_max: 0.7
- MakeShrinkMap:
shrink_ratio: 0.4
min_text_size: 8
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'threshold_map', 'threshold_mask', 'shrink_map', 'shrink_mask'] # the order of the dataloader list
loader:
shuffle: True
drop_last: False
batch_size_per_card: 8
num_workers: 4
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
# image_shape: [736, 1280]
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
+133
View File
@@ -0,0 +1,133 @@
Global:
use_gpu: true
epoch_num: 1200
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/db_mv3/
save_epoch_step: 1200
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/MobileNetV3_large_x0_5_pretrained
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_en/img_10.jpg
save_res_path: ./output/det_db/predicts_db.txt
Architecture:
model_type: det
algorithm: DB
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: DBFPN
out_channels: 256
Head:
name: DBHead
k: 50
Loss:
name: DBLoss
balance_loss: true
main_loss_type: DiceLoss
alpha: 5
beta: 10
ohem_ratio: 3
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: DBPostProcess
thresh: 0.3
box_thresh: 0.6
max_candidates: 1000
unclip_ratio: 1.5
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- IaaAugment:
augmenter_args:
- { 'type': Fliplr, 'args': { 'p': 0.5 } }
- { 'type': Affine, 'args': { 'rotate': [-10, 10] } }
- { 'type': Resize, 'args': { 'size': [0.5, 3] } }
- EastRandomCropData:
size: [640, 640]
max_tries: 50
keep_ratio: true
- MakeBorderMap:
shrink_ratio: 0.4
thresh_min: 0.3
thresh_max: 0.7
- MakeShrinkMap:
shrink_ratio: 0.4
min_text_size: 8
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'threshold_map', 'threshold_mask', 'shrink_map', 'shrink_mask'] # the order of the dataloader list
loader:
shuffle: True
drop_last: False
batch_size_per_card: 16
num_workers: 8
use_shared_memory: False
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
image_shape: [736, 1280]
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 8
use_shared_memory: False
+111
View File
@@ -0,0 +1,111 @@
Global:
use_gpu: true
epoch_num: 10000
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/east_mv3/
save_epoch_step: 1000
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [4000, 5000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/MobileNetV3_large_x0_5_pretrained
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
save_res_path: ./output/det_east/predicts_east.txt
Architecture:
model_type: det
algorithm: EAST
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: EASTFPN
model_name: small
Head:
name: EASTHead
model_name: small
Loss:
name: EASTLoss
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
# name: Cosine
learning_rate: 0.001
# warmup_epoch: 0
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: EASTPostProcess
score_thresh: 0.8
cover_thresh: 0.1
nms_thresh: 0.2
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- EASTProcessTrain:
image_shape: [512, 512]
background_ratio: 0.125
min_crop_side_ratio: 0.1
min_text_size: 10
- KeepKeys:
keep_keys: ['image', 'score_map', 'geo_map', 'training_mask'] # dataloader will return list in this order
loader:
shuffle: True
drop_last: False
batch_size_per_card: 16
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
limit_side_len: 2400
limit_type: max
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
+130
View File
@@ -0,0 +1,130 @@
Global:
use_gpu: true
epoch_num: 1200
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/det_r50_vd/
save_epoch_step: 1200
# evaluation is run every 2000 iterations
eval_batch_step: [0,2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/ResNet50_vd_ssld_pretrained
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_en/img_10.jpg
save_res_path: ./output/det_db/predicts_db.txt
Architecture:
model_type: det
algorithm: DB
Transform:
Backbone:
name: ResNet
layers: 50
Neck:
name: DBFPN
out_channels: 256
Head:
name: DBHead
k: 50
Loss:
name: DBLoss
balance_loss: true
main_loss_type: DiceLoss
alpha: 5
beta: 10
ohem_ratio: 3
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: DBPostProcess
thresh: 0.3
box_thresh: 0.7
max_candidates: 1000
unclip_ratio: 1.5
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- IaaAugment:
augmenter_args:
- { 'type': Fliplr, 'args': { 'p': 0.5 } }
- { 'type': Affine, 'args': { 'rotate': [-10, 10] } }
- { 'type': Resize, 'args': { 'size': [0.5, 3] } }
- EastRandomCropData:
size: [640, 640]
max_tries: 50
keep_ratio: true
- MakeBorderMap:
shrink_ratio: 0.4
thresh_min: 0.3
thresh_max: 0.7
- MakeShrinkMap:
shrink_ratio: 0.4
min_text_size: 8
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'threshold_map', 'threshold_mask', 'shrink_map', 'shrink_mask'] # the order of the dataloader list
loader:
shuffle: True
drop_last: False
batch_size_per_card: 16
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
image_shape: [736, 1280]
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 8
+110
View File
@@ -0,0 +1,110 @@
Global:
use_gpu: true
epoch_num: 10000
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/east_r50_vd/
save_epoch_step: 1000
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [4000, 5000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/ResNet50_vd_pretrained/
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
save_res_path: ./output/det_east/predicts_east.txt
Architecture:
model_type: det
algorithm: EAST
Transform:
Backbone:
name: ResNet
layers: 50
Neck:
name: EASTFPN
model_name: large
Head:
name: EASTHead
model_name: large
Loss:
name: EASTLoss
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
# name: Cosine
learning_rate: 0.001
# warmup_epoch: 0
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: EASTPostProcess
score_thresh: 0.8
cover_thresh: 0.1
nms_thresh: 0.2
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/train_icdar2015_label.txt
ratio_list: [1.0]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- EASTProcessTrain:
image_shape: [512, 512]
background_ratio: 0.125
min_crop_side_ratio: 0.1
min_text_size: 10
- KeepKeys:
keep_keys: ['image', 'score_map', 'geo_map', 'training_mask'] # dataloader will return list in this order
loader:
shuffle: True
drop_last: False
batch_size_per_card: 8
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
limit_side_len: 2400
limit_type: max
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
+110
View File
@@ -0,0 +1,110 @@
Global:
use_gpu: true
epoch_num: 5000
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/sast_r50_vd_ic15/
save_epoch_step: 1000
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [4000, 5000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/ResNet50_vd_ssld_pretrained/
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
save_res_path: ./output/sast_r50_vd_ic15/predicts_sast.txt
Architecture:
model_type: det
algorithm: SAST
Transform:
Backbone:
name: ResNet_SAST
layers: 50
Neck:
name: SASTFPN
with_cab: True
Head:
name: SASTHead
Loss:
name: SASTLoss
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
# name: Cosine
learning_rate: 0.001
# warmup_epoch: 0
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: SASTPostProcess
score_thresh: 0.5
sample_pts_num: 2
nms_thresh: 0.2
expand_scale: 1.0
shrink_ratio_of_width: 0.3
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: [./train_data/icdar2013/train_label_json.txt, ./train_data/icdar2015/train_label_json.txt, ./train_data/icdar17_mlt_latin/train_label_json.txt, ./train_data/coco_text_icdar_4pts/train_label_json.txt]
ratio_list: [0.1, 0.45, 0.3, 0.15]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- SASTProcessTrain:
image_shape: [512, 512]
min_crop_side_ratio: 0.3
min_crop_size: 24
min_text_size: 4
max_text_size: 512
- KeepKeys:
keep_keys: ['image', 'score_map', 'border_map', 'training_mask', 'tvo_map', 'tco_map'] # dataloader will return list in this order
loader:
shuffle: True
drop_last: False
batch_size_per_card: 4
num_workers: 4
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/icdar2015/text_localization/
label_file_list:
- ./train_data/icdar2015/text_localization/test_icdar2015_label.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
resize_long: 1536
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
+110
View File
@@ -0,0 +1,110 @@
Global:
use_gpu: true
epoch_num: 5000
log_smooth_window: 20
print_batch_step: 2
save_model_dir: ./output/sast_r50_vd_tt/
save_epoch_step: 1000
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [4000, 5000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
load_static_weights: True
cal_metric_during_train: False
pretrained_model: ./pretrain_models/ResNet50_vd_ssld_pretrained/
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
save_res_path: ./output/sast_r50_vd_tt/predicts_sast.txt
Architecture:
model_type: det
algorithm: SAST
Transform:
Backbone:
name: ResNet_SAST
layers: 50
Neck:
name: SASTFPN
with_cab: True
Head:
name: SASTHead
Loss:
name: SASTLoss
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
# name: Cosine
learning_rate: 0.001
# warmup_epoch: 0
regularizer:
name: 'L2'
factor: 0
PostProcess:
name: SASTPostProcess
score_thresh: 0.5
sample_pts_num: 6
nms_thresh: 0.2
expand_scale: 1.2
shrink_ratio_of_width: 0.2
Metric:
name: DetMetric
main_indicator: hmean
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: [./train_data/art_latin_icdar_14pt/train_no_tt_test/train_label_json.txt, ./train_data/total_text_icdar_14pt/train_label_json.txt]
ratio_list: [0.5, 0.5]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- SASTProcessTrain:
image_shape: [512, 512]
min_crop_side_ratio: 0.3
min_crop_size: 24
min_text_size: 4
max_text_size: 512
- KeepKeys:
keep_keys: ['image', 'score_map', 'border_map', 'training_mask', 'tvo_map', 'tco_map'] # dataloader will return list in this order
loader:
shuffle: True
drop_last: False
batch_size_per_card: 4
num_workers: 4
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list:
- ./train_data/total_text_icdar_14pt/test_label_json.txt
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- DetLabelEncode: # Class handling label
- DetResizeForTest:
resize_long: 768
- NormalizeImage:
scale: 1./255.
mean: [0.485, 0.456, 0.406]
std: [0.229, 0.224, 0.225]
order: 'hwc'
- ToCHWImage:
- KeepKeys:
keep_keys: ['image', 'shape', 'polys', 'ignore_tags']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 1 # must be 1
num_workers: 2
@@ -0,0 +1,100 @@
Global:
use_gpu: true
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_chinese_common_v2.0
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words/ch/word_1.jpg
# for data or label process
character_dict_path: ppocr/utils/ppocr_keys_v1.txt
character_type: ch
max_text_length: 25
infer_mode: False
use_space_char: True
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00004
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: ResNet
layers: 34
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 256
Head:
name: CTCHead
fc_decay: 0.00004
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/val_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: true
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_chinese_lite_v2.0
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words/ch/word_1.jpg
# for data or label process
character_dict_path: ppocr/utils/ppocr_keys_v1.txt
character_type: ch
max_text_length: 25
infer_mode: False
use_space_char: True
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data
label_file_list: ["./train_data/val_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,200 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import yaml
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import os.path
import logging
logging.basicConfig(level=logging.INFO)
support_list = {
'it': 'italian',
'es': 'spanish',
'pt': 'portuguese',
'ru': 'russian',
'ar': 'arabic',
'ta': 'tamil',
'ug': 'uyghur',
'fa': 'persian',
'ur': 'urdu',
'rs_latin': 'serbian latin',
'oc': 'occitan',
'rs_cyrillic': 'serbian cyrillic',
'bg': 'bulgarian',
'uk': 'ukranian',
'be': 'belarusian',
'te': 'telugu',
'kn': 'kannada',
'ch_tra': 'chinese tradition',
'hi': 'hindi',
'mr': 'marathi',
'ne': 'nepali',
}
assert (os.path.isfile("./rec_multi_language_lite_train.yml")
), "Loss basic configuration file rec_multi_language_lite_train.yml.\
You can download it from \
https://github.com/PaddlePaddle/PaddleOCR/tree/dygraph/configs/rec/multi_language/"
global_config = yaml.load(
open("./rec_multi_language_lite_train.yml", 'rb'), Loader=yaml.Loader)
project_path = os.path.abspath(os.path.join(os.getcwd(), "../../../"))
class ArgsParser(ArgumentParser):
def __init__(self):
super(ArgsParser, self).__init__(
formatter_class=RawDescriptionHelpFormatter)
self.add_argument(
"-o", "--opt", nargs='+', help="set configuration options")
self.add_argument(
"-l",
"--language",
nargs='+',
help="set language type, support {}".format(support_list))
self.add_argument(
"--train",
type=str,
help="you can use this command to change the train dataset default path"
)
self.add_argument(
"--val",
type=str,
help="you can use this command to change the eval dataset default path"
)
self.add_argument(
"--dict",
type=str,
help="you can use this command to change the dictionary default path"
)
self.add_argument(
"--data_dir",
type=str,
help="you can use this command to change the dataset default root path"
)
def parse_args(self, argv=None):
args = super(ArgsParser, self).parse_args(argv)
args.opt = self._parse_opt(args.opt)
args.language = self._set_language(args.language)
return args
def _parse_opt(self, opts):
config = {}
if not opts:
return config
for s in opts:
s = s.strip()
k, v = s.split('=')
config[k] = yaml.load(v, Loader=yaml.Loader)
return config
def _set_language(self, type):
assert (type), "please use -l or --language to choose language type"
assert(
type[0] in support_list.keys()
),"the sub_keys(-l or --language) can only be one of support list: \n{},\nbut get: {}, " \
"please check your running command".format(support_list, type)
global_config['Global'][
'character_dict_path'] = 'ppocr/utils/dict/{}_dict.txt'.format(type[
0])
global_config['Global'][
'save_model_dir'] = './output/rec_{}_lite'.format(type[0])
global_config['Train']['dataset'][
'label_file_list'] = ["train_data/{}_train.txt".format(type[0])]
global_config['Eval']['dataset'][
'label_file_list'] = ["train_data/{}_val.txt".format(type[0])]
global_config['Global']['character_type'] = type[0]
assert (
os.path.isfile(
os.path.join(project_path, global_config['Global'][
'character_dict_path']))
), "Loss default dictionary file {}_dict.txt.You can download it from \
https://github.com/PaddlePaddle/PaddleOCR/tree/dygraph/ppocr/utils/dict/".format(
type[0])
return type[0]
def merge_config(config):
"""
Merge config into global config.
Args:
config (dict): Config to be merged.
Returns: global config
"""
for key, value in config.items():
if "." not in key:
if isinstance(value, dict) and key in global_config:
global_config[key].update(value)
else:
global_config[key] = value
else:
sub_keys = key.split('.')
assert (
sub_keys[0] in global_config
), "the sub_keys can only be one of global_config: {}, but get: {}, please check your running command".format(
global_config.keys(), sub_keys[0])
cur = global_config[sub_keys[0]]
for idx, sub_key in enumerate(sub_keys[1:]):
if idx == len(sub_keys) - 2:
cur[sub_key] = value
else:
cur = cur[sub_key]
def loss_file(path):
assert (
os.path.exists(path)
), "There is no such file:{},Please do not forget to put in the specified file".format(
path)
if __name__ == '__main__':
FLAGS = ArgsParser().parse_args()
merge_config(FLAGS.opt)
save_file_path = 'rec_{}_lite_train.yml'.format(FLAGS.language)
if os.path.isfile(save_file_path):
os.remove(save_file_path)
if FLAGS.train:
global_config['Train']['dataset']['label_file_list'] = [FLAGS.train]
train_label_path = os.path.join(project_path, FLAGS.train)
loss_file(train_label_path)
if FLAGS.val:
global_config['Eval']['dataset']['label_file_list'] = [FLAGS.val]
eval_label_path = os.path.join(project_path, FLAGS.val)
loss_file(eval_label_path)
if FLAGS.dict:
global_config['Global']['character_dict_path'] = FLAGS.dict
dict_path = os.path.join(project_path, FLAGS.dict)
loss_file(dict_path)
if FLAGS.data_dir:
global_config['Eval']['dataset']['data_dir'] = FLAGS.data_dir
global_config['Train']['dataset']['data_dir'] = FLAGS.data_dir
data_dir = os.path.join(project_path, FLAGS.data_dir)
loss_file(data_dir)
with open(save_file_path, 'w') as f:
yaml.dump(
dict(global_config), f, default_flow_style=False, sort_keys=False)
logging.info("Project path is :{}".format(project_path))
logging.info("Train list path set to :{}".format(global_config['Train'][
'dataset']['label_file_list'][0]))
logging.info("Eval list path set to :{}".format(global_config['Eval'][
'dataset']['label_file_list'][0]))
logging.info("Dataset root path set to :{}".format(global_config['Eval'][
'dataset']['data_dir']))
logging.info("Dict path set to :{}".format(global_config['Global'][
'character_dict_path']))
logging.info("Config file set to :configs/rec/multi_language/{}".
format(save_file_path))
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_en_number_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path: ppocr/utils/dict/en_dict.txt
character_type: EN
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/eval_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_french_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path: ppocr/utils/dict/french_dict.txt
character_type: french
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/eval_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_german_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path: ppocr/utils/dict/german_dict.txt
character_type: german
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/eval_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_japan_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path: ppocr/utils/dict/japan_dict.txt
character_type: japan
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/eval_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_korean_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path: ppocr/utils/dict/korean_dict.txt
character_type: korean
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/eval_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,103 @@
Global:
use_gpu: True
epoch_num: 500
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec_multi_language_lite
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img:
# for data or label process
character_dict_path:
# Set the language of training, if set, select the default dictionary file
character_type:
max_text_length: 25
infer_mode: False
use_space_char: True
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
name: Cosine
learning_rate: 0.001
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: small
small_stride: [1, 2, 2, 2]
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 48
Head:
name: CTCHead
fc_decay: 0.00001
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- RecAug:
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: SimpleDataSet
data_dir: train_data/
label_file_list: ["./train_data/val_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 320]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
+100
View File
@@ -0,0 +1,100 @@
Global:
use_gpu: true
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/ic15/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path: ppocr/utils/ic15_dict.txt
character_type: ch
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 96
Head:
name: CTCHead
fc_decay: 0
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
use_shared_memory: False
Eval:
dataset:
name: SimpleDataSet
data_dir: ./train_data/
label_file_list: ["./train_data/train_list.txt"]
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
use_shared_memory: False
@@ -0,0 +1,96 @@
Global:
use_gpu: True
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/mv3_none_bilstm_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 96
Head:
name: CTCHead
fc_decay: 0
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
@@ -0,0 +1,95 @@
Global:
use_gpu: True
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/mv3_none_none_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: Rosetta
Transform:
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: SequenceEncoder
encoder_type: reshape
Head:
name: CTCHead
fc_decay: 0.0004
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,102 @@
Global:
use_gpu: True
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/rec_mv3_tps_bilstm_att/
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words/ch/word_1.jpg
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0.00001
Architecture:
model_type: rec
algorithm: RARE
Transform:
name: TPS
num_fiducial: 20
loc_lr: 0.1
model_name: small
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 96
Head:
name: AttentionHead
hidden_size: 96
Loss:
name: AttentionLoss
PostProcess:
name: AttnLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- AttnLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- AttnLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 1
@@ -0,0 +1,100 @@
Global:
use_gpu: True
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/mv3_tps_bilstm_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: STARNet
Transform:
name: TPS
num_fiducial: 20
loc_lr: 0.1
model_name: small
Backbone:
name: MobileNetV3
scale: 0.5
model_name: large
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 96
Head:
name: CTCHead
fc_decay: 0.0004
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
@@ -0,0 +1,95 @@
Global:
use_gpu: true
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/r34_vd_none_bilstm_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: CRNN
Transform:
Backbone:
name: ResNet
layers: 34
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 256
Head:
name: CTCHead
fc_decay: 0
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
@@ -0,0 +1,93 @@
Global:
use_gpu: true
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/r34_vd_none_none_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: Rosetta
Backbone:
name: ResNet
layers: 34
Neck:
name: SequenceEncoder
encoder_type: reshape
Head:
name: CTCHead
fc_decay: 0.0004
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
@@ -0,0 +1,101 @@
Global:
use_gpu: True
epoch_num: 400
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/b3_rare_r34_none_gru/
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words/ch/word_1.jpg
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0.00000
Architecture:
model_type: rec
algorithm: RARE
Transform:
name: TPS
num_fiducial: 20
loc_lr: 0.1
model_name: large
Backbone:
name: ResNet
layers: 34
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 256 #96
Head:
name: AttentionHead # AttentionHead
hidden_size: 256 #
l2_decay: 0.00001
Loss:
name: AttentionLoss
PostProcess:
name: AttnLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- AttnLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- AttnLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 8
@@ -0,0 +1,99 @@
Global:
use_gpu: true
epoch_num: 72
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/rec/r34_vd_tps_bilstm_ctc/
save_epoch_step: 3
# evaluation is run every 2000 iterations
eval_batch_step: [0, 2000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words_en/word_10.png
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
lr:
learning_rate: 0.0005
regularizer:
name: 'L2'
factor: 0
Architecture:
model_type: rec
algorithm: STARNet
Transform:
name: TPS
num_fiducial: 20
loc_lr: 0.1
model_name: small
Backbone:
name: ResNet
layers: 34
Neck:
name: SequenceEncoder
encoder_type: rnn
hidden_size: 256
Head:
name: CTCHead
fc_decay: 0
Loss:
name: CTCLoss
PostProcess:
name: CTCLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: True
batch_size_per_card: 256
drop_last: True
num_workers: 8
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- CTCLabelEncode: # Class handling label
- RecResizeImg:
image_shape: [3, 32, 100]
- KeepKeys:
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
loader:
shuffle: False
drop_last: False
batch_size_per_card: 256
num_workers: 4
+107
View File
@@ -0,0 +1,107 @@
Global:
use_gpu: True
epoch_num: 72
log_smooth_window: 20
print_batch_step: 5
save_model_dir: ./output/rec/srn_new
save_epoch_step: 3
# evaluation is run every 5000 iterations after the 4000th iteration
eval_batch_step: [0, 5000]
# if pretrained_model is saved in static mode, load_static_weights must set to True
cal_metric_during_train: True
pretrained_model:
checkpoints:
save_inference_dir:
use_visualdl: False
infer_img: doc/imgs_words/ch/word_1.jpg
# for data or label process
character_dict_path:
character_type: en
max_text_length: 25
num_heads: 8
infer_mode: False
use_space_char: False
Optimizer:
name: Adam
beta1: 0.9
beta2: 0.999
clip_norm: 10.0
lr:
learning_rate: 0.0001
Architecture:
model_type: rec
algorithm: SRN
in_channels: 1
Transform:
Backbone:
name: ResNetFPN
Head:
name: SRNHead
max_text_length: 25
num_heads: 8
num_encoder_TUs: 2
num_decoder_TUs: 4
hidden_dims: 512
Loss:
name: SRNLoss
PostProcess:
name: SRNLabelDecode
Metric:
name: RecMetric
main_indicator: acc
Train:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/training/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- SRNLabelEncode: # Class handling label
- SRNRecResizeImg:
image_shape: [1, 64, 256]
- KeepKeys:
keep_keys: ['image',
'label',
'length',
'encoder_word_pos',
'gsrm_word_pos',
'gsrm_slf_attn_bias1',
'gsrm_slf_attn_bias2'] # dataloader will return list in this order
loader:
shuffle: False
batch_size_per_card: 64
drop_last: False
num_workers: 4
Eval:
dataset:
name: LMDBDataSet
data_dir: ./train_data/data_lmdb_release/validation/
transforms:
- DecodeImage: # load image
img_mode: BGR
channel_first: False
- SRNLabelEncode: # Class handling label
- SRNRecResizeImg:
image_shape: [1, 64, 256]
- KeepKeys:
keep_keys: ['image',
'label',
'length',
'encoder_word_pos',
'gsrm_word_pos',
'gsrm_slf_attn_bias1',
'gsrm_slf_attn_bias2']
loader:
shuffle: False
drop_last: False
batch_size_per_card: 32
num_workers: 4
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
filename,filesize,encoding,header
inference_1.pdiparams,50000000,,
inference_2.pdiparams,50000000,,
inference_3.pdiparams,11517375,,
1 filename filesize encoding header
2 inference_1.pdiparams 50000000
3 inference_2.pdiparams 50000000
4 inference_3.pdiparams 11517375
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+281
View File
@@ -0,0 +1,281 @@
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import string
class ClsLabelEncode(object):
def __init__(self, label_list, **kwargs):
self.label_list = label_list
def __call__(self, data):
label = data['label']
if label not in self.label_list:
return None
label = self.label_list.index(label)
data['label'] = label
return data
class DetLabelEncode(object):
def __init__(self, **kwargs):
pass
def __call__(self, data):
import json
label = data['label']
label = json.loads(label)
nBox = len(label)
boxes, txts, txt_tags = [], [], []
for bno in range(0, nBox):
box = label[bno]['points']
txt = label[bno]['transcription']
boxes.append(box)
txts.append(txt)
if txt in ['*', '###']:
txt_tags.append(True)
else:
txt_tags.append(False)
boxes = self.expand_points_num(boxes)
boxes = np.array(boxes, dtype=np.float32)
txt_tags = np.array(txt_tags, dtype=np.bool)
data['polys'] = boxes
data['texts'] = txts
data['ignore_tags'] = txt_tags
return data
def order_points_clockwise(self, pts):
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
def expand_points_num(self, boxes):
max_points_num = 0
for box in boxes:
if len(box) > max_points_num:
max_points_num = len(box)
ex_boxes = []
for box in boxes:
ex_box = box + [box[-1]] * (max_points_num - len(box))
ex_boxes.append(ex_box)
return ex_boxes
class BaseRecLabelEncode(object):
""" Convert between text-label and text-index """
def __init__(self,
max_text_length,
character_dict_path=None,
character_type='ch',
use_space_char=False):
support_character_type = [
'ch', 'en', 'EN_symbol', 'french', 'german', 'japan', 'korean',
'EN', 'it', 'es', 'pt', 'ru', 'ar', 'ta', 'ug', 'fa', 'ur',
'rs_latin', 'oc', 'rs_cyrillic', 'bg', 'uk', 'be', 'te', 'kn',
'ch_tra', 'hi', 'mr', 'ne'
]
assert character_type in support_character_type, "Only {} are supported now but get {}".format(
support_character_type, character_type)
self.max_text_len = max_text_length
self.beg_str = "sos"
self.end_str = "eos"
if character_type == "en":
self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
dict_character = list(self.character_str)
elif character_type == "EN_symbol":
# same with ASTER setting (use 94 char).
self.character_str = string.printable[:-6]
dict_character = list(self.character_str)
elif character_type in support_character_type:
self.character_str = ""
assert character_dict_path is not None, "character_dict_path should not be None when character_type is {}".format(
character_type)
with open(character_dict_path, "rb") as fin:
lines = fin.readlines()
for line in lines:
line = line.decode('utf-8').strip("\n").strip("\r\n")
self.character_str += line
if use_space_char:
self.character_str += " "
dict_character = list(self.character_str)
self.character_type = character_type
dict_character = self.add_special_char(dict_character)
self.dict = {}
for i, char in enumerate(dict_character):
self.dict[char] = i
self.character = dict_character
def add_special_char(self, dict_character):
return dict_character
def encode(self, text):
"""convert text-label into text-index.
input:
text: text labels of each image. [batch_size]
output:
text: concatenated text index for CTCLoss.
[sum(text_lengths)] = [text_index_0 + text_index_1 + ... + text_index_(n - 1)]
length: length of each text. [batch_size]
"""
if len(text) == 0 or len(text) > self.max_text_len:
return None
if self.character_type == "en":
text = text.lower()
text_list = []
for char in text:
if char not in self.dict:
# logger = get_logger()
# logger.warning('{} is not in dict'.format(char))
continue
text_list.append(self.dict[char])
if len(text_list) == 0:
return None
return text_list
class CTCLabelEncode(BaseRecLabelEncode):
""" Convert between text-label and text-index """
def __init__(self,
max_text_length,
character_dict_path=None,
character_type='ch',
use_space_char=False,
**kwargs):
super(CTCLabelEncode,
self).__init__(max_text_length, character_dict_path,
character_type, use_space_char)
def __call__(self, data):
text = data['label']
text = self.encode(text)
if text is None:
return None
data['length'] = np.array(len(text))
text = text + [0] * (self.max_text_len - len(text))
data['label'] = np.array(text)
return data
def add_special_char(self, dict_character):
dict_character = ['blank'] + dict_character
return dict_character
class AttnLabelEncode(BaseRecLabelEncode):
""" Convert between text-label and text-index """
def __init__(self,
max_text_length,
character_dict_path=None,
character_type='ch',
use_space_char=False,
**kwargs):
super(AttnLabelEncode,
self).__init__(max_text_length, character_dict_path,
character_type, use_space_char)
def add_special_char(self, dict_character):
self.beg_str = "sos"
self.end_str = "eos"
dict_character = [self.beg_str] + dict_character + [self.end_str]
return dict_character
def __call__(self, data):
text = data['label']
text = self.encode(text)
if text is None:
return None
if len(text) >= self.max_text_len:
return None
data['length'] = np.array(len(text))
text = [0] + text + [len(self.character) - 1] + [0] * (self.max_text_len
- len(text) - 2)
data['label'] = np.array(text)
return data
def get_ignored_tokens(self):
beg_idx = self.get_beg_end_flag_idx("beg")
end_idx = self.get_beg_end_flag_idx("end")
return [beg_idx, end_idx]
def get_beg_end_flag_idx(self, beg_or_end):
if beg_or_end == "beg":
idx = np.array(self.dict[self.beg_str])
elif beg_or_end == "end":
idx = np.array(self.dict[self.end_str])
else:
assert False, "Unsupport type %s in get_beg_end_flag_idx" \
% beg_or_end
return idx
class SRNLabelEncode(BaseRecLabelEncode):
""" Convert between text-label and text-index """
def __init__(self,
max_text_length=25,
character_dict_path=None,
character_type='en',
use_space_char=False,
**kwargs):
super(SRNLabelEncode,
self).__init__(max_text_length, character_dict_path,
character_type, use_space_char)
def add_special_char(self, dict_character):
dict_character = dict_character + [self.beg_str, self.end_str]
return dict_character
def __call__(self, data):
text = data['label']
text = self.encode(text)
char_num = len(self.character)
if text is None:
return None
if len(text) > self.max_text_len:
return None
data['length'] = np.array(len(text))
text = text + [char_num - 1] * (self.max_text_len - len(text))
data['label'] = np.array(text)
return data
def get_ignored_tokens(self):
beg_idx = self.get_beg_end_flag_idx("beg")
end_idx = self.get_beg_end_flag_idx("end")
return [beg_idx, end_idx]
def get_beg_end_flag_idx(self, beg_or_end):
if beg_or_end == "beg":
idx = np.array(self.dict[self.beg_str])
elif beg_or_end == "end":
idx = np.array(self.dict[self.end_str])
else:
assert False, "Unsupport type %s in get_beg_end_flag_idx" \
% beg_or_end
return idx
+225
View File
@@ -0,0 +1,225 @@
"""
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import six
import cv2
import numpy as np
class DecodeImage(object):
""" decode image """
def __init__(self, img_mode='RGB', channel_first=False, **kwargs):
self.img_mode = img_mode
self.channel_first = channel_first
def __call__(self, data):
img = data['image']
if six.PY2:
assert type(img) is str and len(
img) > 0, "invalid input 'img' in DecodeImage"
else:
assert type(img) is bytes and len(
img) > 0, "invalid input 'img' in DecodeImage"
img = np.frombuffer(img, dtype='uint8')
img = cv2.imdecode(img, 1)
if img is None:
return None
if self.img_mode == 'GRAY':
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
elif self.img_mode == 'RGB':
assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)
img = img[:, :, ::-1]
if self.channel_first:
img = img.transpose((2, 0, 1))
data['image'] = img
return data
class NormalizeImage(object):
""" normalize image such as substract mean, divide std
"""
def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs):
if isinstance(scale, str):
scale = eval(scale)
self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
mean = mean if mean is not None else [0.485, 0.456, 0.406]
std = std if std is not None else [0.229, 0.224, 0.225]
shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)
self.mean = np.array(mean).reshape(shape).astype('float32')
self.std = np.array(std).reshape(shape).astype('float32')
def __call__(self, data):
img = data['image']
from PIL import Image
if isinstance(img, Image.Image):
img = np.array(img)
assert isinstance(img,
np.ndarray), "invalid input 'img' in NormalizeImage"
data['image'] = (
img.astype('float32') * self.scale - self.mean) / self.std
return data
class ToCHWImage(object):
""" convert hwc image to chw image
"""
def __init__(self, **kwargs):
pass
def __call__(self, data):
img = data['image']
from PIL import Image
if isinstance(img, Image.Image):
img = np.array(img)
data['image'] = img.transpose((2, 0, 1))
return data
class KeepKeys(object):
def __init__(self, keep_keys, **kwargs):
self.keep_keys = keep_keys
def __call__(self, data):
data_list = []
for key in self.keep_keys:
data_list.append(data[key])
return data_list
class DetResizeForTest(object):
def __init__(self, **kwargs):
super(DetResizeForTest, self).__init__()
self.resize_type = 0
if 'image_shape' in kwargs:
self.image_shape = kwargs['image_shape']
self.resize_type = 1
elif 'limit_side_len' in kwargs:
self.limit_side_len = kwargs['limit_side_len']
self.limit_type = kwargs.get('limit_type', 'min')
elif 'resize_long' in kwargs:
self.resize_type = 2
self.resize_long = kwargs.get('resize_long', 960)
else:
self.limit_side_len = 736
self.limit_type = 'min'
def __call__(self, data):
img = data['image']
src_h, src_w, _ = img.shape
if self.resize_type == 0:
# img, shape = self.resize_image_type0(img)
img, [ratio_h, ratio_w] = self.resize_image_type0(img)
elif self.resize_type == 2:
img, [ratio_h, ratio_w] = self.resize_image_type2(img)
else:
# img, shape = self.resize_image_type1(img)
img, [ratio_h, ratio_w] = self.resize_image_type1(img)
data['image'] = img
data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w])
return data
def resize_image_type1(self, img):
resize_h, resize_w = self.image_shape
ori_h, ori_w = img.shape[:2] # (h, w, c)
ratio_h = float(resize_h) / ori_h
ratio_w = float(resize_w) / ori_w
img = cv2.resize(img, (int(resize_w), int(resize_h)))
# return img, np.array([ori_h, ori_w])
return img, [ratio_h, ratio_w]
def resize_image_type0(self, img):
"""
resize image to a size multiple of 32 which is required by the network
args:
img(array): array with shape [h, w, c]
return(tuple):
img, (ratio_h, ratio_w)
"""
limit_side_len = self.limit_side_len
h, w, _ = img.shape
# limit the max side
if self.limit_type == 'max':
if max(h, w) > limit_side_len:
if h > w:
ratio = float(limit_side_len) / h
else:
ratio = float(limit_side_len) / w
else:
ratio = 1.
else:
if min(h, w) < limit_side_len:
if h < w:
ratio = float(limit_side_len) / h
else:
ratio = float(limit_side_len) / w
else:
ratio = 1.
resize_h = int(h * ratio)
resize_w = int(w * ratio)
resize_h = int(round(resize_h / 32) * 32)
resize_w = int(round(resize_w / 32) * 32)
try:
if int(resize_w) <= 0 or int(resize_h) <= 0:
return None, (None, None)
img = cv2.resize(img, (int(resize_w), int(resize_h)))
except:
print(img.shape, resize_w, resize_h)
sys.exit(0)
ratio_h = resize_h / float(h)
ratio_w = resize_w / float(w)
# return img, np.array([h, w])
return img, [ratio_h, ratio_w]
def resize_image_type2(self, img):
h, w, _ = img.shape
resize_w = w
resize_h = h
# Fix the longer side
if resize_h > resize_w:
ratio = float(self.resize_long) / resize_h
else:
ratio = float(self.resize_long) / resize_w
resize_h = int(resize_h * ratio)
resize_w = int(resize_w * ratio)
max_stride = 128
resize_h = (resize_h + max_stride - 1) // max_stride * max_stride
resize_w = (resize_w + max_stride - 1) // max_stride * max_stride
img = cv2.resize(img, (int(resize_w), int(resize_h)))
ratio_h = resize_h / float(h)
ratio_w = resize_w / float(w)
return img, [ratio_h, ratio_w]
+140
View File
@@ -0,0 +1,140 @@
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
import random
import six
class RawRandAugment(object):
def __init__(self,
num_layers=2,
magnitude=5,
fillcolor=(128, 128, 128),
**kwargs):
self.num_layers = num_layers
self.magnitude = magnitude
self.max_level = 10
abso_level = self.magnitude / self.max_level
self.level_map = {
"shearX": 0.3 * abso_level,
"shearY": 0.3 * abso_level,
"translateX": 150.0 / 331 * abso_level,
"translateY": 150.0 / 331 * abso_level,
"rotate": 30 * abso_level,
"color": 0.9 * abso_level,
"posterize": int(4.0 * abso_level),
"solarize": 256.0 * abso_level,
"contrast": 0.9 * abso_level,
"sharpness": 0.9 * abso_level,
"brightness": 0.9 * abso_level,
"autocontrast": 0,
"equalize": 0,
"invert": 0
}
# from https://stackoverflow.com/questions/5252170/
# specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand
def rotate_with_fill(img, magnitude):
rot = img.convert("RGBA").rotate(magnitude)
return Image.composite(rot,
Image.new("RGBA", rot.size, (128, ) * 4),
rot).convert(img.mode)
rnd_ch_op = random.choice
self.func = {
"shearX": lambda img, magnitude: img.transform(
img.size,
Image.AFFINE,
(1, magnitude * rnd_ch_op([-1, 1]), 0, 0, 1, 0),
Image.BICUBIC,
fillcolor=fillcolor),
"shearY": lambda img, magnitude: img.transform(
img.size,
Image.AFFINE,
(1, 0, 0, magnitude * rnd_ch_op([-1, 1]), 1, 0),
Image.BICUBIC,
fillcolor=fillcolor),
"translateX": lambda img, magnitude: img.transform(
img.size,
Image.AFFINE,
(1, 0, magnitude * img.size[0] * rnd_ch_op([-1, 1]), 0, 1, 0),
fillcolor=fillcolor),
"translateY": lambda img, magnitude: img.transform(
img.size,
Image.AFFINE,
(1, 0, 0, 0, 1, magnitude * img.size[1] * rnd_ch_op([-1, 1])),
fillcolor=fillcolor),
"rotate": lambda img, magnitude: rotate_with_fill(img, magnitude),
"color": lambda img, magnitude: ImageEnhance.Color(img).enhance(
1 + magnitude * rnd_ch_op([-1, 1])),
"posterize": lambda img, magnitude:
ImageOps.posterize(img, magnitude),
"solarize": lambda img, magnitude:
ImageOps.solarize(img, magnitude),
"contrast": lambda img, magnitude:
ImageEnhance.Contrast(img).enhance(
1 + magnitude * rnd_ch_op([-1, 1])),
"sharpness": lambda img, magnitude:
ImageEnhance.Sharpness(img).enhance(
1 + magnitude * rnd_ch_op([-1, 1])),
"brightness": lambda img, magnitude:
ImageEnhance.Brightness(img).enhance(
1 + magnitude * rnd_ch_op([-1, 1])),
"autocontrast": lambda img, magnitude:
ImageOps.autocontrast(img),
"equalize": lambda img, magnitude: ImageOps.equalize(img),
"invert": lambda img, magnitude: ImageOps.invert(img)
}
def __call__(self, img):
avaiable_op_names = list(self.level_map.keys())
for layer_num in range(self.num_layers):
op_name = np.random.choice(avaiable_op_names)
img = self.func[op_name](img, self.level_map[op_name])
return img
class RandAugment(RawRandAugment):
""" RandAugment wrapper to auto fit different img types """
def __init__(self, *args, **kwargs):
if six.PY2:
super(RandAugment, self).__init__(*args, **kwargs)
else:
super().__init__(*args, **kwargs)
def __call__(self, data):
img = data['image']
if not isinstance(img, Image.Image):
img = np.ascontiguousarray(img)
img = Image.fromarray(img)
if six.PY2:
img = super(RandAugment, self).__call__(img)
else:
img = super().__call__(img)
if isinstance(img, Image.Image):
img = np.asarray(img)
data['image'] = img
return data
@@ -0,0 +1,210 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import cv2
import random
def is_poly_in_rect(poly, x, y, w, h):
poly = np.array(poly)
if poly[:, 0].min() < x or poly[:, 0].max() > x + w:
return False
if poly[:, 1].min() < y or poly[:, 1].max() > y + h:
return False
return True
def is_poly_outside_rect(poly, x, y, w, h):
poly = np.array(poly)
if poly[:, 0].max() < x or poly[:, 0].min() > x + w:
return True
if poly[:, 1].max() < y or poly[:, 1].min() > y + h:
return True
return False
def split_regions(axis):
regions = []
min_axis = 0
for i in range(1, axis.shape[0]):
if axis[i] != axis[i - 1] + 1:
region = axis[min_axis:i]
min_axis = i
regions.append(region)
return regions
def random_select(axis, max_size):
xx = np.random.choice(axis, size=2)
xmin = np.min(xx)
xmax = np.max(xx)
xmin = np.clip(xmin, 0, max_size - 1)
xmax = np.clip(xmax, 0, max_size - 1)
return xmin, xmax
def region_wise_random_select(regions, max_size):
selected_index = list(np.random.choice(len(regions), 2))
selected_values = []
for index in selected_index:
axis = regions[index]
xx = int(np.random.choice(axis, size=1))
selected_values.append(xx)
xmin = min(selected_values)
xmax = max(selected_values)
return xmin, xmax
def crop_area(im, text_polys, min_crop_side_ratio, max_tries):
h, w, _ = im.shape
h_array = np.zeros(h, dtype=np.int32)
w_array = np.zeros(w, dtype=np.int32)
for points in text_polys:
points = np.round(points, decimals=0).astype(np.int32)
minx = np.min(points[:, 0])
maxx = np.max(points[:, 0])
w_array[minx:maxx] = 1
miny = np.min(points[:, 1])
maxy = np.max(points[:, 1])
h_array[miny:maxy] = 1
# ensure the cropped area not across a text
h_axis = np.where(h_array == 0)[0]
w_axis = np.where(w_array == 0)[0]
if len(h_axis) == 0 or len(w_axis) == 0:
return 0, 0, w, h
h_regions = split_regions(h_axis)
w_regions = split_regions(w_axis)
for i in range(max_tries):
if len(w_regions) > 1:
xmin, xmax = region_wise_random_select(w_regions, w)
else:
xmin, xmax = random_select(w_axis, w)
if len(h_regions) > 1:
ymin, ymax = region_wise_random_select(h_regions, h)
else:
ymin, ymax = random_select(h_axis, h)
if xmax - xmin < min_crop_side_ratio * w or ymax - ymin < min_crop_side_ratio * h:
# area too small
continue
num_poly_in_rect = 0
for poly in text_polys:
if not is_poly_outside_rect(poly, xmin, ymin, xmax - xmin,
ymax - ymin):
num_poly_in_rect += 1
break
if num_poly_in_rect > 0:
return xmin, ymin, xmax - xmin, ymax - ymin
return 0, 0, w, h
class EastRandomCropData(object):
def __init__(self,
size=(640, 640),
max_tries=10,
min_crop_side_ratio=0.1,
keep_ratio=True,
**kwargs):
self.size = size
self.max_tries = max_tries
self.min_crop_side_ratio = min_crop_side_ratio
self.keep_ratio = keep_ratio
def __call__(self, data):
img = data['image']
text_polys = data['polys']
ignore_tags = data['ignore_tags']
texts = data['texts']
all_care_polys = [
text_polys[i] for i, tag in enumerate(ignore_tags) if not tag
]
# 计算crop区域
crop_x, crop_y, crop_w, crop_h = crop_area(
img, all_care_polys, self.min_crop_side_ratio, self.max_tries)
# crop 图片 保持比例填充
scale_w = self.size[0] / crop_w
scale_h = self.size[1] / crop_h
scale = min(scale_w, scale_h)
h = int(crop_h * scale)
w = int(crop_w * scale)
if self.keep_ratio:
padimg = np.zeros((self.size[1], self.size[0], img.shape[2]),
img.dtype)
padimg[:h, :w] = cv2.resize(
img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w], (w, h))
img = padimg
else:
img = cv2.resize(
img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w],
tuple(self.size))
# crop 文本框
text_polys_crop = []
ignore_tags_crop = []
texts_crop = []
for poly, text, tag in zip(text_polys, texts, ignore_tags):
poly = ((poly - (crop_x, crop_y)) * scale).tolist()
if not is_poly_outside_rect(poly, 0, 0, w, h):
text_polys_crop.append(poly)
ignore_tags_crop.append(tag)
texts_crop.append(text)
data['image'] = img
data['polys'] = np.array(text_polys_crop)
data['ignore_tags'] = ignore_tags_crop
data['texts'] = texts_crop
return data
class PSERandomCrop(object):
def __init__(self, size, **kwargs):
self.size = size
def __call__(self, data):
imgs = data['imgs']
h, w = imgs[0].shape[0:2]
th, tw = self.size
if w == tw and h == th:
return imgs
# label中存在文本实例,并且按照概率进行裁剪,使用threshold_label_map控制
if np.max(imgs[2]) > 0 and random.random() > 3 / 8:
# 文本实例的左上角点
tl = np.min(np.where(imgs[2] > 0), axis=1) - self.size
tl[tl < 0] = 0
# 文本实例的右下角点
br = np.max(np.where(imgs[2] > 0), axis=1) - self.size
br[br < 0] = 0
# 保证选到右下角点时,有足够的距离进行crop
br[0] = min(br[0], h - th)
br[1] = min(br[1], w - tw)
for _ in range(50000):
i = random.randint(tl[0], br[0])
j = random.randint(tl[1], br[1])
# 保证shrink_label_map有文本
if imgs[1][i:i + th, j:j + tw].sum() <= 0:
continue
else:
break
else:
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
# return i, j, th, tw
for idx in range(len(imgs)):
if len(imgs[idx].shape) == 3:
imgs[idx] = imgs[idx][i:i + th, j:j + tw, :]
else:
imgs[idx] = imgs[idx][i:i + th, j:j + tw]
data['imgs'] = imgs
return data
+435
View File
@@ -0,0 +1,435 @@
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import cv2
import numpy as np
import random
from .text_image_aug import tia_perspective, tia_stretch, tia_distort
class RecAug(object):
def __init__(self, use_tia=True, aug_prob=0.4, **kwargs):
self.use_tia = use_tia
self.aug_prob = aug_prob
def __call__(self, data):
img = data['image']
img = warp(img, 10, self.use_tia, self.aug_prob)
data['image'] = img
return data
class ClsResizeImg(object):
def __init__(self, image_shape, **kwargs):
self.image_shape = image_shape
def __call__(self, data):
img = data['image']
norm_img = resize_norm_img(img, self.image_shape)
data['image'] = norm_img
return data
class RecResizeImg(object):
def __init__(self,
image_shape,
infer_mode=False,
character_type='ch',
**kwargs):
self.image_shape = image_shape
self.infer_mode = infer_mode
self.character_type = character_type
def __call__(self, data):
img = data['image']
if self.infer_mode and self.character_type == "ch":
norm_img = resize_norm_img_chinese(img, self.image_shape)
else:
norm_img = resize_norm_img(img, self.image_shape)
data['image'] = norm_img
return data
class SRNRecResizeImg(object):
def __init__(self, image_shape, num_heads, max_text_length, **kwargs):
self.image_shape = image_shape
self.num_heads = num_heads
self.max_text_length = max_text_length
def __call__(self, data):
img = data['image']
norm_img = resize_norm_img_srn(img, self.image_shape)
data['image'] = norm_img
[encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
srn_other_inputs(self.image_shape, self.num_heads, self.max_text_length)
data['encoder_word_pos'] = encoder_word_pos
data['gsrm_word_pos'] = gsrm_word_pos
data['gsrm_slf_attn_bias1'] = gsrm_slf_attn_bias1
data['gsrm_slf_attn_bias2'] = gsrm_slf_attn_bias2
return data
def resize_norm_img(img, image_shape):
imgC, imgH, imgW = image_shape
h = img.shape[0]
w = img.shape[1]
ratio = w / float(h)
if math.ceil(imgH * ratio) > imgW:
resized_w = imgW
else:
resized_w = int(math.ceil(imgH * ratio))
resized_image = cv2.resize(img, (resized_w, imgH))
resized_image = resized_image.astype('float32')
if image_shape[0] == 1:
resized_image = resized_image / 255
resized_image = resized_image[np.newaxis, :]
else:
resized_image = resized_image.transpose((2, 0, 1)) / 255
resized_image -= 0.5
resized_image /= 0.5
padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
padding_im[:, :, 0:resized_w] = resized_image
return padding_im
def resize_norm_img_chinese(img, image_shape):
imgC, imgH, imgW = image_shape
# todo: change to 0 and modified image shape
max_wh_ratio = imgW * 1.0 / imgH
h, w = img.shape[0], img.shape[1]
ratio = w * 1.0 / h
max_wh_ratio = max(max_wh_ratio, ratio)
imgW = int(32 * max_wh_ratio)
if math.ceil(imgH * ratio) > imgW:
resized_w = imgW
else:
resized_w = int(math.ceil(imgH * ratio))
resized_image = cv2.resize(img, (resized_w, imgH))
resized_image = resized_image.astype('float32')
if image_shape[0] == 1:
resized_image = resized_image / 255
resized_image = resized_image[np.newaxis, :]
else:
resized_image = resized_image.transpose((2, 0, 1)) / 255
resized_image -= 0.5
resized_image /= 0.5
padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
padding_im[:, :, 0:resized_w] = resized_image
return padding_im
def resize_norm_img_srn(img, image_shape):
imgC, imgH, imgW = image_shape
img_black = np.zeros((imgH, imgW))
im_hei = img.shape[0]
im_wid = img.shape[1]
if im_wid <= im_hei * 1:
img_new = cv2.resize(img, (imgH * 1, imgH))
elif im_wid <= im_hei * 2:
img_new = cv2.resize(img, (imgH * 2, imgH))
elif im_wid <= im_hei * 3:
img_new = cv2.resize(img, (imgH * 3, imgH))
else:
img_new = cv2.resize(img, (imgW, imgH))
img_np = np.asarray(img_new)
img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
img_black[:, 0:img_np.shape[1]] = img_np
img_black = img_black[:, :, np.newaxis]
row, col, c = img_black.shape
c = 1
return np.reshape(img_black, (c, row, col)).astype(np.float32)
def srn_other_inputs(image_shape, num_heads, max_text_length):
imgC, imgH, imgW = image_shape
feature_dim = int((imgH / 8) * (imgW / 8))
encoder_word_pos = np.array(range(0, feature_dim)).reshape(
(feature_dim, 1)).astype('int64')
gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
(max_text_length, 1)).astype('int64')
gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
[1, max_text_length, max_text_length])
gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1,
[num_heads, 1, 1]) * [-1e9]
gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
[1, max_text_length, max_text_length])
gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2,
[num_heads, 1, 1]) * [-1e9]
return [
encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
gsrm_slf_attn_bias2
]
def flag():
"""
flag
"""
return 1 if random.random() > 0.5000001 else -1
def cvtColor(img):
"""
cvtColor
"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
delta = 0.001 * random.random() * flag()
hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta)
new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return new_img
def blur(img):
"""
blur
"""
h, w, _ = img.shape
if h > 10 and w > 10:
return cv2.GaussianBlur(img, (5, 5), 1)
else:
return img
def jitter(img):
"""
jitter
"""
w, h, _ = img.shape
if h > 10 and w > 10:
thres = min(w, h)
s = int(random.random() * thres * 0.01)
src_img = img.copy()
for i in range(s):
img[i:, i:, :] = src_img[:w - i, :h - i, :]
return img
else:
return img
def add_gasuss_noise(image, mean=0, var=0.1):
"""
Gasuss noise
"""
noise = np.random.normal(mean, var**0.5, image.shape)
out = image + 0.5 * noise
out = np.clip(out, 0, 255)
out = np.uint8(out)
return out
def get_crop(image):
"""
random crop
"""
h, w, _ = image.shape
top_min = 1
top_max = 8
top_crop = int(random.randint(top_min, top_max))
top_crop = min(top_crop, h - 1)
crop_img = image.copy()
ratio = random.randint(0, 1)
if ratio:
crop_img = crop_img[top_crop:h, :, :]
else:
crop_img = crop_img[0:h - top_crop, :, :]
return crop_img
class Config:
"""
Config
"""
def __init__(self, use_tia):
self.anglex = random.random() * 30
self.angley = random.random() * 15
self.anglez = random.random() * 10
self.fov = 42
self.r = 0
self.shearx = random.random() * 0.3
self.sheary = random.random() * 0.05
self.borderMode = cv2.BORDER_REPLICATE
self.use_tia = use_tia
def make(self, w, h, ang):
"""
make
"""
self.anglex = random.random() * 5 * flag()
self.angley = random.random() * 5 * flag()
self.anglez = -1 * random.random() * int(ang) * flag()
self.fov = 42
self.r = 0
self.shearx = 0
self.sheary = 0
self.borderMode = cv2.BORDER_REPLICATE
self.w = w
self.h = h
self.perspective = self.use_tia
self.stretch = self.use_tia
self.distort = self.use_tia
self.crop = True
self.affine = False
self.reverse = True
self.noise = True
self.jitter = True
self.blur = True
self.color = True
def rad(x):
"""
rad
"""
return x * np.pi / 180
def get_warpR(config):
"""
get_warpR
"""
anglex, angley, anglez, fov, w, h, r = \
config.anglex, config.angley, config.anglez, config.fov, config.w, config.h, config.r
if w > 69 and w < 112:
anglex = anglex * 1.5
z = np.sqrt(w**2 + h**2) / 2 / np.tan(rad(fov / 2))
# Homogeneous coordinate transformation matrix
rx = np.array([[1, 0, 0, 0],
[0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [
0,
-np.sin(rad(anglex)),
np.cos(rad(anglex)),
0,
], [0, 0, 0, 1]], np.float32)
ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0],
[0, 1, 0, 0], [
-np.sin(rad(angley)),
0,
np.cos(rad(angley)),
0,
], [0, 0, 0, 1]], np.float32)
rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0],
[-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0],
[0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
r = rx.dot(ry).dot(rz)
# generate 4 points
pcenter = np.array([h / 2, w / 2, 0, 0], np.float32)
p1 = np.array([0, 0, 0, 0], np.float32) - pcenter
p2 = np.array([w, 0, 0, 0], np.float32) - pcenter
p3 = np.array([0, h, 0, 0], np.float32) - pcenter
p4 = np.array([w, h, 0, 0], np.float32) - pcenter
dst1 = r.dot(p1)
dst2 = r.dot(p2)
dst3 = r.dot(p3)
dst4 = r.dot(p4)
list_dst = np.array([dst1, dst2, dst3, dst4])
org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)
dst = np.zeros((4, 2), np.float32)
# Project onto the image plane
dst[:, 0] = list_dst[:, 0] * z / (z - list_dst[:, 2]) + pcenter[0]
dst[:, 1] = list_dst[:, 1] * z / (z - list_dst[:, 2]) + pcenter[1]
warpR = cv2.getPerspectiveTransform(org, dst)
dst1, dst2, dst3, dst4 = dst
r1 = int(min(dst1[1], dst2[1]))
r2 = int(max(dst3[1], dst4[1]))
c1 = int(min(dst1[0], dst3[0]))
c2 = int(max(dst2[0], dst4[0]))
try:
ratio = min(1.0 * h / (r2 - r1), 1.0 * w / (c2 - c1))
dx = -c1
dy = -r1
T1 = np.float32([[1., 0, dx], [0, 1., dy], [0, 0, 1.0 / ratio]])
ret = T1.dot(warpR)
except:
ratio = 1.0
T1 = np.float32([[1., 0, 0], [0, 1., 0], [0, 0, 1.]])
ret = T1
return ret, (-r1, -c1), ratio, dst
def get_warpAffine(config):
"""
get_warpAffine
"""
anglez = config.anglez
rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0],
[-np.sin(rad(anglez)), np.cos(rad(anglez)), 0]], np.float32)
return rz
def warp(img, ang, use_tia=True, prob=0.4):
"""
warp
"""
h, w, _ = img.shape
config = Config(use_tia=use_tia)
config.make(w, h, ang)
new_img = img
if config.distort:
img_height, img_width = img.shape[0:2]
if random.random() <= prob and img_height >= 20 and img_width >= 20:
new_img = tia_distort(new_img, random.randint(3, 6))
if config.stretch:
img_height, img_width = img.shape[0:2]
if random.random() <= prob and img_height >= 20 and img_width >= 20:
new_img = tia_stretch(new_img, random.randint(3, 6))
if config.perspective:
if random.random() <= prob:
new_img = tia_perspective(new_img)
if config.crop:
img_height, img_width = img.shape[0:2]
if random.random() <= prob and img_height >= 20 and img_width >= 20:
new_img = get_crop(new_img)
if config.blur:
if random.random() <= prob:
new_img = blur(new_img)
if config.color:
if random.random() <= prob:
new_img = cvtColor(new_img)
if config.jitter:
new_img = jitter(new_img)
if config.noise:
if random.random() <= prob:
new_img = add_gasuss_noise(new_img)
if config.reverse:
if random.random() <= prob:
new_img = 255 - new_img
return new_img
+115
View File
@@ -0,0 +1,115 @@
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import os
from paddle.io import Dataset
import lmdb
import cv2
from .imaug import transform, create_operators
class LMDBDataSet(Dataset):
def __init__(self, config, mode, logger, seed=None):
super(LMDBDataSet, self).__init__()
global_config = config['Global']
dataset_config = config[mode]['dataset']
loader_config = config[mode]['loader']
batch_size = loader_config['batch_size_per_card']
data_dir = dataset_config['data_dir']
self.do_shuffle = loader_config['shuffle']
self.lmdb_sets = self.load_hierarchical_lmdb_dataset(data_dir)
logger.info("Initialize indexs of datasets:%s" % data_dir)
self.data_idx_order_list = self.dataset_traversal()
if self.do_shuffle:
np.random.shuffle(self.data_idx_order_list)
self.ops = create_operators(dataset_config['transforms'], global_config)
def load_hierarchical_lmdb_dataset(self, data_dir):
lmdb_sets = {}
dataset_idx = 0
for dirpath, dirnames, filenames in os.walk(data_dir + '/'):
if not dirnames:
env = lmdb.open(
dirpath,
max_readers=32,
readonly=True,
lock=False,
readahead=False,
meminit=False)
txn = env.begin(write=False)
num_samples = int(txn.get('num-samples'.encode()))
lmdb_sets[dataset_idx] = {"dirpath":dirpath, "env":env, \
"txn":txn, "num_samples":num_samples}
dataset_idx += 1
return lmdb_sets
def dataset_traversal(self):
lmdb_num = len(self.lmdb_sets)
total_sample_num = 0
for lno in range(lmdb_num):
total_sample_num += self.lmdb_sets[lno]['num_samples']
data_idx_order_list = np.zeros((total_sample_num, 2))
beg_idx = 0
for lno in range(lmdb_num):
tmp_sample_num = self.lmdb_sets[lno]['num_samples']
end_idx = beg_idx + tmp_sample_num
data_idx_order_list[beg_idx:end_idx, 0] = lno
data_idx_order_list[beg_idx:end_idx, 1] \
= list(range(tmp_sample_num))
data_idx_order_list[beg_idx:end_idx, 1] += 1
beg_idx = beg_idx + tmp_sample_num
return data_idx_order_list
def get_img_data(self, value):
"""get_img_data"""
if not value:
return None
imgdata = np.frombuffer(value, dtype='uint8')
if imgdata is None:
return None
imgori = cv2.imdecode(imgdata, 1)
if imgori is None:
return None
return imgori
def get_lmdb_sample_info(self, txn, index):
label_key = 'label-%09d'.encode() % index
label = txn.get(label_key)
if label is None:
return None
label = label.decode('utf-8')
img_key = 'image-%09d'.encode() % index
imgbuf = txn.get(img_key)
return imgbuf, label
def __getitem__(self, idx):
lmdb_idx, file_idx = self.data_idx_order_list[idx]
lmdb_idx = int(lmdb_idx)
file_idx = int(file_idx)
sample_info = self.get_lmdb_sample_info(self.lmdb_sets[lmdb_idx]['txn'],
file_idx)
if sample_info is None:
return self.__getitem__(np.random.randint(self.__len__()))
img, label = sample_info
data = {'image': img, 'label': label}
outs = transform(data, self.ops)
if outs is None:
return self.__getitem__(np.random.randint(self.__len__()))
return outs
def __len__(self):
return self.data_idx_order_list.shape[0]
+2 -2
View File
@@ -363,8 +363,8 @@ def text_visual(texts,
def base64_to_cv2(b64str):
import base64
data = base64.b64decode(b64str.encode('utf8'))
import test
data = test.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
+2 -2
View File
@@ -29,11 +29,11 @@ from tools.infer.utility import draw_ocr, draw_boxes
import requests
import json
import base64
import test
def cv2_to_base64(image):
return base64.b64encode(image).decode('utf8')
return test.b64encode(image).decode('utf8')
def draw_server_result(image_file, res):
+47 -3
View File
@@ -9,6 +9,9 @@ import os
from pathlib import Path
from enum import Enum
from fsplit.filesplit import Filesplit
from paddle import fluid
fluid.install_check.run_check()
# --------------------- 请你不要改 start-----------------------------
# 项目的base目录
@@ -17,8 +20,10 @@ BASE_DIR = str(Path(os.path.abspath(__file__)).parent)
# 模型文件目录
# 文本检测模型
DET_MODEL_PATH = os.path.join(BASE_DIR, 'backend', 'models', 'ch_det')
DET_MODEL_FAST_PATH = os.path.join(BASE_DIR, 'backend', 'models', 'ch_det_fast')
# 文本识别模型
REC_MODEL_PATH = os.path.join(BASE_DIR, 'backend', 'models', 'ch_rec')
REC_MODEL_FAST_PATH = os.path.join(BASE_DIR, 'backend', 'models', 'ch_rec_fast')
# 查看该路径下是否有文本模型识别完整文件,没有的话合并小文件生成完整文件
if 'inference.pdiparams' not in (os.listdir(REC_MODEL_PATH)):
@@ -39,6 +44,15 @@ class SubtitleArea(Enum):
UNKNOWN = 2
# 明确知道字幕区域出现的位置
CUSTOM = 3
class BackgroundColor(Enum):
# 字幕背景
WHITE = 0
DARK = 1
UNKNOWN = 2
# --------------------- 请你不要改 end-----------------------------
@@ -46,15 +60,39 @@ class SubtitleArea(Enum):
# 是否使用GPU
# 使用GPU可以提速20倍+,你要是有N卡你就改成 True
USE_GPU = False
# 如果paddlepaddle编译了gpu的版本
if fluid.is_compiled_with_cuda():
# 查看是否有可用的gpu
if len(fluid.cuda_places()) > 0:
# 如果有GPU则使用GPU
USE_GPU = True
print('使用GPU进行加速')
# 使用快速字幕检测算法时,背景颜色
BG_MOD = BackgroundColor.DARK
# 黑色背景被减矩阵阈值
BG_VALUE_DARK = 200
# 其他背景颜色被减矩阵阈值
BG_VALUE_OTHER = 63
# ROI比例
ROI_RATE = 0.4
# 默认字幕出现区域为下方
SUBTITLE_AREA = SubtitleArea.LOWER_PART
SUBTITLE_AREA = SubtitleArea.UNKNOWN
# 余弦相似度阈值
# 数值越小生成的视频帧越少,相对提取速度更快但生成的字幕越不精准
# 1表示最精准,每一帧视频帧都进行字幕检测与提取,生成的字幕最精准
# 0.925表示,当视频帧1与视频帧2相似度高达92.5%时,视频帧2将直接pass,不字检测与提取视频帧2的字幕
COSINE_SIMILARITY_THRESHOLD = 0.95 if SUBTITLE_AREA == SubtitleArea.UNKNOWN else 0.91
COSINE_SIMILARITY_THRESHOLD = 0.95 if SUBTITLE_AREA == SubtitleArea.UNKNOWN else 0.9
# 当前帧与之后的多少帧比较
FRAME_COMPARE_TIMES = 10
# 每一秒抓取多少帧进行OCR识别
EXTRACT_FREQUENCY = 3
# 每几帧抽取一帧进行OCR识别
EXTRACT_INTERVAL = 8
# 欧式距离相似值
EUCLIDEAN_SIMILARITY_THRESHOLD = 0.9
@@ -71,5 +109,11 @@ WATERMARK_AREA_NUM = 5
# 文本相似度阈值
# 用于去重时判断两行字幕是不是统一行
TEXT_SIMILARITY_THRESHOLD = 0.95
# 采用动态算法实现相似度阈值判断: 对于短文本要求较低的阈值,对于长文本要求较高的阈值
THRESHOLD_TEXT_SIMILARITY = 0.8
# 字幕提取中置信度低于0.8的不要
DROP_SCORE = 0.8
# --------------------- 请根据自己的实际情况改 end-----------------------------
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 MiB

+414
View File
@@ -0,0 +1,414 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "WAJ7lA2wuvR8"
},
"source": [
"# 运行教程\n",
"\n",
"1. 点击“修改” -> \"笔记本设置\" -> \"硬件加速器GPU\" -> 保存\n",
"<img src=\"https://z3.ax1x.com/2021/03/30/ciQWWV.png\">\n",
"\n",
"2. 点左侧文件夹图标,上传视频文件,复制上传的视频路径\n",
"\n",
"<img src=\"https://z3.ax1x.com/2021/03/30/cilvhq.png\">\n",
"\n",
"3. 运行代码, 输入粘贴的视频路径\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_jPi_FBwyZyr"
},
"source": [
"查看是否有GPU"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eHPHc_Bheo-j",
"outputId": "cdd6ec77-0c14-4530-e184-9da8d6f230e0"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tue Mar 30 04:53:52 2021 \n",
"+-----------------------------------------------------------------------------+\n",
"| NVIDIA-SMI 460.56 Driver Version: 460.32.03 CUDA Version: 11.2 |\n",
"|-------------------------------+----------------------+----------------------+\n",
"| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
"| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n",
"| | | MIG M. |\n",
"|===============================+======================+======================|\n",
"| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 |\n",
"| N/A 65C P8 11W / 70W | 0MiB / 15109MiB | 0% Default |\n",
"| | | N/A |\n",
"+-------------------------------+----------------------+----------------------+\n",
" \n",
"+-----------------------------------------------------------------------------+\n",
"| Processes: |\n",
"| GPU GI CI PID Type Process name GPU Memory |\n",
"| ID ID Usage |\n",
"|=============================================================================|\n",
"| No running processes found |\n",
"+-----------------------------------------------------------------------------+\n"
]
}
],
"source": [
"!nvidia-smi"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_85O6zgPyhto"
},
"source": [
"# 安装依赖"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ICeq0T1FeqjT",
"outputId": "8bb896d4-4826-4585-d69e-670a110d234d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cloning into 'video-subtitle-extractor'...\n",
"remote: Enumerating objects: 36, done.\u001b[K\n",
"remote: Counting objects: 100% (36/36), done.\u001b[K\n",
"remote: Compressing objects: 100% (29/29), done.\u001b[K\n",
"remote: Total 383 (delta 18), reused 18 (delta 7), pack-reused 347\u001b[K\n",
"Receiving objects: 100% (383/383), 151.42 MiB | 39.00 MiB/s, done.\n",
"Resolving deltas: 100% (128/128), done.\n",
"Checking out files: 100% (160/160), done.\n"
]
}
],
"source": [
"!git clone https://github.com/YaoFANGUK/video-subtitle-extractor.git"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cd video-subtitle-extractor"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install -r requirements_gpu.txt"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SGb0i3tPyw9Q"
},
"source": [
"# 运行程序"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "B2MPjMOOgGbD",
"outputId": "40b65892-28ca-4af7-bb89-cd8716265644"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Running Verify Fluid Program ... \n",
"W0330 05:00:56.211509 282 device_context.cc:362] Please NOTE: device: 0, GPU Compute Capability: 7.5, Driver API Version: 11.2, Runtime API Version: 10.2\n",
"W0330 05:00:56.217797 282 device_context.cc:372] device: 0, cuDNN Version: 7.6.\n",
"Your Paddle Fluid works well on SINGLE GPU or CPU.\n",
"Your Paddle Fluid works well on MUTIPLE GPU or CPU.\n",
"Your Paddle Fluid is installed successfully! Let's start deep Learning with Paddle Fluid now\n",
"使用GPU进行加速\n",
"/usr/local/lib/python3.7/dist-packages/yaml/constructor.py:126: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working\n",
" if not isinstance(key, collections.Hashable):\n",
"请输入视频完整路径:/content/testvd.mp4\n",
"帧数:568.0,帧率:30.000033010599704\n",
"Step 1. 开启提取视频关键帧...\n",
"提取视频关键帧完毕...\n",
"Step 2. 开始提取字幕信息,此步骤可能花费较长时间,请耐心等待...\n",
"[2021/03/30 05:01:15] root INFO: dt_boxes num : 4, elapse : 0.14402198791503906\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 4, elapse : 0.06298613548278809\n",
"['30', '编辑部评分是7.2分', 'TSST']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 3, elapse : 0.0818178653717041\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 3, elapse : 0.03780984878540039\n",
"['8', '编辑部评分是7.2分', 'TEST']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 4, elapse : 0.07239007949829102\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 4, elapse : 0.03380751609802246\n",
"['易', '8', '编辑部评分是7.2分', 'T-ST']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 5, elapse : 0.06836462020874023\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 5, elapse : 0.041188955307006836\n",
"['功能', '易用性', '编辑部评分是7.2分', 'TEST']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 6, elapse : 0.06691503524780273\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 6, elapse : 0.05425071716308594\n",
"['易用性', '正临', '编辑部评分是7.2分', 'TSSTI']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 5, elapse : 0.06857109069824219\n",
"[2021/03/30 05:01:16] root INFO: rec_res num : 5, elapse : 0.034926652908325195\n",
"['LE', '易用性', '而观众老爷们嘛']\n",
"[2021/03/30 05:01:16] root INFO: dt_boxes num : 6, elapse : 0.06962084770202637\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 6, elapse : 0.04759716987609863\n",
"['写瓦', '二', '易用性', '而观众老爷们嘛']\n",
"[2021/03/30 05:01:17] root INFO: dt_boxes num : 7, elapse : 0.06960034370422363\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 7, elapse : 0.04424023628234863\n",
"['?', '易用性', '而观众老爷们嘛']\n",
"[2021/03/30 05:01:17] root INFO: dt_boxes num : 9, elapse : 0.06829595565795898\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 9, elapse : 0.05313420295715332\n",
"['易用性', '主题壁纸', '换机', '而观众老爷们嘛', 'T']\n",
"[2021/03/30 05:01:17] root INFO: dt_boxes num : 8, elapse : 0.06818628311157227\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 8, elapse : 0.05216336250305176\n",
"['易用性', '而观众老爷们嘛', 'TEST']\n",
"[2021/03/30 05:01:17] root INFO: dt_boxes num : 10, elapse : 0.06845855712890625\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 10, elapse : 0.06405067443847656\n",
"['功能', '回放', '易用性', '今日步数5084', '影音视听14分钟', '我们收到1569份评分', 'T-ST']\n",
"[2021/03/30 05:01:17] root INFO: dt_boxes num : 6, elapse : 0.06773829460144043\n",
"[2021/03/30 05:01:17] root INFO: rec_res num : 6, elapse : 0.05858922004699707\n",
"['功能', '易用性', '14号', '我们收到1569份评分', 'TSST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 11, elapse : 0.07036185264587402\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 11, elapse : 0.0695803165435791\n",
"['功能', '29', '期五', '易用性', '我们收到1569份评分', 'TEST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 3, elapse : 0.0671992301940918\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 3, elapse : 0.031127452850341797\n",
"['我们收到1569份评分', 'TEST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 9, elapse : 0.0686032772064209\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 9, elapse : 0.05087685585021973\n",
"['大圣净化', '23', '易翔,', '我们收到1569份评分', 'TEST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 6, elapse : 0.06680893898010254\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 6, elapse : 0.061042070388793945\n",
"['功能', '大墨净化', '23', '易用性', '我们收到1569份评分', 'TEST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 9, elapse : 0.07074356079101562\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 9, elapse : 0.049074649810791016\n",
"['功能', '23', '易用性', '我们收到1569份评分', 'TEST']\n",
"[2021/03/30 05:01:18] root INFO: dt_boxes num : 7, elapse : 0.06651568412780762\n",
"[2021/03/30 05:01:18] root INFO: rec_res num : 7, elapse : 0.054694414138793945\n",
"['功能', '王价比', '易用性', '获得平均分83分', 'TEST']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 11, elapse : 0.0700066089630127\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 11, elapse : 0.050124168395996094\n",
"['功能', '29', '日历', '8:', '易用性', '生日', '获得平均分8分', 'TEST']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 11, elapse : 0.07042765617370605\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 11, elapse : 0.05459332466125488\n",
"['功能', '工', '29', '易用性', 'C', '获得平均分83分', 'TEST']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 10, elapse : 0.06987738609313965\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 10, elapse : 0.057497262954711914\n",
"['功能', '易用性', '获得平均分8.3分', 'T-ST']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 23, elapse : 0.07419443130493164\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 23, elapse : 0.08902907371520996\n",
"['功能', '利物浦', '1', '19:00', '回放', 'WE', '星', 'RNG', '00:30', '西汉姆', '利物酒', '照开更多', '易用性', '今日步数5084', '影音视听14分钟', '获得平均分8.3分', 'TEST', '设备']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 23, elapse : 0.07614350318908691\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 23, elapse : 0.08669447898864746\n",
"['功能', '19:00', '回放', 'WE', '1', 'RNG', '00:30', '西汉姆', '前', '利物薄', '前', '展开更多', '易用性', '今日步数5084', '屏幕使用2时38分', '131', 'T', '获得平均分8.3份', 'ST', '备']\n",
"[2021/03/30 05:01:19] root INFO: dt_boxes num : 2, elapse : 0.06589818000793457\n",
"[2021/03/30 05:01:19] root INFO: rec_res num : 2, elapse : 0.014737606048583984\n",
"['易用性', '布朗熊与可妮兔']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 5, elapse : 0.06754112243652344\n",
"[2021/03/30 05:01:20] root INFO: rec_res num : 5, elapse : 0.07237792015075684\n",
"['易用性', '布朗熊与可妮兔', '米11在四个纬度的分数只高不低', 'Brown&Con']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 5, elapse : 0.06590557098388672\n",
"[2021/03/30 05:01:20] root INFO: rec_res num : 5, elapse : 0.08357715606689453\n",
"['易用性', '布朗熊与可妮鱼', '¥11在四个纬度的分数只高不低', 'Brown&ConY']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 4, elapse : 0.06757831573486328\n",
"[2021/03/30 05:01:20] root INFO: rec_res num : 4, elapse : 0.026897192001342773\n",
"['D', '易用性', 'Brown&Cony']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 6, elapse : 0.068145751953125\n",
"[2021/03/30 05:01:20] root INFO: rec_res num : 6, elapse : 0.08809947967529297\n",
"['HDn', '易用性', '布朗熊与可妮兔', '11在四个纬度的分数只高不低', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 5, elapse : 0.06944656372070312\n",
"[2021/03/30 05:01:20] root INFO: rec_res num : 5, elapse : 0.02738165855407715\n",
"['易用性', 'Brown&Cony', '茶']\n",
"[2021/03/30 05:01:20] root INFO: dt_boxes num : 4, elapse : 0.06836795806884766\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 4, elapse : 0.02448129653930664\n",
"['易用性', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 3, elapse : 0.06509160995483398\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 3, elapse : 0.0194094181060791\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 3, elapse : 0.06666183471679688\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 3, elapse : 0.017718076705932617\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 4, elapse : 0.06582808494567871\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 4, elapse : 0.025033950805664062\n",
"['易用性', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 3, elapse : 0.0648648738861084\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 3, elapse : 0.02213597297668457\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 3, elapse : 0.06644940376281738\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 3, elapse : 0.019091129302978516\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 3, elapse : 0.06672954559326172\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 3, elapse : 0.02083420753479004\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:21] root INFO: dt_boxes num : 4, elapse : 0.06565666198730469\n",
"[2021/03/30 05:01:21] root INFO: rec_res num : 4, elapse : 0.02493119239807129\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 5, elapse : 0.06770944595336914\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 5, elapse : 0.028589487075805664\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 3, elapse : 0.06848573684692383\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 3, elapse : 0.021693706512451172\n",
"['易用性', 'Brown&Cony']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 3, elapse : 0.06637048721313477\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 3, elapse : 0.022501468658447266\n",
"['易用性', '漆', 'Brown&Cony']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 3, elapse : 0.06774711608886719\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 3, elapse : 0.021985292434692383\n",
"['易用性', '茶', 'Brown&Cony']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 5, elapse : 0.06895327568054199\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 5, elapse : 0.03924155235290527\n",
"['功能', '价IE', '易用性', '看来在观众眼中', '1']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 5, elapse : 0.06944680213928223\n",
"[2021/03/30 05:01:22] root INFO: rec_res num : 5, elapse : 0.03776049613952637\n",
"['功能', '任价比', '易用性', '看来在观众眼中', 'PST']\n",
"[2021/03/30 05:01:22] root INFO: dt_boxes num : 5, elapse : 0.06571078300476074\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 5, elapse : 0.04117131233215332\n",
"['功能', '价比', '易用性', '看来在观众眼中', 'TEST']\n",
"[2021/03/30 05:01:23] root INFO: dt_boxes num : 5, elapse : 0.06788992881774902\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 5, elapse : 0.0761101245880127\n",
"['功能', '在价比', '易用性', '小米11还是十分值得购买的手机哟', 'TESTI']\n",
"[2021/03/30 05:01:23] root INFO: dt_boxes num : 5, elapse : 0.06792283058166504\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 5, elapse : 0.07545995712280273\n",
"['功能', '任价比', '易用性', '小米11还是十分值得购买的手机哟', 'TEST']\n",
"[2021/03/30 05:01:23] root INFO: dt_boxes num : 6, elapse : 0.06739664077758789\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 6, elapse : 0.0957193374633789\n",
"['功能', '价式', '易用性', '小米11还是十分值得购买的手机哟', 'T三STI']\n",
"[2021/03/30 05:01:23] root INFO: dt_boxes num : 5, elapse : 0.0679783821105957\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 5, elapse : 0.07640886306762695\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟', 'TEST']\n",
"[2021/03/30 05:01:23] root INFO: dt_boxes num : 5, elapse : 0.06631970405578613\n",
"[2021/03/30 05:01:23] root INFO: rec_res num : 5, elapse : 0.07297635078430176\n",
"['功能', '任价比', '易用性', '小米11还是十分值得购买的手机哟', 'TES']\n",
"[2021/03/30 05:01:24] root INFO: dt_boxes num : 5, elapse : 0.06671547889709473\n",
"[2021/03/30 05:01:24] root INFO: rec_res num : 5, elapse : 0.07393217086791992\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟', 'T']\n",
"[2021/03/30 05:01:24] root INFO: dt_boxes num : 5, elapse : 0.06604695320129395\n",
"[2021/03/30 05:01:24] root INFO: rec_res num : 5, elapse : 0.07659339904785156\n",
"['功能', 'DLL', '易用性', '小米11还是十分值得购买的手机哟', 'TPC']\n",
"[2021/03/30 05:01:24] root INFO: dt_boxes num : 6, elapse : 0.06710600852966309\n",
"[2021/03/30 05:01:24] root INFO: rec_res num : 6, elapse : 0.09409260749816895\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟', 'TS']\n",
"[2021/03/30 05:01:24] root INFO: dt_boxes num : 5, elapse : 0.06793045997619629\n",
"[2021/03/30 05:01:24] root INFO: rec_res num : 5, elapse : 0.07574295997619629\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟', 'T-C']\n",
"[2021/03/30 05:01:24] root INFO: dt_boxes num : 5, elapse : 0.06672501564025879\n",
"[2021/03/30 05:01:24] root INFO: rec_res num : 5, elapse : 0.07797956466674805\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟', 'I']\n",
"[2021/03/30 05:01:25] root INFO: dt_boxes num : 5, elapse : 0.06730794906616211\n",
"[2021/03/30 05:01:25] root INFO: rec_res num : 5, elapse : 0.07574915885925293\n",
"['功能', '王价L', '易用性', '小米11还是十分值得购买的手机哟', 'TEST']\n",
"[2021/03/30 05:01:25] root INFO: dt_boxes num : 6, elapse : 0.06949663162231445\n",
"[2021/03/30 05:01:25] root INFO: rec_res num : 6, elapse : 0.08900570869445801\n",
"['功能', '易用性', '小米11还是十分值得购买的手机哟']\n",
"[2021/03/30 05:01:25] root INFO: dt_boxes num : 5, elapse : 0.06655359268188477\n",
"[2021/03/30 05:01:25] root INFO: rec_res num : 5, elapse : 0.07690143585205078\n",
"['功能', '价L', '易用性', 'T', '小米11还是十分值得购买的手机哟']\n",
"完成字幕提取,生成原始字幕文件...\n",
"Step 3. 开始检测并过滤水印区域内容\n",
"视频是否存在水印区域,存在的话输入y,不存在的话输入n: y\n",
"请查看图片, 确定水印区域: /content/video-subtitle-extractor/output/watermark_area.jpg\n",
"是否去除区域A((349, 432, 161, 181), 56)中的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: y\n",
"已经删除该区域字幕...\n",
"是否去除区域B((1058, 1178, 262, 281), 32)中的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: y\n",
"已经删除该区域字幕...\n",
"是否去除区域C((171, 224, 0, 12), 28)中的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: y\n",
"已经删除该区域字幕...\n",
"是否去除区域D((353, 468, 327, 328), 27)中的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: y\n",
"已经删除该区域字幕...\n",
"是否去除区域E((419, 870, 266, 291), 26)中的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: n\n",
"水印区域字幕过滤完毕...\n",
"已经成功过滤水印区域内容\n",
"Step 4. 开始检测非字幕区域,并将非字幕区域的内容删除\n",
"请查看图片, 确定字幕区域是否正确: /content/video-subtitle-extractor/output/subtitle_area.jpg\n",
"是否去除红色框区域外(216, 341)的字幕?\n",
"输入 \"y\" 或 \"回车\" 表示去除,输入\"n\"或其他表示不去除: y\n",
"去除完毕\n",
"已将非字幕区域的内容删除\n",
"Step 5. 开始生成字幕文件\n",
"/content/testvd\n",
"字幕文件生成位置:/content/testvd.srt\n",
"字幕文件生成成功\n"
]
}
],
"source": [
"!python main.py"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EGsjK3RRgIlD"
},
"source": [
"<img src=\"\">"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
"name": "video-subtitle-extractor.ipynb",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+204
View File
@@ -0,0 +1,204 @@
# -*- coding: utf-8 -*-
"""
@Author : Fang Yao
@Time : 2021/4/1 6:07 下午
@FileName: gui.py
@desc:
"""
import sys
import PySimpleGUI as sg
import os
import cv2
from PIL import Image
import io
import config
import numpy as np
from main import SubtitleExtractor
from threading import Thread
class SubtitleExtractorGUI:
def __init__(self):
# 字幕提取器布局
self.layout = None
# 字幕提取其窗口
self.window = None
# 视频路径
self.video_path = None
# 视频cap
self.video_cap = None
# 视频的帧率
self.fps = None
# 视频的帧数
self.frame_count = None
# 视频的宽
self.frame_width = None
# 视频的高
self.frame_height = None
# 设置字幕区域高宽
self.xmin = None
self.xmax = None
self.ymin = None
self.ymax = None
def run(self):
# 创建布局
self._create_layout()
# 创建窗口
self.window = sg.Window('硬字幕提取器', self.layout)
while True:
# 循环读取事件
event, values = self.window.read(timeout=10)
# 处理【打开】事件
self._file_event_handler(event, values)
# 处理【滑动】事件
self._slide_event_handler(event, values)
# 处理【运行】事件
self._run_event_handler(event, values)
# 如果关闭软件,退出
if event == sg.WIN_CLOSED:
break
def _create_layout(self):
"""
创建字幕提取器布局
"""
sg.theme('LightBrown12')
self.layout = [
# 显示视频预览
[sg.Image(size=(854, 480), background_color='black', key='-DISPLAY-')],
# 打开按钮 + 快进快退条
[sg.Input(key='-FILE-', visible=False, enable_events=True),
sg.FileBrowse('打开', file_types=(('mp4文件', '*.mp4'), ('flv文件', '*.flv'),
('wmv文件', '*.wmv'), ('avi文件', '*.avi')),
key='-FILE_BTN-'),
sg.Slider(size=(95, 20), range=(1, 1), key='-SLIDER-', orientation='h', enable_events=True,
disable_number_display=True)
],
# 输出区域
[sg.Output(size=(70, 10), font='Courier 10'),
sg.Frame(title='垂直方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-Y-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-Y-SLIDER-H-'),
]], pad=((15, 5), (0, 0))),
sg.Frame(title='水平方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-X-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-X-SLIDER-W-'),
]], pad=((15, 5), (0, 0)))
],
# 运行按钮 + 进度条
[sg.Button(button_text='运行', key='-RUN-', size=(20, 1))],
]
def _file_event_handler(self, event, values):
"""
当点击打开按钮时:
1)打开视频文件,将画布显示视频帧
2)获取视频信息,初始化进度条滑块范围
"""
if event == '-FILE-':
self.video_path = values['-FILE-']
if self.video_path != '':
self.video_cap = cv2.VideoCapture(self.video_path)
if self.video_cap is None:
return
if self.video_cap.isOpened():
ret, frame = self.video_cap.read()
if ret:
print(f'成功打开视频:{self.video_path}')
# 获取视频的帧数
self.frame_count = self.video_cap.get(cv2.CAP_PROP_FRAME_COUNT)
# 获取视频的高度
self.frame_height = self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
# 获取视频的宽度
self.frame_width = self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)
# 获取视频的帧率
self.fps = self.video_cap.get(cv2.CAP_PROP_FPS)
# 调整视频帧大小,是播放器能够显示
resized_frame = cv2.resize(src=frame, dsize=(854, 480))
# 显示视频帧
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
# 更新视频进度条滑块range
self.window['-SLIDER-'].update(range=(1, self.frame_count))
self.window['-SLIDER-'].update(1)
# 更新视频字幕位置滑块range
self.window['-Y-SLIDER-'].update(range=(0, self.frame_height), disabled=False)
self.window['-Y-SLIDER-H-'].update(range=(0, self.frame_height // 2), disabled=False)
self.window['-Y-SLIDER-'].update(self.frame_height - 50)
self.window['-Y-SLIDER-H-'].update(10)
self.window['-X-SLIDER-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-W-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-'].update(0)
self.window['-X-SLIDER-W-'].update(self.frame_width)
def _run_event_handler(self, event, values):
"""
当点击运行按钮时:
1) 禁止修改字幕滑块区域
2) 禁止再次点击【运行】和【打开】按钮
3) 设定字幕区域位置
"""
if event == '-RUN-':
if self.video_cap is None:
print('请先打开视频')
else:
# 1) 禁止修改字幕滑块区域
self.window['-Y-SLIDER-'].update(disabled=True)
self.window['-X-SLIDER-'].update(disabled=True)
self.window['-Y-SLIDER-H-'].update(disabled=True)
self.window['-X-SLIDER-W-'].update(disabled=True)
# 2) 禁止再次点击【运行】和【打开】按钮
self.window['-RUN-'].update(disabled=True)
self.window['-FILE-'].update(disabled=True)
self.window['-FILE_BTN-'].update(disabled=True)
# 3) 设定字幕区域位置
self.xmin = int(values['-X-SLIDER-'])
self.xmax = int(values['-X-SLIDER-'] + values['-X-SLIDER-W-'])
self.ymin = int(values['-Y-SLIDER-'])
self.ymax = int(values['-Y-SLIDER-'] + values['-Y-SLIDER-H-'])
print(f'字幕区域:({self.ymin},{self.ymax},{self.xmin},{self.xmax})')
subtitle_area = (self.ymin, self.ymax, self.xmin, self.xmax)
se = SubtitleExtractor(self.video_path, subtitle_area)
Thread(target=se.run, daemon=True).start()
def _slide_event_handler(self, event, values):
"""
当滑动视频进度条/滑动字幕选择区域滑块时:
1) 判断视频是否存在,如果存在则显示对应的视频帧
2) 绘制rectangle
"""
if event == '-SLIDER-' or event == '-Y-SLIDER-' or event == '-Y-SLIDER-H-' or event == '-X-SLIDER-' or event == '-X-SLIDER-W-':
if self.video_cap is not None and self.video_cap.isOpened():
frame_no = int(values['-SLIDER-'])
self.video_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame = self.video_cap.read()
if ret:
# 画字幕框
y = int(values['-Y-SLIDER-'])
h = int(values['-Y-SLIDER-H-'])
x = int(values['-X-SLIDER-'])
w = int(values['-X-SLIDER-W-'])
draw = cv2.rectangle(img=frame, pt1=(x, y), pt2=(x + w, y + h),
color=(0, 255, 0), thickness=3)
# 调整视频帧大小,是播放器能够显示
resized_frame = cv2.resize(src=draw, dsize=(854, 480))
# 显示视频帧
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
if __name__ == '__main__':
subtitleExtractorGUI = SubtitleExtractorGUI()
subtitleExtractorGUI.run()
+411 -153
View File
@@ -5,33 +5,43 @@
@FileName: main.py
@desc: 主程序入口文件
"""
import config
from config import SubtitleArea
from backend.tools.infer.predict_system import TextSystem
from backend.tools.infer import utility
import cv2
import random
import os
import math
import random
from collections import Counter
import numpy as np
import unicodedata
import cv2
from Levenshtein import ratio
from PIL import Image
from numpy import average, dot, linalg
from Levenshtein import ratio
import numpy as np
import config
from backend.tools.infer import utility
from backend.tools.infer.predict_system import TextSystem
from config import SubtitleArea
# 加载文本检测+识别模型
def load_model():
# 获取参数对象
args = utility.parse_args()
# 设置文本检测模型路径
args.det_model_dir = config.DET_MODEL_PATH
# 设置文本识别模型路径
args.rec_model_dir = config.REC_MODEL_PATH
# 设置字典路径
args.rec_char_dict_path = config.DICT_PATH
# 是否使用GPU加速
args.use_gpu = config.USE_GPU
if config.USE_GPU:
# 设置文本检测模型路径
args.det_model_dir = config.DET_MODEL_PATH
# 设置文本识别模型路径
args.rec_model_dir = config.REC_MODEL_PATH
else:
# 加载快速模型
args.det_model_dir = config.DET_MODEL_FAST_PATH
# 加载快速模型
# args.rec_model_dir = config.REC_MODEL_FAST_PATH
args.rec_model_dir = config.REC_MODEL_PATH
# 设置字典路径
args.rec_char_dict_path = config.DICT_PATH
return TextSystem(args)
@@ -40,7 +50,9 @@ class SubtitleExtractor:
视频字幕提取类
"""
def __init__(self, vd_path):
def __init__(self, vd_path, sub_area=None):
# 字幕区域位置
self.sub_area = sub_area
# 视频路径
self.video_path = vd_path
self.video_cap = cv2.VideoCapture(vd_path)
@@ -72,19 +84,41 @@ class SubtitleExtractor:
"""
运行整个提取视频的步骤
"""
self.extract_frame()
print('【处理中】开启提取视频关键帧...')
self.extract_frame_by_fps()
print('【结束】提取视频关键帧完毕...')
print('【处理中】开始提取字幕信息,此步骤可能花费较长时间,请耐心等待...')
self.extract_subtitles()
self.detect_watermark_area()
self.filter_watermark()
self.detect_subtitle_area()
self.filter_scene_text()
print('【结束】完成字幕提取,生成原始字幕文件...')
if self.sub_area is None:
print('【处理中】开始检测并过滤水印区域内容')
# 询问用户视频是否有水印区域
user_input = input('视频是否存在水印区域,存在的话输入y,不存在的话输入n: ').strip()
if user_input == 'y':
self.filter_watermark()
print('【结束】已经成功过滤水印区域内容')
else:
print('-----------------------------')
if self.sub_area is None:
print('【处理中】开始检测非字幕区域,并将非字幕区域的内容删除')
self.filter_scene_text()
print('【结束】已将非字幕区域的内容删除')
print('【处理中】开始生成字幕文件')
self.generate_subtitle_file()
print('【结束】字幕文件生成成功')
def extract_frame(self):
"""
根据视频的分辨率,将高分辨的视频帧缩放到1280*720p
根据字幕区域位置,将该图像区域截取出来
"""
# 删除缓存
self.__delete_frame_cache()
# 当前视频帧的帧号
frame_no = 0
@@ -96,22 +130,7 @@ class SubtitleExtractor:
# 读取视频帧成功
else:
frame_no += 1
# 对于分辨率大于1920*1080的视频,将其视频帧进行等比缩放至1280*720进行识别
# paddlepaddle会将图像压缩为640*640
if self.frame_width > 1280:
scale_rate = round(float(1280 / self.frame_width), 2)
frame = cv2.resize(frame, None, fx=scale_rate, fy=scale_rate, interpolation=cv2.INTER_AREA)
cropped = int(frame.shape[0] // 2)
# 如果字幕出现的区域在下部分
if self.subtitle_area == SubtitleArea.LOWER_PART:
# 将视频帧切割为下半部分
frame = frame[cropped:]
# 如果字幕出现的区域在上半部分
elif self.subtitle_area == SubtitleArea.UPPER_PART:
# 将视频帧切割为下半部分
frame = frame[:cropped]
frame = self._frame_preprocess(frame)
# 帧名往前补零,后续用于排序与时间戳转换,补足8位
# 一部10h电影,fps120帧最多也才1*60*60*120=432000 6位,所以8位足够
@@ -120,13 +139,17 @@ class SubtitleExtractor:
cv2.imwrite(filename, frame)
# 将当前帧与接下来的帧进行比较,计算余弦相似度
compare_times = 0
while self.video_cap.isOpened():
ret, frame_next = self.video_cap.read()
if ret:
frame_no += 1
frame_next = self._frame_preprocess(frame_next)
cosine_distance = self._compute_image_similarity(Image.fromarray(frame),
Image.fromarray(frame_next))
print(cosine_distance)
compare_times += 1
if compare_times == config.FRAME_COMPARE_TIMES:
break
if cosine_distance > config.COSINE_SIMILARITY_THRESHOLD:
# 如果下一帧与当前帧的相似度大于设定阈值,则略过该帧
continue
@@ -137,7 +160,68 @@ class SubtitleExtractor:
break
self.video_cap.release()
cv2.destroyAllWindows()
def extract_frame_by_fps(self):
"""
根据帧率,定时提取视频帧,容易丢字幕,但速度快
"""
# 删除缓存
self.__delete_frame_cache()
# 当前视频帧的帧号
frame_no = 0
while self.video_cap.isOpened():
ret, frame = self.video_cap.read()
# 如果读取视频帧失败(视频读到最后一帧)
if not ret:
break
# 读取视频帧成功
else:
frame_no += 1
frame = self._frame_preprocess(frame)
# 帧名往前补零,后续用于排序与时间戳转换,补足8位
# 一部10h电影,fps120帧最多也才1*60*60*120=432000 6位,所以8位足够
filename = os.path.join(self.frame_output_dir, str(frame_no).zfill(8) + '.jpg')
# 保存视频帧
cv2.imwrite(filename, frame)
# 跳过剩下的帧
for i in range(int(self.fps // config.EXTRACT_FREQUENCY) - 1):
ret, _ = self.video_cap.read()
if ret:
frame_no += 1
self.video_cap.release()
def extract_subtitle_frame(self):
"""
提取包含字幕的视频帧
"""
# 删除缓存
self.__delete_frame_cache()
# 获取字幕帧列表
subtitle_frame_list = self._analyse_subtitle_frame()
if subtitle_frame_list is None:
print('请指定字幕区域')
return
cap = cv2.VideoCapture(self.video_path)
idx = 0
index = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if idx in subtitle_frame_list and idx != 0:
filename = os.path.join(self.frame_output_dir, str(idx).zfill(8) + '.jpg')
frame = self._frame_preprocess(frame)
cv2.imwrite(filename, frame)
subtitle_frame_list.remove(idx)
index += 1
idx = idx + 1
cap.release()
def extract_subtitles(self):
"""
@@ -147,7 +231,9 @@ class SubtitleExtractor:
text_recogniser = load_model()
# 视频帧列表
frame_list = [i for i in sorted(os.listdir(self.frame_output_dir)) if i.endswith('.jpg')]
# 删除缓存
if os.path.exists(self.raw_subtitle_path):
os.remove(self.raw_subtitle_path)
# 新建文件
f = open(self.raw_subtitle_path, mode='w+', encoding='utf-8')
@@ -159,14 +245,197 @@ class SubtitleExtractor:
# 获取文本坐标
coordinates = self.__get_coordinates(dt_box)
# 将结果写入txt文本中
for content, coordinate in zip(([res[0] for res in rec_res]), coordinates):
f.write(f'{os.path.splitext(frame)[0]}\t'
f'{coordinate}\t'
f'{content}\n')
text_res = [(res[0], res[1]) for res in rec_res]
for content, coordinate in zip(text_res, coordinates):
if self.sub_area is not None:
s_ymin = self.sub_area[0]
s_ymax = self.sub_area[1]
s_xmin = self.sub_area[2]
s_xmax = self.sub_area[3]
xmin = coordinate[0]
xmax = coordinate[1]
ymin = coordinate[2]
ymax = coordinate[3]
if s_xmin <= xmin and xmax <= s_xmax and s_ymin <= ymin and ymax <= s_ymax:
print(content[0], content[1])
if content[1] > config.DROP_SCORE:
f.write(f'{os.path.splitext(frame)[0]}\t'
f'{coordinate}\t'
f'{content[0]}\n')
else:
f.write(f'{os.path.splitext(frame)[0]}\t'
f'{coordinate}\t'
f'{content[0]}\n')
# 关闭文件
f.close()
def detect_watermark_area(self):
def filter_watermark(self):
"""
去除原始字幕文本中的水印区域的文本
"""
# 获取潜在水印区域
watermark_areas = self._detect_watermark_area()
# 从frame目录随机读取一张图片,将所水印区域标记出来,用户看图判断是否是水印区域
frame_path = os.path.join(self.frame_output_dir,
random.choice(
[i for i in sorted(os.listdir(self.frame_output_dir)) if i.endswith('.jpg')]))
sample_frame = cv2.imread(frame_path)
# 给潜在的水印区域编号
area_num = ['E', 'D', 'C', 'B', 'A']
for watermark_area in watermark_areas:
ymin = min(watermark_area[0][2], watermark_area[0][3])
ymax = max(watermark_area[0][3], watermark_area[0][2])
xmin = min(watermark_area[0][0], watermark_area[0][1])
xmax = max(watermark_area[0][1], watermark_area[0][0])
cover = sample_frame[ymin:ymax, xmin:xmax]
cover = cv2.blur(cover, (10, 10))
cv2.rectangle(cover, pt1=(0, cover.shape[0]), pt2=(cover.shape[1], 0), color=(0, 0, 255), thickness=3)
sample_frame[ymin:ymax, xmin:xmax] = cover
position = ((xmin + xmax) // 2, ymax)
cv2.putText(sample_frame, text=area_num.pop(), org=position, fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1, color=(255, 0, 0), thickness=2, lineType=cv2.LINE_AA)
sample_frame_file_path = os.path.join(os.path.dirname(self.frame_output_dir), 'watermark_area.jpg')
cv2.imwrite(sample_frame_file_path, sample_frame)
print(f'请查看图片, 确定水印区域: {sample_frame_file_path}')
area_num = ['E', 'D', 'C', 'B', 'A']
for watermark_area in watermark_areas:
user_input = input(f'是否去除区域{area_num.pop()}{str(watermark_area)}中的字幕?'
f'\n输入 "y" 或 "回车" 表示去除,输入"n"或其他表示不去除: ').strip()
if user_input == 'y' or user_input == '\n':
with open(self.raw_subtitle_path, mode='r+', encoding='utf-8') as f:
content = f.readlines()
f.seek(0)
for i in content:
if i.find(str(watermark_area[0])) == -1:
f.write(i)
f.truncate()
print(f'已经删除该区域字幕...')
print('水印区域字幕过滤完毕...')
# 删除缓存
if os.path.exists(sample_frame_file_path):
os.remove(sample_frame_file_path)
def filter_scene_text(self):
"""
将场景里提取的文字过滤,仅保留字幕区域
"""
# 获取潜在字幕区域
subtitle_area = self._detect_subtitle_area()[0][0]
# 从frame目录随机读取一张图片,将所水印区域标记出来,用户看图判断是否是水印区域
frame_path = os.path.join(self.frame_output_dir,
random.choice(
[i for i in sorted(os.listdir(self.frame_output_dir)) if i.endswith('.jpg')]))
sample_frame = cv2.imread(frame_path)
# 为了防止有双行字幕,根据容忍度,将字幕区域y范围加高
ymin = abs(subtitle_area[0] - config.SUBTITLE_AREA_DEVIATION_PIXEL)
ymax = subtitle_area[1] + config.SUBTITLE_AREA_DEVIATION_PIXEL
# 画出字幕框的区域
cv2.rectangle(sample_frame, pt1=(0, ymin), pt2=(sample_frame.shape[1], ymax), color=(0, 0, 255), thickness=3)
sample_frame_file_path = os.path.join(os.path.dirname(self.frame_output_dir), 'subtitle_area.jpg')
cv2.imwrite(sample_frame_file_path, sample_frame)
print(f'请查看图片, 确定字幕区域是否正确: {sample_frame_file_path}')
user_input = input(f'是否去除红色框区域外{(ymin, ymax)}的字幕?'
f'\n输入 "y" 或 "回车" 表示去除,输入"n"或其他表示不去除: ').strip()
if user_input == 'y' or user_input == '\n':
with open(self.raw_subtitle_path, mode='r+', encoding='utf-8') as f:
content = f.readlines()
f.seek(0)
for i in content:
i_ymin = int(i.split('\t')[1].split('(')[1].split(')')[0].split(', ')[2])
i_ymax = int(i.split('\t')[1].split('(')[1].split(')')[0].split(', ')[3])
if ymin <= i_ymin and i_ymax <= ymax:
f.write(i)
f.truncate()
print('去除完毕')
# 删除缓存
if os.path.exists(sample_frame_file_path):
os.remove(sample_frame_file_path)
def generate_subtitle_file(self):
"""
生成srt格式的字幕文件
"""
subtitle_content = self._remove_duplicate_subtitle()
print(os.path.splitext(self.video_path)[0])
srt_filename = os.path.join(os.path.splitext(self.video_path)[0] + '.srt')
# 保存持续时间不足1秒的字幕行,用于后续处理
post_process_subtitle = []
with open(srt_filename, mode='w', encoding='utf-8') as f:
for index, content in enumerate(subtitle_content):
line_code = index + 1
frame_start = self._frame_to_timecode(int(content[0]))
# 比较起始帧号与结束帧号, 如果字幕持续时间不足1秒,则将显示时间设为1s
if abs(int(content[1]) - int(content[0])) < self.fps:
frame_end = self._frame_to_timecode(int(int(content[0]) + self.fps))
post_process_subtitle.append(line_code)
else:
frame_end = self._frame_to_timecode(int(content[1]))
frame_content = content[2]
subtitle_line = f'{line_code}\n{frame_start} --> {frame_end}\n{frame_content}\n'
f.write(subtitle_line)
print(f'字幕文件生成位置:{srt_filename}')
# 返回持续时间低于1s的字幕行
return post_process_subtitle
def _analyse_subtitle_frame(self):
"""
使用简单的图像算法找出包含字幕的视频帧
: 参考 https://github.com/BruceHan98/OCR-Extract-Subtitles/blob/main/analyze_key_frame.py
"""
if self.sub_area is None:
return None
else:
subtitle_frame_index_list = []
index = 0
s_ymin = self.sub_area[0]
s_ymax = self.sub_area[1]
s_xmin = self.sub_area[2]
s_xmax = self.sub_area[3]
cap = cv2.VideoCapture(self.video_path)
success, frame = cap.read()
if success:
# 截取字幕部分
frame = frame[s_ymin:s_ymax, s_xmin:s_xmax]
h, w = frame.shape[0:2]
if config.BG_MOD == config.BackgroundColor.DARK: # 深色背景
minuend = np.full(h * w, config.BG_VALUE_DARK) # 被减矩阵
else:
minuend = np.full(h * w, config.BG_VALUE_OTHER) # 被减矩阵
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flatten_gray = gray.flatten()
last_roi = flatten_gray - minuend
last_roi = np.where(last_roi > 0, 1, 0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame = frame[s_ymin:s_ymax, s_xmin:s_xmax]
if index % config.EXTRACT_INTERVAL == 0:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flatten_gray = gray.flatten()
roi = flatten_gray - minuend
roi = np.where(roi > 0, 1, 0)
change = roi - last_roi
addi = np.where(change > 0, 1, 0).sum()
if addi > roi.sum() * config.ROI_RATE: # 字幕增加
subtitle_frame_index_list.append(index)
last_roi = roi
index += 1
cap.release()
return subtitle_frame_index_list
def _detect_watermark_area(self):
"""
根据识别出来的raw txt文件中的坐标点信息,查找水印区域
假定:水印区域(台标)的坐标在水平和垂直方向都是固定的,也就是具有(xmin, xmax, ymin, ymax)相对固定
@@ -208,56 +477,7 @@ class SubtitleExtractor:
# 不够则有几个返回几个
return Counter(coordinates_list).most_common()
def filter_watermark(self):
"""
去除原始字幕文本中的水印区域的文本
"""
# 获取潜在水印区域
watermark_areas = self.detect_watermark_area()
# 从frame目录随机读取一张图片,将所水印区域标记出来,用户看图判断是否是水印区域
frame_path = os.path.join(self.frame_output_dir,
random.choice(
[i for i in sorted(os.listdir(self.frame_output_dir)) if i.endswith('.jpg')]))
sample_frame = cv2.imread(frame_path)
# 给潜在的水印区域编号
area_num = ['E', 'D', 'C', 'B', 'A']
for watermark_area in watermark_areas:
ymin = watermark_area[0][2]
ymax = watermark_area[0][3]
xmin = watermark_area[0][0]
xmax = watermark_area[0][1]
cover = sample_frame[ymin:ymax, xmin:xmax]
cover = cv2.blur(cover, (10, 10))
cv2.rectangle(cover, pt1=(0, cover.shape[0]), pt2=(cover.shape[1], 0), color=(0, 0, 255), thickness=3)
sample_frame[watermark_area[0][2]:watermark_area[0][3], watermark_area[0][0]:watermark_area[0][1]] = cover
position = ((xmin + xmax) // 2, ymax)
cv2.putText(sample_frame, text=area_num.pop(), org=position, fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1, color=(255, 0, 0), thickness=2, lineType=cv2.LINE_AA)
sample_frame_file_path = os.path.join(os.path.dirname(self.frame_output_dir), 'watermark_area.jpg')
cv2.imwrite(sample_frame_file_path, sample_frame)
print(f'请查看图片, 确定水印区域: {sample_frame_file_path}')
area_num = ['E', 'D', 'C', 'B', 'A']
for watermark_area in watermark_areas:
user_input = input(f'是否去除区域{area_num.pop()}{str(watermark_area)}中的字幕?'
f'\n输入 "y" 或 "回车" 表示去除,输入"n"或其他表示不去除: ').strip()
if user_input == 'y' or user_input == '\n':
with open(self.raw_subtitle_path, mode='r+', encoding='utf-8') as f:
content = f.readlines()
f.seek(0)
for i in content:
if i.find(str(watermark_area[0])) == -1:
f.write(i)
f.truncate()
print(f'已经删除该区域字幕...')
print('水印区域字幕过滤完毕...')
def detect_subtitle_area(self):
def _detect_subtitle_area(self):
"""
读取过滤水印区域后的raw txt文件,根据坐标信息,查找字幕区域
假定:字幕区域在y轴上有一个相对固定的坐标范围,相对于场景文本,这个范围出现频率更高
@@ -275,63 +495,30 @@ class SubtitleExtractor:
f.close()
return Counter(y_coordinates_list).most_common(1)
def filter_scene_text(self):
def _frame_preprocess(self, frame):
"""
将场景里提取的文字过滤,仅保留字幕区域
将视频帧进行裁剪
"""
# 获取潜在字幕区域
subtitle_area = self.detect_subtitle_area()[0][0]
# 从frame目录随机读取一张图片,将所水印区域标记出来,用户看图判断是否是水印区域
frame_path = os.path.join(self.frame_output_dir,
random.choice(
[i for i in sorted(os.listdir(self.frame_output_dir)) if i.endswith('.jpg')]))
sample_frame = cv2.imread(frame_path)
# 为了防止有双行字幕,根据容忍度,将字幕区域y范围加高
ymin = abs(subtitle_area[0] - config.SUBTITLE_AREA_DEVIATION_PIXEL)
ymax = subtitle_area[1] + config.SUBTITLE_AREA_DEVIATION_PIXEL
# 画出字幕框的区域
cv2.rectangle(sample_frame, pt1=(0, ymin), pt2=(sample_frame.shape[1], ymax), color=(0, 0, 255), thickness=3)
sample_frame_file_path = os.path.join(os.path.dirname(self.frame_output_dir), 'subtitle_area.jpg')
cv2.imwrite(sample_frame_file_path, sample_frame)
print(f'请查看图片, 确定字幕区域是否正确: {sample_frame_file_path}')
user_input = input(f'是否去除红色框区域外{(ymin, ymax)}的字幕?'
f'\n输入 "y" 或 "回车" 表示去除,输入"n"或其他表示不去除: ').strip()
if user_input == 'y' or user_input == '\n':
with open(self.raw_subtitle_path, mode='r+', encoding='utf-8') as f:
content = f.readlines()
f.seek(0)
for i in content:
i_ymin = int(i.split('\t')[1].split('(')[1].split(')')[0].split(', ')[2])
i_ymax = int(i.split('\t')[1].split('(')[1].split(')')[0].split(', ')[3])
if ymin <= i_ymin and i_ymax <= ymax:
f.write(i)
f.truncate()
def generate_subtitle_file(self):
"""
生成srt格式的字幕文件
"""
subtitle_content = self._remove_duplicate_subtitle()
print(os.path.splitext(self.video_path)[0])
srt_filename = os.path.join(os.path.splitext(self.video_path)[0] + '.srt')
with open(srt_filename, mode='w', encoding='utf-8') as f:
for index, content in enumerate(subtitle_content):
line_code = index + 1
frame_start = self._frame_to_timecode(int(content[0]))
frame_end = self._frame_to_timecode(int(content[1]))
frame_content = content[2]
subtitle_line = f'{line_code}\n{frame_start} --> {frame_end}\n{frame_content}\n'
f.write(subtitle_line)
# 对于分辨率大于1920*1080的视频,将其视频帧进行等比缩放至1280*720进行识别
# paddlepaddle会将图像压缩为640*640
# if self.frame_width > 1280:
# scale_rate = round(float(1280 / self.frame_width), 2)
# frame = cv2.resize(frame, None, fx=scale_rate, fy=scale_rate, interpolation=cv2.INTER_AREA)
cropped = int(frame.shape[0] // 2)
# 如果字幕出现的区域在下部分
if self.subtitle_area == SubtitleArea.LOWER_PART:
# 将视频帧切割为下半部分
frame = frame[cropped:]
# 如果字幕出现的区域在上半部分
elif self.subtitle_area == SubtitleArea.UPPER_PART:
# 将视频帧切割为下半部分
frame = frame[:cropped]
return frame
def _frame_to_timecode(self, frame_no):
"""
将视频帧转换成时间
:param frame_no: 视频的帧号,i.e. 第几帧视频帧
:param frame_rate: 视频的帧率
:param drop: 帧率不为整数时,是否添加drop frame进行补帧
:returns: SMPTE格式时间戳 as string, 如'01:02:12:32' 或者 '01:02:12;32'
"""
# 将小数点后两位的数字丢弃
@@ -400,11 +587,9 @@ class SubtitleExtractor:
if fps_int == 60:
frame_no = frame_no * 2
# time codes are on the form 12:12:12;12
smpte_token = ";"
smpte_token = "," # 也可能为;号
else:
# time codes are on the form 12:12:12:12
smpte_token = ","
# 将视频帧转化为时间戳
@@ -418,7 +603,8 @@ class SubtitleExtractor:
"""
读取原始的raw txt,去除重复行,返回去除了重复后的字幕列表
"""
with open(self.raw_subtitle_path, 'r') as r:
self._concat_content_with_same_frameno()
with open(self.raw_subtitle_path, mode='r', encoding='utf-8') as r:
lines = r.readlines()
content_list = []
for line in lines:
@@ -436,23 +622,91 @@ class SubtitleExtractor:
for j in content_list[index:]:
# 计算当前行与下一行的Levenshtein距离
distance = ratio(i[1], j[1])
if distance < config.TEXT_SIMILARITY_THRESHOLD or j == content_list[-1]:
if distance < config.THRESHOLD_TEXT_SIMILARITY or j == content_list[-1]:
# 定义字幕结束帧帧号
end_frame = content_list[content_list.index(j) - 1][0]
if end_frame == start_frame:
end_frame = j[0]
if str(unique_subtitle_list).find(i[1].replace('\n', '')) == -1:
# 如果是第一行字幕,直接添加进列表
if len(unique_subtitle_list) < 1:
unique_subtitle_list.append((start_frame, end_frame, i[1]))
else:
string_a = unique_subtitle_list[-1][2].replace(' ', '')
string_b = i[1].replace(' ', '')
similarity_ratio = ratio(string_a, string_b)
# 打印相似度
# print(f'{similarity_ratio}: {unique_subtitle_list[-1][2]} vs {i[1]}')
# 如果相似度小于阈值,说明该两行字幕不一样
if similarity_ratio < config.THRESHOLD_TEXT_SIMILARITY:
unique_subtitle_list.append((start_frame, end_frame, i[1]))
else:
# 如果大于阈值,但又不完全相同,说明两行字幕相似
# 可能出现以下情况: "但如何进人并接管上海" vs "但如何进入并接管上海"
# OCR识别出现了错误识别
if similarity_ratio < 1:
# TODO:
# 1) 取出两行字幕的并集
# 2) 纠错
# print(f'{round(similarity_ratio, 2)}, 需要手动纠错:\n {string_a} vs\n {string_b}')
# 保存较长的
if len(string_a) < len(string_b):
unique_subtitle_list[-1] = (start_frame, end_frame, i[1])
index += 1
break
else:
continue
return unique_subtitle_list
def _concat_content_with_same_frameno(self):
"""
将raw txt文本中具有相同帧号的字幕行合并
"""
with open(self.raw_subtitle_path, mode='r', encoding='utf-8') as r:
lines = r.readlines()
content_list = []
frame_no_list = []
for line in lines:
frame_no = line.split('\t')[0]
frame_no_list.append(frame_no)
coordinate = line.split('\t')[1]
content = line.split('\t')[2]
content_list.append([frame_no, coordinate, content])
# 找出那些不止一行的帧号
frame_no_list = [i[0] for i in Counter(frame_no_list).most_common() if i[1] > 1]
# 找出这些帧号出现的位置
concatenation_list = []
for frame_no in frame_no_list:
position = [i for i, x in enumerate(content_list) if x[0] == frame_no]
concatenation_list.append((frame_no, position))
for i in concatenation_list:
content = []
for j in i[1]:
content.append(content_list[j][2])
content = ' '.join(content).replace('\n', ' ') + '\n'
for k in i[1]:
content_list[k][2] = content
# 将多余的字幕行删除
to_delete = []
for i in concatenation_list:
for j in i[1][1:]:
to_delete.append(content_list[j])
for i in to_delete:
if i in content_list:
content_list.remove(i)
with open(self.raw_subtitle_path, mode='w', encoding='utf-8') as f:
for frame_no, coordinate, content in content_list:
content = unicodedata.normalize('NFKC', content)
f.write(f'{frame_no}\t{coordinate}\t{content}')
def _unite_coordinates(self, coordinates_list):
"""
给定一个坐标列表,将这个列表中相似的坐标统一为一个值
e.g. 由于检测框检测的结果不是一直的,相同位置文字的坐标可能一次检测为(255,123,456,789),另一次检测为(253,122,456,799)
e.g. 由于检测框检测的结果不是一致的,相同位置文字的坐标可能一次检测为(255,123,456,789),另一次检测为(253,122,456,799)
因此要对相似的坐标进行值的统一
:param coordinates_list 包含坐标点的列表
:return: 返回一个统一值后的坐标列表
@@ -534,6 +788,11 @@ class SubtitleExtractor:
image = image.convert('L')
return image
def __delete_frame_cache(self):
if len(os.listdir(self.frame_output_dir)) > 0:
for i in os.listdir(self.frame_output_dir):
os.remove(os.path.join(self.frame_output_dir, i))
if __name__ == '__main__':
# 提示用户输入视频路径
@@ -542,4 +801,3 @@ if __name__ == '__main__':
se = SubtitleExtractor(video_path)
# 开始提取字幕
se.run()
+31 -13
View File
@@ -1,14 +1,32 @@
shapely~=1.7.1
scikit-image==0.17.2
astor==0.8.1
certifi==2020.12.5
chardet==4.0.0
cycler==0.10.0
decorator==4.4.2
filesplit==3.0.2
gast==0.3.3
idna==2.10
imageio==2.9.0
imgaug==0.4.0
pyclipper~=1.2.1
lmdb~=1.1.1
opencv-python==4.2.0.32
tqdm~=4.59.0
numpy~=1.19.0
visualdl
python-Levenshtein
six~=1.15.0
pillow~=8.1.2
pyyaml~=5.4.1
requests~=2.25.1
kiwisolver==1.3.1
lmdb==1.1.1
matplotlib==3.4.1
networkx==2.5.1
numpy==1.19.0
opencv-python==4.5.1.48
paddlepaddle==2.0.1
Pillow==8.2.0
protobuf==3.15.8
pyclipper==1.2.1
pyparsing==2.4.7
PySimpleGUI==4.38.0
python-dateutil==2.8.1
python-Levenshtein-wheels==0.13.2
PyWavelets==1.1.1
requests==2.25.1
scikit-image==0.18.1
scipy==1.6.2
Shapely==1.7.1
six==1.15.0
tifffile==2021.4.8
urllib3==1.26.4
+32
View File
@@ -0,0 +1,32 @@
astor==0.8.1
certifi==2020.12.5
chardet==4.0.0
cycler==0.10.0
decorator==4.4.2
filesplit==3.0.2
gast==0.3.3
idna==2.10
imageio==2.9.0
imgaug==0.4.0
kiwisolver==1.3.1
lmdb==1.1.1
matplotlib==3.4.1
networkx==2.5.1
numpy==1.19.0
opencv-python==4.5.1.48
paddlepaddle-gpu==2.0.1
Pillow==8.2.0
protobuf==3.15.8
pyclipper==1.2.1
pyparsing==2.4.7
PySimpleGUI==4.38.0
python-dateutil==2.8.1
python-Levenshtein-wheels==0.13.2
PyWavelets==1.1.1
requests==2.25.1
scikit-image==0.18.1
scipy==1.6.2
Shapely==1.7.1
six==1.15.0
tifffile==2021.4.8
urllib3==1.26.4