dlxj commited on
Commit
ce0144c
·
1 Parent(s): 03d4c37
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .gitignore +47 -0
  3. LICENSE +202 -0
  4. README.md +106 -0
  5. config/_base_/datasets/complete_data.py +152 -0
  6. config/_base_/datasets/iacc2022_chdac.py +28 -0
  7. config/_base_/datasets/iacc2022_chdac_toy.py +12 -0
  8. config/_base_/datasets/icdar2019hdrc.py +30 -0
  9. config/_base_/datasets/mthv2.py +19 -0
  10. config/_base_/default_runtime.py +46 -0
  11. config/_base_/schedules/schedule_adam_600e.py +13 -0
  12. config/_base_/schedules/schedule_sgd_500e.py +13 -0
  13. config/_base_/textdet_runtime.py +36 -0
  14. config/baseline/config.py +96 -0
  15. config/baseline/model/dbnetpp.py +37 -0
  16. config/baseline/model/psenet.py +44 -0
  17. config/baseline/pipeline.py +51 -0
  18. config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.py +47 -0
  19. config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.py +44 -0
  20. config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.py +44 -0
  21. config/seghist/_base_seghist_resnet50-dcnv2_fpnc.py +48 -0
  22. config/seghist/pipeline/seghist_pipeline_basic.py +50 -0
  23. config/seghist/pipeline/seghist_pipeline_basic_rotate.py +58 -0
  24. config/seghist/pipeline/seghist_pipeline_color_jitter.py +48 -0
  25. config/seghist/pipeline/seghist_pipeline_large_rotate.py +57 -0
  26. config/seghist/pipeline/seghist_pipeline_largescale.py +49 -0
  27. config/seghist/seghist_resnet50-dcnv2_fpnc.py +89 -0
  28. config/seghist/seghist_resnet50-dcnv2_fpnc_large.py +75 -0
  29. config/seghist/seghist_resnet50-dcnv2_fpnc_toy.py +67 -0
  30. environment.yml +198 -0
  31. readme.txt +1 -0
  32. samples/gt1.png +3 -0
  33. samples/gt2.png +3 -0
  34. samples/pred1.png +3 -0
  35. samples/pred2.png +3 -0
  36. seghist/__init__.py +2 -0
  37. seghist/datasets/__init__.py +1 -0
  38. seghist/datasets/transforms/__init__.py +5 -0
  39. seghist/datasets/transforms/colorspace.py +30 -0
  40. seghist/datasets/transforms/textdet_transforms.py +164 -0
  41. seghist/model/__init__.py +10 -0
  42. seghist/model/heads/seghist_heads.py +280 -0
  43. seghist/model/layer/dyrelu.py +88 -0
  44. seghist/model/layer/layout_enhanced_block.py +292 -0
  45. seghist/model/module_loss/db_tks.py +143 -0
  46. seghist/model/module_loss/pan_tks.py +53 -0
  47. seghist/model/module_loss/pse_tks.py +15 -0
  48. seghist/model/module_loss/tks.py +138 -0
  49. seghist/model/postprocessor/iedp.py +123 -0
  50. seghist/utils/__init__.py +2 -0
.gitattributes CHANGED
@@ -1,4 +1,5 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.avro filter=lfs diff=lfs merge=lfs -text
4
  *.bin filter=lfs diff=lfs merge=lfs -text
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.pdf filter=lfs diff=lfs merge=lfs -text
3
  *.arrow filter=lfs diff=lfs merge=lfs -text
4
  *.avro filter=lfs diff=lfs merge=lfs -text
5
  *.bin filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 操作系统生成的文件
2
+ .DS_Store
3
+ Thumbs.db
4
+
5
+ # 日志文件
6
+ *.log
7
+
8
+ # Python 编译生成的文件
9
+ *.pyc
10
+ *.pyo
11
+
12
+ # 虚拟环境
13
+ env/
14
+ venv/
15
+ .venv/
16
+
17
+ # 配置文件
18
+ .env
19
+ .env.local
20
+ .env.*.local
21
+
22
+ # 项目依赖
23
+ .mypy_cache/
24
+ .tox/
25
+ .coverage
26
+ .cache
27
+ nosetests.xml
28
+ coverage.xml
29
+ *.cover
30
+
31
+ # 临时文件和目录
32
+ .dist_test/
33
+ *.swp
34
+ .idea/
35
+ .vscode/
36
+ *.ipynb
37
+
38
+ # 忽略所有目录,不包含 config 和 seghist,同时忽略下面的pycache
39
+ */
40
+ data
41
+ !config/
42
+ !config/**
43
+ !seghist/
44
+ !seghist/**
45
+ !samples/
46
+ !samples/**
47
+ **/__pycache__/
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Xingjian Hu from Peking University.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (ICDAR 2024) SegHist: A General Segmentation-based Framework for Chinese Historical Document Text Line Detection
2
+
3
+ <div align="center">
4
+
5
+ [![arXiv](https://img.shields.io/badge/Arxiv-2406.15485-A42C25?style=flat&logo=arXiv&logoColor=A42C25)](https://arxiv.org/abs/2406.15485)
6
+
7
+ [![GitHub watchers](https://img.shields.io/github/watchers/LumionHXJ/SegHist?style=social)](https://github.com/LumionHXJ/SegHist/watchers)
8
+
9
+ [![GitHub stars](https://img.shields.io/github/stars/LumionHXJ/SegHist?style=social)](https://github.com/LumionHXJ/SegHist/stargazers)
10
+
11
+ [![Visits Badge](https://badges.pufler.dev/visits/LumionHXJ/SegHist)](https://github.com/LumionHXJ/SegHist)
12
+ </div>
13
+
14
+ **Official implementation based on [MMOCR](https://github.com/open-mmlab/mmocr) for paper ["SegHist: A General Segmentation-based Framework for Chinese Historical Document Text Line Detection"](https://arxiv.org/abs/2406.15485).**
15
+
16
+ ## 🔍 **Examples**
17
+
18
+ | Groundtruth | Prediction |
19
+ | --------------------------- | ------------------------------- |
20
+ | ![gt1](samples/gt1.png) | ![pred1](samples/pred1.png) |
21
+ | ![gt2](samples/gt2.png) | ![pred2](samples/pred2.png) |
22
+
23
+ ## 📄 Abstract
24
+
25
+ Text line detection is a key task in historical document analysis facing many challenges of arbitrary-shaped text lines, dense texts, and text lines with high aspect ratios, etc. In this paper, we propose a general **Seg**mentation-based framework for **Hist**orical document text detection (SegHist), enabling existing text detection methods to effectively address the challenges, especially text lines with high aspect ratios. Integrating the SegHist framework with the commonly used method DB++, we develop DB-SegHist. This approach achieves SOTA on the CHDAC, MTHv2, and competitive results on HDRC datasets, with a significant improvement of 1.19% on the most challenging CHDAC dataset which features more text lines with high aspect ratios. Moreover, our method attains SOTA on rotated MTHv2 and rotated HDRC, demonstrating its rotational robustness.
26
+
27
+ ## ⚙️ **Requirements**
28
+
29
+ Installing using config:
30
+
31
+ ```bash
32
+ conda env create -f environment.yml
33
+ ```
34
+
35
+ Or installing step-by-step:
36
+
37
+ ```bash
38
+ conda create --name openmmlab python=3.8 -y
39
+ conda activate openmmlab
40
+ conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 -c pytorch
41
+ pip install -U openmim
42
+ mim install mmengine==0.10.4 mmcv==2.0.1 mmdet==3.0.0 mmocr==1.0.0rc5
43
+ ```
44
+
45
+ ## 🚀 **Training**
46
+
47
+ Training DB-SegHist as example (training other model by changing checkpoint):
48
+
49
+ ```bash
50
+ python -m torch.distributed.run --nproc_per_node=4 train.py --launcher pytorch --work-dir work_dirs/ config/seghist/seghist_resnet50-dcnv2_fpnc.py
51
+ ```
52
+
53
+ ## 🧠 **Inferencing**
54
+
55
+ ```bash
56
+ python test.py --work-dir work_dirs/ config/seghist/seghist_resnet50-dcnv2_fpnc.py [your_checkpoint]
57
+ ```
58
+
59
+ ## 📚 **Acquiring Data**
60
+
61
+ The data we used can be accessed as follows:
62
+
63
+ - CHDAC: Contact their [email](iacc_pazhoulab_hp@163.com) or visit their [official website](https://iacc.pazhoulab-huangpu.com/).
64
+ - MTHv2: https://github.com/HCIILAB/MTHv2_Datasets_Release
65
+ - ICDAR2019: https://tc11.cvc.uab.es/datasets/ICDAR2019HDRC
66
+
67
+ ## 🏆 **Our Results on CHDAC**
68
+
69
+ | Method | P | R | F |
70
+ |-------------------------|--------|--------|--------|
71
+ | EAST [Zhou et al. 2017] | 61.41 | 73.13 | 66.76 |
72
+ | Mask R-CNN [He et al. 2017] | 89.03 | 80.90 | 84.77 |
73
+ | Cascade R-CNN [Cai et al. 2018] | 92.82 | 83.63 | 87.98 |
74
+ | OBD [Liu et al. 2021] | 94.73 | 81.52 | 87.63 |
75
+ | TextSnake [Long et al. 2018] | 96.33 | 89.62 | 92.85 |
76
+ | PSENet [Wang et al. 2019] | 76.99 | 89.62 | 82.83 |
77
+ | PAN [Wang et al. 2019] | 92.74 | 85.71 | 89.09 |
78
+ | FCENet [Zhu et al. 2021] | 88.42 | 85.04 | 86.70 |
79
+ | DBNet++ [Liao et al. 2022] | 91.39 | 89.15 | 90.26 |
80
+ | HisDoc R-CNN [Jian et al. 2023] | _98.19_ | 93.74 | 95.92 |
81
+ | **PSE-SegHist (ours)** | 97.00 | _95.31_ | _96.15_ |
82
+ | **PAN-SegHist (ours)** | 97.52 | 94.77 | 96.12 |
83
+ | **DB-SegHist (ours)** | **98.36** | **95.88** | **97.11** |
84
+
85
+ *_P_, _R_, and _F_ indicate the precision, recall, and F-measure, respectively, at an IoU threshold of 0.5.
86
+
87
+ ## 🔒 **LICENSE**
88
+
89
+ This code is distributed under the Apache License. Please note that the datasets we rely on may not be allowed for commercial use.
90
+
91
+ ## 🔗 **CITATION**
92
+
93
+ ```
94
+ @inproceedings{hu2024seghist,
95
+ title={SegHist: A General Segmentation-Based Framework for Chinese Historical Document Text Line Detection},
96
+ author={Hu, Xingjian and Wei, Baole and Gao, Liangcai and Wang, Jun},
97
+ booktitle={International Conference on Document Analysis and Recognition},
98
+ pages={391--410},
99
+ year={2024},
100
+ organization={Springer}
101
+ }
102
+ ```
103
+
104
+ ## 📧 **CONTACT US**
105
+
106
+ If you have any question, please contact: huxingjian@pku.edu.cn.
config/_base_/datasets/complete_data.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
+ data_root = 'data/historical_document/IACC2022_CHDAC/official_dataset'
3
+ =======
4
+ data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'
5
+ >>>>>>> origin/main
6
+
7
+ chdac_train_preliminary = dict(
8
+ type='OCRDataset',
9
+ data_root=data_root,
10
+ ann_file='preliminary/train/ocr_train.json',
11
+ data_prefix=dict(img_path='preliminary/train/image'),
12
+ pipeline=None)
13
+
14
+ chdac_train_final = dict(
15
+ type='OCRDataset',
16
+ data_root=data_root,
17
+ ann_file='final/train/ocr_train.json',
18
+ data_prefix=dict(img_path='final/train/image'),
19
+ pipeline=None)
20
+
21
+ chdac_test = dict(
22
+ type='OCRDataset',
23
+ data_root=data_root,
24
+ ann_file='final/test/ocr_test.json',
25
+ data_prefix=dict(img_path='final/test/image'),
26
+ test_mode=True,
27
+ pipeline=None)
28
+
29
+ <<<<<<< HEAD
30
+ data_root = 'data/historical_document/IACC2022_CHDAC/private_dataset'
31
+ =======
32
+ data_root = './data/historical_document/IACC2022_CHDAC/private_dataset'
33
+ >>>>>>> origin/main
34
+
35
+ chdac_train_private1 = dict(
36
+ type='OCRDataset',
37
+ data_root=data_root,
38
+ ann_file='dataset_1/train/ocr_train.json',
39
+ data_prefix=dict(img_path='dataset_1/train/image'),
40
+ pipeline=None)
41
+
42
+ chdac_test_private1 = dict(
43
+ type='OCRDataset',
44
+ data_root=data_root,
45
+ ann_file='dataset_1/test/ocr_test.json',
46
+ data_prefix=dict(img_path='dataset_1/test/image'),
47
+ test_mode=True,
48
+ pipeline=None)
49
+
50
+ chdac_train_private2 = dict(
51
+ type='OCRDataset',
52
+ data_root=data_root,
53
+ ann_file='dataset_2/train/ocr_train.json',
54
+ data_prefix=dict(img_path='dataset_2/train/image'),
55
+ pipeline=None)
56
+
57
+ chdac_test_private2 = dict(
58
+ type='OCRDataset',
59
+ data_root=data_root,
60
+ ann_file='dataset_2/test/ocr_test.json',
61
+ data_prefix=dict(img_path='dataset_2/test/image'),
62
+ test_mode=True,
63
+ pipeline=None)
64
+
65
+ chdac_train_private3 = dict(
66
+ type='OCRDataset',
67
+ data_root=data_root,
68
+ ann_file='dataset_3/train/ocr_train.json',
69
+ data_prefix=dict(img_path='dataset_3/train/image'),
70
+ pipeline=None)
71
+
72
+ chdac_test_private3 = dict(
73
+ type='OCRDataset',
74
+ data_root=data_root,
75
+ ann_file='dataset_3/test/ocr_test.json',
76
+ data_prefix=dict(img_path='dataset_3/test/image'),
77
+ test_mode=True,
78
+ pipeline=None)
79
+
80
+ data_root = './data/historical_document/ICDAR2019HDRC_Chinese/'
81
+
82
+ icdar2019_trainset = dict(
83
+ type='OCRDataset',
84
+ data_root=data_root,
85
+ ann_file='train_label_comp.json',
86
+ data_prefix=dict(img_path='images'),
87
+ pipeline=None)
88
+
89
+ icdar2019_testset = dict(
90
+ type='OCRDataset',
91
+ data_root=data_root,
92
+ ann_file='test_label_comp.json',
93
+ test_mode=True,
94
+ data_prefix=dict(img_path='images'),
95
+ # indices=50 在更小的数据集上尝试验证效果
96
+ pipeline=None)
97
+
98
+ data_root = './data/historical_document/MTHv2/MTHv2'
99
+
100
+ mthv2_trainset = dict(
101
+ type='OCRDataset',
102
+ data_root=data_root,
103
+ ann_file='train_label.json',
104
+ pipeline=None)
105
+
106
+ mthv2_testset = dict(
107
+ type='OCRDataset',
108
+ data_root=data_root,
109
+ ann_file='test_label.json',
110
+ test_mode=True,
111
+ pipeline=None)
112
+
113
+ data_root = './data/historical_document/MTHv2/twist_MTHv2'
114
+
115
+ twist_mthv2_trainset = dict(
116
+ type='OCRDataset',
117
+ data_root=data_root,
118
+ ann_file='train_label.json',
119
+ pipeline=None)
120
+
121
+ twist_mthv2_testset = dict(
122
+ type='OCRDataset',
123
+ data_root=data_root,
124
+ ann_file='test_label.json',
125
+ test_mode=True,
126
+ pipeline=None)
127
+
128
+ data_root = './data/historical_document/Huayan'
129
+
130
+ huayan_trainset = dict(
131
+ type='OCRDataset',
132
+ data_root=data_root,
133
+ ann_file='train_label.json',
134
+ data_prefix=dict(img_path='images'),
135
+ pipeline=None
136
+ )
137
+
138
+ huayan_testset = dict(
139
+ type='OCRDataset',
140
+ data_root=data_root,
141
+ ann_file='test_label.json',
142
+ data_prefix=dict(img_path='images'),
143
+ test_mode=True,
144
+ pipeline=None
145
+ )
146
+ # 没有使用mthv2
147
+ train_list = [chdac_train_preliminary, chdac_train_final, icdar2019_trainset,
148
+ twist_mthv2_trainset, huayan_trainset,
149
+ chdac_train_private1, chdac_train_private2, chdac_train_private3]
150
+ test_list = [chdac_test, icdar2019_testset, huayan_testset, twist_mthv2_testset,
151
+ chdac_test_private1, chdac_test_private2, chdac_test_private3]
152
+ val_list = test_list
config/_base_/datasets/iacc2022_chdac.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'
2
+
3
+ chdac_train_preliminary = dict(
4
+ type='OCRDataset',
5
+ data_root=data_root,
6
+ ann_file='preliminary/train/ocr_train.json',
7
+ data_prefix=dict(img_path='preliminary/train/image'),
8
+ pipeline=None)
9
+
10
+ chdac_train_final = dict(
11
+ type='OCRDataset',
12
+ data_root=data_root,
13
+ ann_file='final/train/ocr_train.json',
14
+ data_prefix=dict(img_path='final/train/image'),
15
+ pipeline=None)
16
+
17
+ chdac_test = dict(
18
+ type='OCRDataset',
19
+ data_root=data_root,
20
+ ann_file='final/test/ocr_test.json',
21
+ data_prefix=dict(img_path='final/test/image'),
22
+ test_mode=True,
23
+ #indices=150, #在更小的数据集上尝试验证效果
24
+ pipeline=None)
25
+
26
+ train_list = [chdac_train_preliminary, chdac_train_final]
27
+ test_list = [chdac_test]
28
+ val_list = test_list
config/_base_/datasets/iacc2022_chdac_toy.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'
2
+
3
+ chdac_toy = dict(
4
+ type='OCRDataset',
5
+ data_root=data_root,
6
+ ann_file='final/train/ocr_toy.json',
7
+ data_prefix=dict(img_path='final/train/image'),
8
+ pipeline=None)
9
+
10
+ train_list = [chdac_toy]
11
+ test_list = [chdac_toy]
12
+ val_list = [chdac_toy]
config/_base_/datasets/icdar2019hdrc.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root = './data/historical_document/ICDAR2019HDRC_Chinese/'
2
+
3
+ trainset = dict(
4
+ type='OCRDataset',
5
+ data_root=data_root,
6
+ ann_file='train_label.json',
7
+ data_prefix=dict(img_path='images'),
8
+ pipeline=None)
9
+
10
+ valset = dict(
11
+ type='OCRDataset',
12
+ data_root=data_root,
13
+ ann_file='val_label.json',
14
+ test_mode=True,
15
+ data_prefix=dict(img_path='images'),
16
+ # indices=50 在更小的数据集上尝试验证效果
17
+ pipeline=None)
18
+
19
+ testset = dict(
20
+ type='OCRDataset',
21
+ data_root=data_root,
22
+ ann_file='test_label.json',
23
+ test_mode=True,
24
+ data_prefix=dict(img_path='images'),
25
+ # indices=50 在更小的数据集上尝试验证效果
26
+ pipeline=None)
27
+
28
+ train_list = [trainset]
29
+ val_list = [valset]
30
+ test_list = [testset]
config/_base_/datasets/mthv2.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data_root = './data/historical_document/MTHv2/MTHv2'
2
+
3
+ trainset = dict(
4
+ type='OCRDataset',
5
+ data_root=data_root,
6
+ ann_file='train_label.json',
7
+ pipeline=None)
8
+
9
+ testset = dict(
10
+ type='OCRDataset',
11
+ data_root=data_root,
12
+ ann_file='test_label.json',
13
+ test_mode=True,
14
+ # indices=50 在更小的数据集上尝试验证效果
15
+ pipeline=None)
16
+
17
+ train_list = [trainset]
18
+ test_list = [testset]
19
+ val_list = [testset]
config/_base_/default_runtime.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_scope = 'mmocr'
2
+ env_cfg = dict(
3
+ cudnn_benchmark=True,
4
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
5
+ dist_cfg=dict(backend='nccl'),
6
+ )
7
+ randomness = dict(seed=None)
8
+
9
+ default_hooks = dict(
10
+ timer=dict(type='IterTimerHook'),
11
+ logger=dict(type='LoggerHook', interval=10), #
12
+ param_scheduler=dict(type='ParamSchedulerHook'),
13
+ checkpoint=dict(type='CheckpointHook',
14
+ interval=5,
15
+ max_keep_ckpts=3),
16
+ sampler_seed=dict(type='DistSamplerSeedHook'),
17
+ sync_buffer=dict(type='SyncBuffersHook'),
18
+ visualization=dict(
19
+ type='VisualizationHook',
20
+ interval=1,
21
+ enable=False,
22
+ show=False,
23
+ draw_gt=False,
24
+ draw_pred=False),
25
+ )
26
+
27
+ custom_hooks = [dict(type='EmptyCacheHook', after_iter=True),
28
+ dict(type='SyncBuffersHook')]
29
+
30
+ # Logging
31
+ log_level = 'INFO'
32
+ log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True)
33
+
34
+ # Evaluation
35
+ val_evaluator = [dict(type='E2EHmeanIOUMetric'),
36
+ dict(type='HmeanIOUMetric'),
37
+ dict(type='E2ENEDMetric')]
38
+ test_evaluator = val_evaluator
39
+
40
+ # Visualization
41
+ vis_backends = [dict(type='LocalVisBackend'),
42
+ dict(type='TensorboardVisBackend')]
43
+ visualizer = dict(
44
+ type='TextSpottingLocalVisualizer',
45
+ name='visualizer',
46
+ vis_backends=vis_backends)
config/_base_/schedules/schedule_adam_600e.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # optimizer
2
+ # 不同层采用不同学习率,下调学习率后scheduler也要调整
3
+ optim_wrapper = dict(type='OptimWrapper',
4
+ optimizer=dict(type='AdamW', lr=1e-3))
5
+ train_cfg = dict(type='EpochBasedTrainLoop',
6
+ max_epochs=200,
7
+ val_interval=10)
8
+
9
+ val_cfg = dict(type='ValLoop')
10
+ test_cfg = dict(type='TestLoop')
11
+
12
+
13
+ #param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[50, 120], gamma=0.1)
config/_base_/schedules/schedule_sgd_500e.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # optimizer
3
+ optim_wrapper = dict(
4
+ type='OptimWrapper',
5
+ optimizer=dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0001),
6
+ clip_grad=dict(type='value', clip_value=1))
7
+ train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=1, val_interval=50)
8
+ val_cfg = dict(type='ValLoop')
9
+ test_cfg = dict(type='TestLoop')
10
+ # learning policy
11
+ param_scheduler = [
12
+ dict(type='LinearLR', end=1000, start_factor=0.001, by_epoch=False),
13
+ ]
config/_base_/textdet_runtime.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_scope = 'mmocr'
2
+ env_cfg = dict(
3
+ cudnn_benchmark=True,
4
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
5
+ dist_cfg=dict(backend='nccl'),
6
+ )
7
+
8
+ default_hooks = dict(
9
+ timer=dict(type='IterTimerHook'),
10
+ logger=dict(type='LoggerHook', interval=10),
11
+ param_scheduler=dict(type='ParamSchedulerHook'),
12
+ checkpoint=dict(type='CheckpointHook',
13
+ interval=5,
14
+ max_keep_ckpts=10),
15
+ sampler_seed=dict(type='DistSamplerSeedHook'),
16
+ sync_buffer=dict(type='SyncBuffersHook'),
17
+ visualization=dict(
18
+ type='VisualizationHook',
19
+ interval=1,
20
+ enable=False,
21
+ show=False,
22
+ draw_gt=False,
23
+ draw_pred=False),
24
+ )
25
+
26
+ # Logging
27
+ log_level = 'INFO'
28
+ log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True)
29
+
30
+
31
+ # Visualization
32
+ vis_backends = [dict(type='LocalVisBackend'), dict(type='TensorboardVisBackend')]
33
+ visualizer = dict(
34
+ type='TextDetLocalVisualizer',
35
+ name='visualizer',
36
+ vis_backends=vis_backends)
config/baseline/config.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _base_ = [
2
+ './model/dbnetpp.py',
3
+ './pipeline.py',
4
+ '../_base_/textdet_runtime.py',
5
+ '../_base_/datasets/iacc2022_chdac.py'
6
+ ]
7
+
8
+ # dataset settings
9
+ train_list = _base_.train_list
10
+ test_list = _base_.test_list
11
+ val_list = _base_.val_list
12
+
13
+ train_dataloader = dict(
14
+ batch_size=8,
15
+ num_workers=8,
16
+ persistent_workers=True,
17
+ sampler=dict(type='DefaultSampler', shuffle=True),
18
+ dataset=dict(
19
+ type='ConcatDataset',
20
+ datasets=train_list,
21
+ pipeline=_base_.train_pipeline))
22
+
23
+ test_dataloader = dict(
24
+ batch_size=1,
25
+ num_workers=1,
26
+ persistent_workers=False,
27
+ sampler=dict(type='DefaultSampler', shuffle=False),
28
+ dataset=dict(
29
+ type='ConcatDataset',
30
+ datasets=test_list,
31
+ pipeline=_base_.test_pipeline))
32
+
33
+ val_dataloader = dict(
34
+ batch_size=1,
35
+ num_workers=1,
36
+ persistent_workers=False,
37
+ sampler=dict(type='DefaultSampler', shuffle=False),
38
+ dataset=dict(
39
+ type='ConcatDataset',
40
+ datasets=val_list,
41
+ pipeline=_base_.test_pipeline))
42
+
43
+ auto_scale_lr = dict(base_batch_size=16)
44
+
45
+ test_evaluator = [dict(type='HmeanIOUMetric',
46
+ prefix='Iacc',
47
+ match_iou_thr=0.5,
48
+ pred_score_thrs=dict(start=0.3, stop=0.9, step=0.05)),
49
+ dict(type='HmeanIOUMetric',
50
+ prefix='Iacc75',
51
+ match_iou_thr=0.75,
52
+ pred_score_thrs=dict(start=0.3, stop=0.9, step=0.05))]
53
+ val_evaluator = test_evaluator
54
+
55
+ train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=250, val_interval=10)
56
+ default_hooks = dict(
57
+ checkpoint=dict(type='CheckpointHook',
58
+ interval=5,
59
+ max_keep_ckpts=10))
60
+
61
+ val_cfg = dict(type='ValLoop')
62
+ test_cfg = dict(type='TestLoop')
63
+
64
+ <<<<<<< HEAD
65
+ =======
66
+ '''
67
+ param_scheduler = dict(
68
+ type='MultiStepLR', by_epoch=True, milestones=[110], gamma=0.1)
69
+ '''
70
+ >>>>>>> origin/main
71
+ param_scheduler = [dict(type='ReduceOnPlateauLR',
72
+ rule='greater',
73
+ monitor='Iacc/recall',
74
+ factor=0.3,
75
+ patience=1,
76
+ threshold=1e-4)] # use arg last_step when resuming optim!
77
+
78
+ custom_imports = dict(
79
+ imports=['seghist'], # not support relative import
80
+ allow_failed_imports=False)
81
+
82
+
83
+ optim_wrapper = dict(
84
+ type='AmpOptimWrapper',
85
+ optimizer=dict(type='AdamW', lr=1e-4))
86
+
87
+ <<<<<<< HEAD
88
+ =======
89
+ '''
90
+ optim_wrapper = dict(
91
+ type='OptimWrapper',
92
+ optimizer=dict(type='AdamW', lr=1e-3))'''
93
+
94
+ >>>>>>> origin/main
95
+ #resume = True
96
+ #load_from = '/home/huxingjian/model/mmocr/projects/SegHist/work_dirs_baseline/dbnetpp/epoch_5.pth'
config/baseline/model/dbnetpp.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model = dict(
2
+ type='DBNet',
3
+ backbone=dict(
4
+ type='mmdet.ResNet',
5
+ depth=50,
6
+ num_stages=4,
7
+ out_indices=(0, 1, 2, 3),
8
+ frozen_stages=-1,
9
+ norm_cfg=dict(type='BN', requires_grad=True),
10
+ norm_eval=False,
11
+ style='pytorch',
12
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
13
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
14
+ stage_with_dcn=(False, True, True, True)),
15
+ neck=dict(
16
+ type='FPNC',
17
+ in_channels=[256, 512, 1024, 2048],
18
+ lateral_channels=256,
19
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
20
+ det_head=dict(
21
+ type='DBHead',
22
+ in_channels=256,
23
+ module_loss=dict(type='DBModuleLoss'),
24
+ postprocessor=dict(
25
+ type='IterExpandPostprocessor',
26
+ text_repr_type='poly',
27
+ epsilon_ratio=0.002,
28
+ shrink_ratio=0.16,
29
+ stretch_ratio=1,
30
+ refine=True,
31
+ unclip_ratio=2.5)),
32
+ data_preprocessor=dict(
33
+ type='TextDetDataPreprocessor',
34
+ mean=[123.675, 116.28, 103.53],
35
+ std=[58.395, 57.12, 57.375],
36
+ bgr_to_rgb=True,
37
+ pad_size_divisor=32))
config/baseline/model/psenet.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model = dict(
2
+ type='DBNet',
3
+ backbone=dict(
4
+ type='mmdet.ResNet',
5
+ depth=50,
6
+ num_stages=4,
7
+ out_indices=(0, 1, 2, 3),
8
+ frozen_stages=-1,
9
+ norm_cfg=dict(type='BN', requires_grad=True),
10
+ norm_eval=False,
11
+ style='pytorch',
12
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
13
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
14
+ stage_with_dcn=(False, True, True, True)),
15
+ neck=dict(
16
+ type='FPNC',
17
+ in_channels=[256, 512, 1024, 2048],
18
+ lateral_channels=256,
19
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
20
+ det_head=dict(
21
+ type='PANSegHistHead',
22
+ in_channels=256,
23
+ num_blocks=0,
24
+ num_query=8,
25
+ output_channels=7,
26
+ shallow_channels=128,
27
+ embedding_channels=128, # = shallow channels
28
+ use_dyrelu=True,
29
+ dyrelu_mode='awared',
30
+ with_m2f_mask=True,
31
+ module_loss=dict(type='PSETKSModuleLoss',
32
+ shrink_ratio=(1, 0.81, 0.64, 0.49, 0.36, 0.25, 0.16),
33
+ stretch_ratio=1),
34
+ postprocessor=dict(type='PSEPostprocessor',
35
+ text_repr_type='poly',
36
+ min_text_area=200,
37
+ score_threshold=0.3,
38
+ downsample_ratio=1)),
39
+ data_preprocessor=dict(
40
+ type='TextDetDataPreprocessor',
41
+ mean=[123.675, 116.28, 103.53],
42
+ std=[58.395, 57.12, 57.375],
43
+ bgr_to_rgb=True,
44
+ pad_size_divisor=32))
config/baseline/pipeline.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(
9
+ type='TorchVisionWrapper',
10
+ op='ColorJitter',
11
+ brightness=0.12549019607843137,
12
+ saturation=0.5),
13
+ dict(type='RandomFlip',
14
+ prob=0.5,
15
+ direction=['horizontal', 'vertical']), # both direction
16
+ dict(
17
+ type='RandomRotate',
18
+ max_angle=10 # [-10, 10]
19
+ ),
20
+ dict(
21
+ type='RandomChoiceResize',
22
+ scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800),
23
+ (1333, 832), (1333, 864), (1333, 896)],
24
+ keep_ratio=True,
25
+ clip_object_border=False), # clip the object when outside border
26
+ dict(type='TextDetRandomCrop', target_size=(640, 640)),
27
+ dict(type='Pad', size=(640, 640)),
28
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
29
+ dict(
30
+ type='PackTextDetInputs',
31
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
32
+ ]
33
+ test_pipeline = [
34
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
35
+ dict(
36
+ type='Resize',
37
+ scale=(1333, 800),
38
+ keep_ratio=True,
39
+ clip_object_border=True),
40
+ dict(
41
+ type='LoadOCRAnnotations',
42
+ with_polygon=True,
43
+ with_bbox=False,
44
+ with_label=True),
45
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
46
+ dict(
47
+ type='PackTextDetInputs',
48
+ meta_keys=('img_path', 'ori_shape',
49
+ 'img_shape', 'scale_factor',
50
+ 'valid_shape', 'instances'))
51
+ ]
config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r = 0. # shrink_ratio
2
+ stretch_ratio = 2. # 1.5
3
+ model = dict(
4
+ type='DBNet',
5
+ backbone=dict(
6
+ type='mmdet.ResNet',
7
+ depth=50,
8
+ num_stages=4,
9
+ out_indices=(0, 1, 2, 3),
10
+ frozen_stages=-1,
11
+ norm_cfg=dict(type='BN', requires_grad=True),
12
+ norm_eval=False,
13
+ style='pytorch',
14
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
15
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
16
+ stage_with_dcn=(False, True, True, True)),
17
+ neck=dict(
18
+ type='FPNC',
19
+ in_channels=[256, 512, 1024, 2048],
20
+ lateral_channels=256,
21
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
22
+ det_head=dict(
23
+ type='DBSegHistHead',
24
+ in_channels=256,
25
+ num_blocks=3,
26
+ num_query=8,
27
+ shallow_channels=128,
28
+ embedding_channels=128, # = shallow channels
29
+ use_dyrelu=True,
30
+ dyrelu_mode='awared',
31
+ with_m2f_mask=True,
32
+ module_loss=dict(type='DBTKSModuleLoss',
33
+ shrink_ratio=r,
34
+ stretch_ratio=stretch_ratio),
35
+ postprocessor=dict(
36
+ type='IterExpandPostprocessor',
37
+ text_repr_type='poly',
38
+ shrink_ratio=r,
39
+ stretch_ratio=stretch_ratio,
40
+ epsilon_ratio=0.002,
41
+ mask_thr=0.6)),
42
+ data_preprocessor=dict(
43
+ type='TextDetDataPreprocessor',
44
+ mean=[123.675, 116.28, 103.53],
45
+ std=[58.395, 57.12, 57.375],
46
+ bgr_to_rgb=True,
47
+ pad_size_divisor=32))
config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model = dict(
2
+ type='DBNet',
3
+ backbone=dict(
4
+ type='mmdet.ResNet',
5
+ depth=50,
6
+ num_stages=4,
7
+ out_indices=(0, 1, 2, 3),
8
+ frozen_stages=-1,
9
+ norm_cfg=dict(type='BN', requires_grad=True),
10
+ norm_eval=False,
11
+ style='pytorch',
12
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
13
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
14
+ stage_with_dcn=(False, True, True, True)),
15
+ neck=dict(
16
+ type='FPNC',
17
+ in_channels=[256, 512, 1024, 2048],
18
+ lateral_channels=256,
19
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
20
+ det_head=dict(
21
+ type='PANSegHistHead',
22
+ in_channels=256,
23
+ num_blocks=3,
24
+ num_query=8,
25
+ output_channels=6,
26
+ shallow_channels=128,
27
+ embedding_channels=128, # = shallow channels
28
+ use_dyrelu=True,
29
+ dyrelu_mode='awared',
30
+ with_m2f_mask=True,
31
+ module_loss=dict(type='PANTKSModuleLoss',
32
+ shrink_ratio=(1, 0),
33
+ stretch_ratio=2),
34
+ postprocessor=dict(type='PANPostprocessor',
35
+ text_repr_type='poly',
36
+ min_text_area=200,
37
+ downsample_ratio=1,
38
+ score_threshold=0.6)),
39
+ data_preprocessor=dict(
40
+ type='TextDetDataPreprocessor',
41
+ mean=[123.675, 116.28, 103.53],
42
+ std=[58.395, 57.12, 57.375],
43
+ bgr_to_rgb=True,
44
+ pad_size_divisor=32))
config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model = dict(
2
+ type='DBNet',
3
+ backbone=dict(
4
+ type='mmdet.ResNet',
5
+ depth=50,
6
+ num_stages=4,
7
+ out_indices=(0, 1, 2, 3),
8
+ frozen_stages=-1,
9
+ norm_cfg=dict(type='BN', requires_grad=True),
10
+ norm_eval=False,
11
+ style='pytorch',
12
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
13
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
14
+ stage_with_dcn=(False, True, True, True)),
15
+ neck=dict(
16
+ type='FPNC',
17
+ in_channels=[256, 512, 1024, 2048],
18
+ lateral_channels=256,
19
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
20
+ det_head=dict(
21
+ type='PANSegHistHead',
22
+ in_channels=256,
23
+ num_blocks=3,
24
+ num_query=8,
25
+ output_channels=6,
26
+ shallow_channels=128,
27
+ embedding_channels=128, # = shallow channels
28
+ use_dyrelu=True,
29
+ dyrelu_mode='awared',
30
+ with_m2f_mask=True,
31
+ module_loss=dict(type='PSETKSModuleLoss',
32
+ shrink_ratio=(1, 0.8, 0.6, 0.4, 0.2, 0),
33
+ stretch_ratio=2),
34
+ postprocessor=dict(type='PSEPostprocessor',
35
+ text_repr_type='poly',
36
+ min_text_area=200,
37
+ score_threshold=0.6,
38
+ downsample_ratio=1)),
39
+ data_preprocessor=dict(
40
+ type='TextDetDataPreprocessor',
41
+ mean=[123.675, 116.28, 103.53],
42
+ std=[58.395, 57.12, 57.375],
43
+ bgr_to_rgb=True,
44
+ pad_size_divisor=32))
config/seghist/_base_seghist_resnet50-dcnv2_fpnc.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r = 0. # shrink_ratio
2
+ stretch_ratio = 2. # 1.5
3
+ model = dict(
4
+ type='DBNet',
5
+ backbone=dict(
6
+ type='mmdet.ResNet',
7
+ depth=50,
8
+ num_stages=4,
9
+ out_indices=(0, 1, 2, 3),
10
+ frozen_stages=-1,
11
+ norm_cfg=dict(type='BN', requires_grad=True),
12
+ norm_eval=False,
13
+ style='pytorch',
14
+ dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
15
+ init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'),
16
+ stage_with_dcn=(False, True, True, True)),
17
+ neck=dict(
18
+ type='FPNC',
19
+ in_channels=[256, 512, 1024, 2048],
20
+ lateral_channels=256,
21
+ asf_cfg=dict(attention_type='ScaleChannelSpatial')),
22
+ det_head=dict(
23
+ type='SegHistHead',
24
+ in_channels=256,
25
+ num_blocks=3,
26
+ num_query=8,
27
+ shallow_channels=128,
28
+ embedding_channels=128, # = shallow channels
29
+ use_dyrelu=True,
30
+ dyrelu_mode='awared',
31
+ with_m2f_mask=True,
32
+ with_sigmoid=False,
33
+ module_loss=dict(type='SegHistModuleLoss',
34
+ shrink_ratio=r,
35
+ stretch_ratio=stretch_ratio),
36
+ postprocessor=dict(
37
+ type='IterExpandPostprocessor',
38
+ text_repr_type='poly',
39
+ shrink_ratio=r,
40
+ stretch_ratio=stretch_ratio,
41
+ epsilon_ratio=0.002,
42
+ mask_thr=0.6)),
43
+ data_preprocessor=dict(
44
+ type='TextDetDataPreprocessor',
45
+ mean=[123.675, 116.28, 103.53],
46
+ std=[58.395, 57.12, 57.375],
47
+ bgr_to_rgb=True,
48
+ pad_size_divisor=32))
config/seghist/pipeline/seghist_pipeline_basic.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(
9
+ type='TorchVisionWrapper',
10
+ op='ColorJitter',
11
+ brightness=0.12549019607843137,
12
+ saturation=0.5),
13
+ dict(type='RandomFlip',
14
+ prob=0.5,
15
+ direction=['horizontal', 'vertical']), # both direction
16
+ dict(
17
+ type='RandomRotate',
18
+ max_angle=10 # [-10, 10]
19
+ ),
20
+ dict(
21
+ type='RandomChoiceResize',
22
+ scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800),
23
+ (1333, 832), (1333, 864), (1333, 896)],
24
+ keep_ratio=True,
25
+ clip_object_border=False), # clip the object when outside border
26
+ dict(type='TextDetRandomCrop', target_size=(640, 640)),
27
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
28
+ dict(
29
+ type='PackTextDetInputs',
30
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
31
+ ]
32
+ test_pipeline = [
33
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
34
+ dict(
35
+ type='Resize',
36
+ scale=(1333, 800),
37
+ keep_ratio=True,
38
+ clip_object_border=True),
39
+ dict(
40
+ type='LoadOCRAnnotations',
41
+ with_polygon=True,
42
+ with_bbox=False,
43
+ with_label=True),
44
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
45
+ dict(
46
+ type='PackTextDetInputs',
47
+ meta_keys=('img_path', 'ori_shape',
48
+ 'img_shape', 'scale_factor',
49
+ 'valid_shape', 'instances'))
50
+ ]
config/seghist/pipeline/seghist_pipeline_basic_rotate.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(
9
+ type='TorchVisionWrapper',
10
+ op='ColorJitter',
11
+ brightness=0.12549019607843137,
12
+ saturation=0.5),
13
+ dict(type='RandomFlip',
14
+ prob=0.5,
15
+ direction=['horizontal', 'vertical']), # both direction
16
+ dict(
17
+ type='RandomRotate',
18
+ max_angle=10 # [-10, 10]
19
+ ),
20
+ dict(
21
+ type='RandomChoiceResize',
22
+ scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800),
23
+ (1333, 832), (1333, 864), (1333, 896)],
24
+ keep_ratio=True,
25
+ clip_object_border=False), # clip the object when outside border
26
+ dict(type='TextDetRandomCrop', target_size=(640, 640)),
27
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
28
+ dict(
29
+ type='PackTextDetInputs',
30
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
31
+ ]
32
+ test_pipeline = [
33
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
34
+ dict(
35
+ type='LoadOCRAnnotations',
36
+ with_polygon=True,
37
+ with_bbox=False,
38
+ with_label=True),
39
+ dict(
40
+ type='Resize',
41
+ scale=(1333, 800),
42
+ keep_ratio=True,
43
+ clip_object_border=True),
44
+ dict(type='RandomRotate', max_angle=15),
45
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
46
+ dict(
47
+ type='PackTextDetInputs',
48
+ meta_keys=('img_path', 'ori_shape',
49
+ 'img_shape', 'scale_factor',
50
+ 'valid_shape', 'instances'))
51
+ ]
52
+ model = dict(
53
+ det_head=dict(
54
+ postprocessor=dict(
55
+ rescale_fields=[], # test time: first load annotations then transform
56
+ )
57
+ )
58
+ )
config/seghist/pipeline/seghist_pipeline_color_jitter.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(type='RandomFlip',
9
+ prob=0.5,
10
+ direction=['horizontal', 'vertical']), # both direction
11
+ dict(
12
+ type='RandomRotate',
13
+ max_angle=10 # [-10, 10]
14
+ ),
15
+ dict(
16
+ type='RandomChoiceResize',
17
+ scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800),
18
+ (1333, 832), (1333, 864), (1333, 896)],
19
+ keep_ratio=True,
20
+ clip_object_border=False), # clip the object when outside border
21
+ dict(type='ChannelShuffle', prob=0.2),
22
+ dict(type='GaussianBlur', blur_limit=(3, 7), prob=0.5),
23
+ dict(type='mmdet.PhotoMetricDistortion'),
24
+ dict(type='TextDetRandomCrop', target_size=(640, 640)),
25
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
26
+ dict(
27
+ type='PackTextDetInputs',
28
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
29
+ ]
30
+ test_pipeline = [
31
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
32
+ dict(
33
+ type='Resize',
34
+ scale=(1333, 800),
35
+ keep_ratio=True,
36
+ clip_object_border=True),
37
+ dict(
38
+ type='LoadOCRAnnotations',
39
+ with_polygon=True,
40
+ with_bbox=False,
41
+ with_label=True),
42
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
43
+ dict(
44
+ type='PackTextDetInputs',
45
+ meta_keys=('img_path', 'ori_shape',
46
+ 'img_shape', 'scale_factor',
47
+ 'valid_shape', 'instances'))
48
+ ]
config/seghist/pipeline/seghist_pipeline_large_rotate.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(
9
+ type='TorchVisionWrapper',
10
+ op='ColorJitter',
11
+ brightness=0.12549019607843137,
12
+ saturation=0.5),
13
+ dict(type='RandomFlip',
14
+ prob=0.5,
15
+ direction=['horizontal', 'vertical']), # both direction
16
+ dict(
17
+ type='RandomRotate',
18
+ max_angle=10 # [-10, 10]
19
+ ),
20
+ dict(
21
+ type='MultiScaleResizeShorterSide',
22
+ fixed_longer_side=2000,
23
+ shorter_side_ratio=(0.8, 1.2),
24
+ clip_object_border=True), # clip the object when outside border
25
+ dict(type='RatioAwareCrop', crop_ratio=(0.7, 0.5)),
26
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
27
+ dict(
28
+ type='PackTextDetInputs',
29
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
30
+ ]
31
+ test_pipeline = [
32
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
33
+ dict(
34
+ type='LoadOCRAnnotations',
35
+ with_polygon=True,
36
+ with_bbox=False,
37
+ with_label=True),
38
+ dict(
39
+ type='Resize',
40
+ scale=(1600, 1600),
41
+ keep_ratio=True,
42
+ clip_object_border=False),
43
+ dict(type='RandomRotate', max_angle=15),
44
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
45
+ dict(
46
+ type='PackTextDetInputs',
47
+ meta_keys=('img_path', 'ori_shape',
48
+ 'img_shape', 'scale_factor',
49
+ 'valid_shape', 'instances'))
50
+ ]
51
+ model = dict(
52
+ det_head=dict(
53
+ postprocessor=dict(
54
+ rescale_fields=[], # test time: first load annotations then transform
55
+ )
56
+ )
57
+ )
config/seghist/pipeline/seghist_pipeline_largescale.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_pipeline = [
2
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
3
+ dict(
4
+ type='LoadOCRAnnotations',
5
+ with_bbox=False,
6
+ with_polygon=True,
7
+ with_label=True),
8
+ dict(
9
+ type='TorchVisionWrapper',
10
+ op='ColorJitter',
11
+ brightness=0.12549019607843137,
12
+ saturation=0.5),
13
+ dict(type='RandomFlip',
14
+ prob=0.5,
15
+ direction=['horizontal', 'vertical']), # both direction
16
+ dict(
17
+ type='RandomRotate',
18
+ max_angle=10 # [-10, 10]
19
+ ),
20
+ dict(
21
+ type='MultiScaleResizeShorterSide',
22
+ fixed_longer_side=2000,
23
+ shorter_side_ratio=(0.8, 1.2),
24
+ clip_object_border=True), # clip the object when outside border
25
+ dict(type='RatioAwareCrop', crop_ratio=(0.7, 0.5)),
26
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
27
+ dict(
28
+ type='PackTextDetInputs',
29
+ meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))
30
+ ]
31
+ test_pipeline = [
32
+ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'),
33
+ dict(
34
+ type='Resize',
35
+ scale=(1600, 1600),
36
+ keep_ratio=True,
37
+ clip_object_border=False),
38
+ dict(
39
+ type='LoadOCRAnnotations',
40
+ with_polygon=True,
41
+ with_bbox=False,
42
+ with_label=True),
43
+ dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last!
44
+ dict(
45
+ type='PackTextDetInputs',
46
+ meta_keys=('img_path', 'ori_shape',
47
+ 'img_shape', 'scale_factor',
48
+ 'valid_shape', 'instances'))
49
+ ]
config/seghist/seghist_resnet50-dcnv2_fpnc.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _base_ = [
2
+ '_base_db_seghist_resnet50-dcnv2_fpnc.py',
3
+ './pipeline/seghist_pipeline_basic.py',
4
+ '../_base_/textdet_runtime.py',
5
+ '../_base_/datasets/iacc2022_chdac.py'
6
+ ]
7
+
8
+ # dataset settings
9
+ train_list = _base_.train_list
10
+ test_list = _base_.test_list
11
+ val_list = _base_.val_list
12
+
13
+ train_dataloader = dict(
14
+ batch_size=8,
15
+ num_workers=8,
16
+ persistent_workers=True,
17
+ sampler=dict(type='DefaultSampler', shuffle=True),
18
+ dataset=dict(
19
+ type='ConcatDataset',
20
+ datasets=train_list,
21
+ verify_meta=False,
22
+ pipeline=_base_.train_pipeline))
23
+
24
+ test_dataloader = dict(
25
+ batch_size=1,
26
+ num_workers=1,
27
+ persistent_workers=False,
28
+ sampler=dict(type='DefaultSampler', shuffle=False),
29
+ dataset=dict(
30
+ type='ConcatDataset',
31
+ datasets=test_list,
32
+ verify_meta=False,
33
+ pipeline=_base_.test_pipeline))
34
+
35
+ val_dataloader = dict(
36
+ batch_size=1,
37
+ num_workers=1,
38
+ persistent_workers=False,
39
+ sampler=dict(type='DefaultSampler', shuffle=False),
40
+ dataset=dict(
41
+ type='ConcatDataset',
42
+ datasets=val_list,
43
+ verify_meta=False,
44
+ pipeline=_base_.test_pipeline))
45
+
46
+ auto_scale_lr = dict(base_batch_size=16)
47
+
48
+ test_evaluator = [dict(type='HmeanIOUMetric',
49
+ pred_score_thrs=dict(start=0.6, stop=1.0, step=0.05),
50
+ prefix='Iacc',
51
+ match_iou_thr=0.5)]
52
+ val_evaluator = test_evaluator
53
+
54
+ train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=200, val_interval=5)
55
+ default_hooks = dict(
56
+ checkpoint=dict(type='CheckpointHook',
57
+ interval=5))
58
+
59
+ val_cfg = dict(type='ValLoop')
60
+ test_cfg = dict(type='TestLoop')
61
+
62
+
63
+ param_scheduler = [dict(type='ReduceOnPlateauLR',
64
+ rule='greater',
65
+ monitor='Iacc/recall',
66
+ factor=0.3,
67
+ patience=1,
68
+ threshold=1e-4)] # use arg last_step when resuming optim!'''
69
+ #param_scheduler = dict(
70
+ # type='MultiStepLR', by_epoch=True, milestones=[80, 128], gamma=0.1)
71
+
72
+ custom_imports = dict(
73
+ imports=['seghist'], # not support relative import
74
+ allow_failed_imports=False)
75
+
76
+
77
+ optim_wrapper = dict(
78
+ type='AmpOptimWrapper',
79
+ <<<<<<< HEAD
80
+ optimizer=dict(type='AdamW', lr=1e-4))
81
+
82
+ #resume = False
83
+ #load_from = './work_dirs_icdar2019/pse-seghist/epoch_600.pth'
84
+ =======
85
+ optimizer=dict(type='AdamW', lr=1e-4)) # 1e-3
86
+
87
+ #resume = False
88
+ load_from = './work_dirs_chdac/seghist/final_9712.pth'
89
+ >>>>>>> origin/main
config/seghist/seghist_resnet50-dcnv2_fpnc_large.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _base_ = [
2
+ '_base_seghist_resnet50-dcnv2_fpnc.py',
3
+ './pipeline/seghist_pipeline_largescale.py',
4
+ '../_base_/textdet_runtime.py',
5
+ '../_base_/datasets/iacc2022_chdac.py',
6
+ '../_base_/schedules/schedule_adam_600e.py',
7
+ ]
8
+
9
+ # dataset settings
10
+ train_list = _base_.train_list
11
+ test_list = _base_.test_list
12
+ val_list = _base_.val_list
13
+
14
+ train_dataloader = dict(
15
+ batch_size=8,
16
+ num_workers=4,
17
+ persistent_workers=True,
18
+ sampler=dict(type='DefaultSampler', shuffle=True),
19
+ dataset=dict(
20
+ type='ConcatDataset',
21
+ datasets=train_list,
22
+ pipeline=_base_.train_pipeline))
23
+
24
+ test_dataloader = dict(
25
+ batch_size=4,
26
+ num_workers=4,
27
+ persistent_workers=False,
28
+ sampler=dict(type='DefaultSampler', shuffle=False),
29
+ dataset=dict(
30
+ type='ConcatDataset',
31
+ datasets=test_list,
32
+ pipeline=_base_.test_pipeline))
33
+
34
+ val_dataloader = dict(
35
+ batch_size=4,
36
+ num_workers=4,
37
+ persistent_workers=False,
38
+ sampler=dict(type='DefaultSampler', shuffle=False),
39
+ dataset=dict(
40
+ type='ConcatDataset',
41
+ datasets=val_list,
42
+ pipeline=_base_.test_pipeline))
43
+
44
+ test_dataloader = val_dataloader
45
+
46
+ auto_scale_lr = dict(base_batch_size=16) # 对不同大小的batch_size应用不同的系数,但是设置学习率可以根据base_batch设置
47
+
48
+ val_evaluator = [dict(type='HmeanIOUMetric',
49
+ pred_score_thrs=dict(start=0.6, stop=1.0, step=0.1))]
50
+ test_evaluator = val_evaluator
51
+
52
+ train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=200, val_interval=10)
53
+
54
+ '''
55
+ param_scheduler = dict(
56
+ type='MultiStepLR', by_epoch=True, milestones=[50, 125], gamma=0.1)
57
+ '''
58
+ param_scheduler = [dict(type='LinearLR',
59
+ start_factor=1e-5,
60
+ by_epoch=False,
61
+ begin=0,
62
+ end=125),
63
+ dict(type='ReduceOnPlateauLR',
64
+ rule='greater',
65
+ factor=0.33,
66
+ patience=1,
67
+ threshold=1e-4)] # use arg last_step when resuming optim!
68
+
69
+ custom_imports = dict(
70
+ imports=['seghist'], # not support relative import
71
+ allow_failed_imports=False)
72
+
73
+ optim_wrapper = dict(
74
+ type='OptimWrapper',
75
+ optimizer=dict(type='AdamW', lr=1e-3))
config/seghist/seghist_resnet50-dcnv2_fpnc_toy.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _base_ = [
2
+ '_base_seghist_resnet50-dcnv2_fpnc.py',
3
+ './pipeline/seghist_pipeline_basic.py',
4
+ '../_base_/textdet_runtime.py',
5
+ '../_base_/datasets/iacc2022_chdac_toy.py'
6
+ ]
7
+
8
+ # dataset settings
9
+ train_list = _base_.train_list
10
+ test_list = _base_.test_list
11
+ val_list = _base_.val_list
12
+
13
+ train_dataloader = dict(
14
+ batch_size=8,
15
+ num_workers=4,
16
+ persistent_workers=True,
17
+ sampler=dict(type='DefaultSampler', shuffle=True),
18
+ dataset=dict(
19
+ type='ConcatDataset',
20
+ datasets=train_list,
21
+ pipeline=_base_.train_pipeline))
22
+
23
+ test_dataloader = dict(
24
+ batch_size=4,
25
+ num_workers=4,
26
+ persistent_workers=False,
27
+ sampler=dict(type='DefaultSampler', shuffle=False),
28
+ dataset=dict(
29
+ type='ConcatDataset',
30
+ datasets=test_list,
31
+ pipeline=_base_.test_pipeline))
32
+
33
+ val_dataloader = dict(
34
+ batch_size=4,
35
+ num_workers=4,
36
+ persistent_workers=False,
37
+ sampler=dict(type='DefaultSampler', shuffle=False),
38
+ dataset=dict(
39
+ type='ConcatDataset',
40
+ datasets=val_list,
41
+ pipeline=_base_.test_pipeline))
42
+
43
+ test_dataloader = val_dataloader
44
+
45
+ auto_scale_lr = dict(base_batch_size=16) # 对不同大小的batch_size应用不同的系数,但是设置学习率可以根据base_batch设置
46
+
47
+ val_evaluator = [dict(type='HmeanIOUMetric',
48
+ pred_score_thrs=dict(start=0.6, stop=1.0, step=0.1))]
49
+ test_evaluator = val_evaluator
50
+
51
+ param_scheduler = dict(
52
+ type='MultiStepLR', by_epoch=True, milestones=[50, 125], gamma=0.1)
53
+
54
+ custom_imports = dict(
55
+ imports=['seghist'], # not support relative import
56
+ allow_failed_imports=False)
57
+
58
+ optim_wrapper = dict(
59
+ type='OptimWrapper',
60
+ optimizer=dict(type='AdamW', lr=0.001),
61
+ accumulative_counts=4)
62
+
63
+ train_cfg = dict(type='EpochBasedTrainLoop',
64
+ max_epochs=1)
65
+
66
+ val_cfg = dict(type='ValLoop')
67
+ test_cfg = dict(type='TestLoop')
environment.yml ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: openmmlab
2
+ channels:
3
+ - conda-forge
4
+ - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
5
+ - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
6
+ - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
7
+ dependencies:
8
+ - _libgcc_mutex=0.1=main
9
+ - _openmp_mutex=5.1=1_gnu
10
+ - asttokens=2.2.1=pyhd8ed1ab_0
11
+ - backcall=0.2.0=pyh9f0ad1d_0
12
+ - backports=1.0=pyhd8ed1ab_3
13
+ - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0
14
+ - ca-certificates=2022.12.7=ha878542_0
15
+ - certifi=2022.12.7=pyhd8ed1ab_0
16
+ - debugpy=1.5.1=py38h295c915_0
17
+ - decorator=5.1.1=pyhd8ed1ab_0
18
+ - entrypoints=0.4=pyhd8ed1ab_0
19
+ - executing=1.2.0=pyhd8ed1ab_0
20
+ - ipykernel=6.15.0=pyh210e3f2_0
21
+ - ipython=8.11.0=pyh41d4057_0
22
+ - jedi=0.18.2=pyhd8ed1ab_0
23
+ - jupyter_client=7.0.6=pyhd8ed1ab_0
24
+ - jupyter_core=5.2.0=py38h578d9bd_0
25
+ - ld_impl_linux-64=2.38=h1181459_1
26
+ - libffi=3.4.2=h6a678d5_6
27
+ - libgcc-ng=11.2.0=h1234567_1
28
+ - libgomp=11.2.0=h1234567_1
29
+ - libsodium=1.0.18=h36c2ea0_1
30
+ - libstdcxx-ng=11.2.0=h1234567_1
31
+ - matplotlib-inline=0.1.6=pyhd8ed1ab_0
32
+ - ncurses=6.4=h6a678d5_0
33
+ - nest-asyncio=1.5.6=pyhd8ed1ab_0
34
+ - openssl=1.1.1t=h7f8727e_0
35
+ - packaging=23.0=pyhd8ed1ab_0
36
+ - parso=0.8.3=pyhd8ed1ab_0
37
+ - pexpect=4.8.0=pyh1a96a4e_2
38
+ - pickleshare=0.7.5=py_1003
39
+ - pip=22.3.1=py38h06a4308_0
40
+ - prompt-toolkit=3.0.38=pyha770c72_0
41
+ - prompt_toolkit=3.0.38=hd8ed1ab_0
42
+ - psutil=5.9.0=py38h5eee18b_0
43
+ - ptyprocess=0.7.0=pyhd3deb0d_0
44
+ - pure_eval=0.2.2=pyhd8ed1ab_0
45
+ - pygments=2.14.0=pyhd8ed1ab_0
46
+ - python=3.8.16=h7a1cb2a_2
47
+ - python-dateutil=2.8.2=pyhd8ed1ab_0
48
+ - python_abi=3.8=2_cp38
49
+ - readline=8.2=h5eee18b_0
50
+ - setuptools=65.6.3=py38h06a4308_0
51
+ - six=1.16.0=pyh6c4a22f_0
52
+ - sqlite=3.40.1=h5082296_0
53
+ - stack_data=0.6.2=pyhd8ed1ab_0
54
+ - tk=8.6.12=h1ccaba5_0
55
+ - traitlets=5.9.0=pyhd8ed1ab_0
56
+ - typing-extensions=4.5.0=hd8ed1ab_0
57
+ - typing_extensions=4.5.0=pyha770c72_0
58
+ - wcwidth=0.2.6=pyhd8ed1ab_0
59
+ - wheel=0.38.4=py38h06a4308_0
60
+ - xz=5.2.10=h5eee18b_1
61
+ - zeromq=4.3.4=h9c3ff4c_1
62
+ - zlib=1.2.13=h5eee18b_0
63
+ - pip:
64
+ - absl-py==1.4.0
65
+ - addict==2.4.0
66
+ - albumentations==1.3.1
67
+ - asynctest==0.13.0
68
+ - attrs==22.2.0
69
+ - beautifulsoup4==4.11.2
70
+ - bleach==6.0.0
71
+ - blessed==1.20.0
72
+ - cachetools==5.3.0
73
+ - charset-normalizer==3.0.1
74
+ - click==8.1.3
75
+ - codecov==2.1.12
76
+ - colorama==0.4.6
77
+ - contourpy==1.0.7
78
+ - coverage==7.2.0
79
+ - cycler==0.11.0
80
+ - defusedxml==0.7.1
81
+ - einops==0.8.0
82
+ - exceptiongroup==1.1.0
83
+ - fastjsonschema==2.16.2
84
+ - filelock==3.14.0
85
+ - flake8==6.0.0
86
+ - flask==2.2.5
87
+ - fonttools==4.38.0
88
+ - fsspec==2024.6.0
89
+ - google-auth==2.16.1
90
+ - google-auth-oauthlib==0.4.6
91
+ - gpustat==1.1.1
92
+ - grpcio==1.51.3
93
+ - huggingface-hub==0.23.3
94
+ - idna==3.4
95
+ - imageio==2.25.1
96
+ - imgaug==0.4.0
97
+ - importlib-metadata==6.0.0
98
+ - importlib-resources==5.12.0
99
+ - iniconfig==2.0.0
100
+ - interrogate==1.5.0
101
+ - isort==5.12.0
102
+ - itsdangerous==2.1.2
103
+ - jinja2==3.1.2
104
+ - joblib==1.3.2
105
+ - jsonschema==4.17.3
106
+ - jupyter-client==8.0.3
107
+ - jupyterlab-pygments==0.2.2
108
+ - kiwisolver==1.4.4
109
+ - kwarray==0.6.9
110
+ - lanms-neo==1.0.2
111
+ - levenshtein==0.25.1
112
+ - lmdb==1.4.0
113
+ - lxml==5.1.0
114
+ - markdown==3.4.1
115
+ - markdown-it-py==2.2.0
116
+ - markupsafe==2.1.2
117
+ - mat4py==0.6.0
118
+ - matplotlib==3.7.0
119
+ - mccabe==0.7.0
120
+ - mdurl==0.1.2
121
+ - mistune==2.0.5
122
+ - mmcv==2.0.1
123
+ - mmdet==3.0.0
124
+ - mmengine==0.10.4
125
+ - mmocr==1.0.0rc5
126
+ - model-index==0.1.11
127
+ - modelindex==0.0.2
128
+ - nbclient==0.7.2
129
+ - nbconvert==7.2.9
130
+ - nbformat==5.7.3
131
+ - networkx==3.0
132
+ - numpy==1.24.4
133
+ - nvidia-ml-py==12.535.133
134
+ - oauthlib==3.2.2
135
+ - opencc==1.1.2
136
+ - opencv-python==4.7.0.72
137
+ - openmim==0.3.6
138
+ - ordered-set==4.1.0
139
+ - pandas==1.5.3
140
+ - pandocfilters==1.5.0
141
+ - parameterized==0.8.1
142
+ - pillow==9.4.0
143
+ - pkgutil-resolve-name==1.3.10
144
+ - platformdirs==3.0.0
145
+ - pluggy==1.0.0
146
+ - protobuf==4.22.0
147
+ - py==1.11.0
148
+ - pyasn1==0.4.8
149
+ - pyasn1-modules==0.2.8
150
+ - pyclipper==1.3.0.post4
151
+ - pycocotools==2.0.6
152
+ - pycodestyle==2.10.0
153
+ - pyflakes==3.0.1
154
+ - pyparsing==3.0.9
155
+ - pyrsistent==0.19.3
156
+ - pytest==7.2.1
157
+ - pytest-cov==4.0.0
158
+ - pytest-runner==6.0.0
159
+ - pytz==2022.7.1
160
+ - pywavelets==1.4.1
161
+ - pyyaml==6.0
162
+ - pyzmq==25.0.0
163
+ - qudida==0.0.4
164
+ - rapidfuzz==3.9.0
165
+ - requests==2.28.2
166
+ - requests-oauthlib==1.3.1
167
+ - rich==13.3.1
168
+ - rsa==4.9
169
+ - safetensors==0.4.3
170
+ - scikit-image==0.19.3
171
+ - scikit-learn==1.3.2
172
+ - scipy==1.10.1
173
+ - seaborn==0.13.2
174
+ - shapely==2.0.2
175
+ - soupsieve==2.4
176
+ - tabulate==0.9.0
177
+ - tensorboard==2.12.0
178
+ - tensorboard-data-server==0.7.0
179
+ - tensorboard-plugin-wit==1.8.1
180
+ - termcolor==2.2.0
181
+ - terminaltables==3.1.10
182
+ - threadpoolctl==3.2.0
183
+ - tifffile==2023.2.3
184
+ - tinycss2==1.2.1
185
+ - toml==0.10.2
186
+ - tomli==2.0.1
187
+ - torch==1.12.1+cu102
188
+ - torchaudio==0.12.1+cu102
189
+ - torchvision==0.13.1+cu102
190
+ - tornado==6.2
191
+ - tqdm==4.65.0
192
+ - ubelt==1.2.3
193
+ - urllib3==1.26.14
194
+ - webencodings==0.5.1
195
+ - werkzeug==2.2.2
196
+ - xdoctest==1.1.1
197
+ - yapf==0.32.0
198
+ - zipp==3.14.0
readme.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ see https://github.com/LumionHXJ/SegHist
samples/gt1.png ADDED

Git LFS Details

  • SHA256: a72383f5a996098df47b47bd4e9e4987e78cd6a4dcac946444301c00189a39fc
  • Pointer size: 132 Bytes
  • Size of remote file: 2.57 MB
samples/gt2.png ADDED

Git LFS Details

  • SHA256: b81624e7aeed4948efbe47a2e701ea034a805c78e825557a2f3c7eb316e08a6a
  • Pointer size: 132 Bytes
  • Size of remote file: 2.49 MB
samples/pred1.png ADDED

Git LFS Details

  • SHA256: 8e2cc2ae1832dbb4a335c8d72b6109773d9039274557fc55a63ce400282b43bf
  • Pointer size: 132 Bytes
  • Size of remote file: 2.57 MB
samples/pred2.png ADDED

Git LFS Details

  • SHA256: 070525d284425af3c2ec6f102c3b0ba063daf69632255e4a3dfa7542f5a6b9e0
  • Pointer size: 132 Bytes
  • Size of remote file: 2.5 MB
seghist/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .datasets import * # NOQA
2
+ from .model import * # NOQA
seghist/datasets/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .transforms import *
seghist/datasets/transforms/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .textdet_transforms import MultiScaleResizeShorterSide, RatioAwareCrop, PadDivisor
2
+ from .colorspace import GaussianBlur, ChannelShuffle
3
+
4
+ __all__ = ['MultiScaleResizeShorterSide', 'RatioAwareCrop', 'PadDivisor',
5
+ 'GaussianBlur', 'ChannelShuffle']
seghist/datasets/transforms/colorspace.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mmocr.registry import TRANSFORMS
2
+ import numpy as np
3
+ import cv2
4
+ from mmdet.datasets.transforms import ColorTransform
5
+
6
+ @TRANSFORMS.register_module()
7
+ class ChannelShuffle(ColorTransform):
8
+ def _transform_img(self, results: dict, mag: float) -> None:
9
+ """Invert the image."""
10
+ img = results['img']
11
+ channels = img.shape[-1]
12
+ shuffle_result = np.arange(0, channels)
13
+ np.random.shuffle(shuffle_result)
14
+ results['img'] = results['img'][..., shuffle_result]
15
+
16
+ @TRANSFORMS.register_module()
17
+ class GaussianBlur(ColorTransform):
18
+ def __init__(self,
19
+ blur_limit = (3, 7),
20
+ sigma = 0,
21
+ **kwargs):
22
+ self.blur_limit = blur_limit
23
+ self.sigma = sigma
24
+ super().__init__(**kwargs)
25
+
26
+ def _transform_img(self, results: dict, mag: float) -> None:
27
+ kernel_size = np.random.choice(np.arange(self.blur_limit[0],
28
+ self.blur_limit[1] + 2,
29
+ 2))
30
+ results['img'] = cv2.GaussianBlur(results['img'], (kernel_size, kernel_size), self.sigma)
seghist/datasets/transforms/textdet_transforms.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional, Tuple, Union
2
+ from mmocr.registry import TRANSFORMS
3
+ from mmocr.datasets.transforms import Resize, TextDetRandomCrop
4
+ import numpy as np
5
+ from mmcv.transforms.processing import Pad
6
+
7
+ @TRANSFORMS.register_module()
8
+ class MultiScaleResizeShorterSide(Resize):
9
+ """Resize historical image by fixing longer side
10
+ and using multi-scale strategy to shorter side.
11
+
12
+ Required Keys:
13
+
14
+ - img
15
+ - img_shape
16
+ - gt_bboxes
17
+ - gt_polygons
18
+
19
+
20
+ Modified Keys:
21
+
22
+ - img
23
+ - img_shape
24
+ - gt_bboxes
25
+ - gt_polygons
26
+
27
+ Added Keys:
28
+
29
+ - scale
30
+ - scale_factor
31
+ - keep_ratio
32
+
33
+ Args:
34
+ fixed_longer_side(int): length of longer side (no matter
35
+ it's height or width)
36
+ shorter_side_ratio(Tuple[float, float]): range of multi-scale ratio
37
+ on resizing the shorter side, thus we don't keep the aspect ratio.
38
+ clip_object_border (bool): Whether to clip the objects outside the
39
+ border of the image. Defaults to True.
40
+
41
+ """
42
+ def __init__(self,
43
+ fixed_longer_side: int = 2000,
44
+ shorter_side_ratio: Tuple[float, float] = (0.8, 1.2),
45
+ clip_object_border: bool = True) -> None:
46
+ super().__init__(scale_factor=1.,
47
+ keep_ratio=False,
48
+ clip_object_border=clip_object_border)
49
+ self.fixed_longer_side = fixed_longer_side
50
+ self.shorter_side_ratio = shorter_side_ratio
51
+
52
+ @staticmethod
53
+ def _random_sample_ratio(ratio_range: Tuple[float, float]) -> float:
54
+ """Private function to randomly sample ratio for shorter side
55
+ from a tuple.
56
+
57
+ A ratio will be randomly sampled from the range specified by
58
+ ``ratio_range``.
59
+
60
+ Args:
61
+ ratio_range (tuple[float]): The minimum and maximum ratio to scale
62
+ the ``scale``.
63
+
64
+ Returns:
65
+ float: The targeted ratio of the shorter side to be resized.
66
+ """
67
+
68
+ min_ratio, max_ratio = ratio_range
69
+ assert min_ratio <= max_ratio
70
+ ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio
71
+ return ratio
72
+
73
+ def transform(self, results: dict) -> dict:
74
+ """Transform function to resize images, bounding boxes, semantic
75
+ segmentation map and keypoints.
76
+
77
+ NOTE: Scale in mmcv is in (w, h)-style.
78
+
79
+ Args:
80
+ results (dict): Result dict from loading pipeline.
81
+ Returns:
82
+ dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map',
83
+ 'gt_keypoints', 'scale', 'scale_factor', 'img_shape',
84
+ and 'keep_ratio' keys are updated in result dict.
85
+ """
86
+ h, w = results['img'].shape[:2]
87
+ if h > w:
88
+ scale_factor = self.fixed_longer_side / h
89
+ scale_factor *= MultiScaleResizeShorterSide._random_sample_ratio(self.shorter_side_ratio)
90
+ results['scale'] = (int(w * scale_factor), self.fixed_longer_side) # wh-style
91
+ else:
92
+ scale_factor = self.fixed_longer_side / w
93
+ scale_factor *= MultiScaleResizeShorterSide._random_sample_ratio(self.shorter_side_ratio)
94
+ results['scale'] = (self.fixed_longer_side, int(h * scale_factor))
95
+
96
+ self._resize_img(results)
97
+ self._resize_bboxes(results)
98
+ self._resize_seg(results)
99
+ self._resize_keypoints(results)
100
+ self._resize_polygons(results)
101
+ return results
102
+
103
+ def __repr__(self):
104
+ repr_str = self.__class__.__name__
105
+ repr_str += f'(fixed_longer_side={self.fixed_longer_side}, '
106
+ repr_str += f'shorter_side_ratio={self.shorter_side_ratio}, '
107
+ repr_str += f'clip_object_border={self.clip_object_border}), '
108
+ return repr_str
109
+
110
+
111
+ @TRANSFORMS.register_module()
112
+ class RatioAwareCrop(TextDetRandomCrop):
113
+ """Due to many vertical text lines in historical document,
114
+ set different different crop ratio for height and width.
115
+
116
+ Targets size will be computed dynamically.
117
+
118
+ NOTE: crop ratio in hw-style but target_size should in wh-style
119
+
120
+ Required Keys:
121
+
122
+ - img
123
+ - gt_polygons
124
+ - gt_bboxes
125
+ - gt_bboxes_labels
126
+ - gt_ignored
127
+
128
+ Modified Keys:
129
+
130
+ - img
131
+ - img_shape
132
+ - gt_polygons
133
+ - gt_bboxes
134
+ - gt_bboxes_labels
135
+ - gt_ignored
136
+
137
+ Args:
138
+ crop_ratio (Tuple[float, float] or float): ratio for height and width.
139
+ i.e. crop_ratio is in hw-style
140
+ positive_sample_ratio (float): The probability of sampling regions
141
+ that go through text regions. Defaults to 5. / 8.
142
+ """
143
+ def __init__(self,
144
+ crop_ratio: Tuple[float, float] or float = (0.7, 0.5), # h, w
145
+ positive_sample_ratio: float = 5.0 / 8.0) -> None:
146
+ super().__init__(target_size=None,
147
+ positive_sample_ratio=positive_sample_ratio)
148
+ if isinstance(crop_ratio, float):
149
+ self.crop_ratio = (crop_ratio, crop_ratio)
150
+ else:
151
+ self.crop_ratio = crop_ratio
152
+
153
+
154
+ def transform(self, results: Dict) -> Dict:
155
+ self.target_size = (int(results['img'].shape[0] * self.crop_ratio[0]),
156
+ int(results['img'].shape[1] * self.crop_ratio[1]))[::-1]
157
+ return super().transform(results)
158
+
159
+
160
+ @TRANSFORMS.register_module()
161
+ class PadDivisor(Pad):
162
+ def transform(self, results: dict) -> dict:
163
+ results['valid_shape'] = results['img_shape']
164
+ return super().transform(results)
seghist/model/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .heads.seghist_heads import DBSegHistHead, PANSegHistHead, SegHistHead
2
+ from .postprocessor.iedp import IterExpandPostprocessor
3
+ from .module_loss.tks import SegHistModuleLoss, TKSModuleLoss
4
+ from .module_loss.db_tks import DBTKSModuleLoss
5
+ from .module_loss.pan_tks import PANTKSModuleLoss
6
+ from .module_loss.pse_tks import PSETKSModuleLoss
7
+
8
+ __all__ = ['SegHistModuleLoss', 'DBSegHistHead', 'IterExpandPostprocessor',
9
+ 'DBTKSModuleLoss', 'PANTKSModuleLoss', 'PSETKSModuleLoss',
10
+ 'PANSegHistHead', 'SegHistHead', 'TKSModuleLoss']
seghist/model/heads/seghist_heads.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch import Tensor
6
+
7
+ from mmcv.cnn import ConvModule
8
+ from mmengine.model import BaseModule
9
+ from mmdet.models.utils import multi_apply
10
+ from mmocr.models.textdet.heads import BaseTextDetHead, DBHead
11
+ from mmocr.registry import MODELS
12
+ from mmocr.structures import TextDetDataSample
13
+
14
+ from seghist.model.layer.layout_enhanced_block import LayoutEnhancedBlock
15
+
16
+ @MODELS.register_module()
17
+ class SegHistHead(BaseModule):
18
+ def __init__(self,
19
+ in_channels: int,
20
+ num_blocks: int,
21
+ shallow_channels: int,
22
+ embedding_channels: int,
23
+ output_channels: int = 1,
24
+ num_query: int = 6,
25
+ bridge_heads: int = 4,
26
+ former_heads: int = 8,
27
+ with_bias: bool = True,
28
+ with_sigmoid: bool = True,
29
+ use_dyrelu: bool = True,
30
+ dyrelu_mode: str = 'shared',
31
+ init_cfg: Optional[Union[Dict, List[Dict]]] = [
32
+ dict(type='Kaiming', layer='Conv'),
33
+ dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4)
34
+ ]):
35
+ super().__init__(init_cfg)
36
+ self.conv1 = ConvModule(in_channels, shallow_channels, 3,
37
+ padding=1,
38
+ bias=with_bias,
39
+ norm_cfg=dict(type='BN'))
40
+ bottleneck_channels = shallow_channels // 4 # 128 / 4 = 32
41
+ bottleneck_groups = bottleneck_channels // 4 # 32 / 4 = 8
42
+ if num_blocks == 0:
43
+ self.lem = None
44
+ else:
45
+ self.lem = nn.Sequential(*[LayoutEnhancedBlock(in_channels=shallow_channels,
46
+ bottleneck_channels=bottleneck_channels,
47
+ bottleneck_group=bottleneck_groups,
48
+ embedding_channels=embedding_channels,
49
+ bridge_heads=bridge_heads,
50
+ former_heads=former_heads,
51
+ use_dyrelu=use_dyrelu,
52
+ dyrelu_mode=dyrelu_mode,
53
+ with_bias=with_bias
54
+ ) for _ in range(num_blocks)])
55
+ self.query = nn.Parameter(torch.randn(num_query, embedding_channels))
56
+
57
+ self.with_sigmoid = with_sigmoid
58
+ self.sigmoid = nn.Sigmoid()
59
+
60
+ self.upconv = nn.Sequential(
61
+ nn.ConvTranspose2d(shallow_channels, shallow_channels // 4, 2, 2),
62
+ nn.BatchNorm2d(shallow_channels // 4),
63
+ nn.ReLU(),
64
+ nn.ConvTranspose2d(shallow_channels // 4, output_channels, 2, 2)
65
+ )
66
+
67
+ self.num_query= num_query
68
+ self.embedding_channels = embedding_channels
69
+
70
+ def forward(self,
71
+ img: Tensor,
72
+ data_samples: Optional[List[TextDetDataSample]],
73
+ mode: str = 'predict') -> Tuple[Tensor, Tensor, Tensor]:
74
+ # N, H, W
75
+ prob_logits = self.forward_pass(img).squeeze(1)
76
+ prob_map = self.sigmoid(prob_logits)
77
+ if mode == 'predict':
78
+ return prob_map
79
+ return prob_logits
80
+
81
+ def forward_pass(self, x, mask=None):
82
+ bs = x.size()[0]
83
+ x = self.conv1(x)
84
+ if self.lem is not None:
85
+ x, _, _ = self.lem((x,
86
+ self.query.expand(bs, self.num_query, self.embedding_channels),
87
+ mask))
88
+ x = self.upconv(x)
89
+ if self.with_sigmoid:
90
+ x = self.sigmoid(x)
91
+ return x # return prob map
92
+
93
+ @MODELS.register_module()
94
+ class DBSegHistHead(DBHead):
95
+ def __init__(self,
96
+ in_channels: int,
97
+ num_blocks: int,
98
+ shallow_channels: int,
99
+ output_channels: int = 1,
100
+ num_query: int = 8,
101
+ embedding_channels: int = 128,
102
+ bridge_heads: int = 4,
103
+ former_heads: int = 8,
104
+ use_dyrelu: bool = True,
105
+ dyrelu_mode: str = 'awared',
106
+ with_bias: bool = True,
107
+ with_m2f_mask: bool = True,
108
+ module_loss: Dict = None,
109
+ postprocessor: Dict = None,
110
+ init_cfg: Optional[Union[Dict, List[Dict]]] = [
111
+ dict(type='Kaiming', layer='Conv'),
112
+ dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4)
113
+ ]
114
+ ) -> None:
115
+ BaseTextDetHead.__init__(self,
116
+ module_loss=module_loss,
117
+ postprocessor=postprocessor,
118
+ init_cfg=init_cfg)
119
+
120
+ # binarization(logit in losses)
121
+ self.binarize = SegHistHead(in_channels=in_channels,
122
+ num_blocks=num_blocks,
123
+ shallow_channels=shallow_channels,
124
+ output_channels=output_channels,
125
+ num_query=num_query,
126
+ embedding_channels=embedding_channels,
127
+ bridge_heads=bridge_heads,
128
+ former_heads=former_heads,
129
+ with_bias=with_bias,
130
+ use_dyrelu=use_dyrelu,
131
+ dyrelu_mode=dyrelu_mode,
132
+ with_sigmoid=False,
133
+ init_cfg=init_cfg)
134
+ self.sigmoid = nn.Sigmoid()
135
+
136
+ # threshold: no separation in threshold
137
+ self.threshold = SegHistHead(in_channels=in_channels,
138
+ num_blocks=num_blocks,
139
+ shallow_channels=shallow_channels,
140
+ output_channels=output_channels,
141
+ num_query=num_query,
142
+ embedding_channels=embedding_channels,
143
+ bridge_heads=bridge_heads,
144
+ former_heads=former_heads,
145
+ with_bias=with_bias,
146
+ use_dyrelu=use_dyrelu,
147
+ dyrelu_mode=dyrelu_mode,
148
+ with_sigmoid=True,
149
+ init_cfg=init_cfg)
150
+
151
+ self.with_m2f_mask = with_m2f_mask
152
+
153
+ def generate_masks(self, data_samples: List[TextDetDataSample]):
154
+ '''Generate mask for M2F(mobile2former), mask = 0 means masking a place.
155
+ '''
156
+ masks_h, masks_w = multi_apply(self._get_mask_single, data_samples)
157
+ masks_h = torch.cat(masks_h, dim=0) # N, H
158
+ masks_w = torch.cat(masks_w, dim=0) # N, W
159
+ return torch.cat([masks_h, masks_w], dim=1) # N, H+W
160
+
161
+ def _get_mask_single(self, data_sample: TextDetDataSample):
162
+ mask_h = torch.ones(data_sample.batch_input_shape[0] // 4)
163
+ mask_w = torch.ones(data_sample.batch_input_shape[1] // 4) # H, W
164
+ mask_h[data_sample.valid_shape[0] // 4:] = 0
165
+ mask_w[data_sample.valid_shape[1] // 4:] = 0
166
+ return mask_h.unsqueeze(0), mask_w.unsqueeze(0)
167
+
168
+ def forward(self,
169
+ img: Tensor,
170
+ data_samples: Optional[List[TextDetDataSample]],
171
+ mode: str = 'predict') -> Tuple[Tensor, Tensor, Tensor]:
172
+ """
173
+ Args:
174
+ img (Tensor): Shape :math:`(N, C, H, W)`.
175
+ data_samples (list[TextDetDataSample], optional): A list of data
176
+ samples. Defaults to None.
177
+ mode (str): Forward mode. It affects the return values. Options are
178
+ "loss", "predict" and "both". Defaults to "predict".
179
+
180
+ - ``loss``: Run the full network and return the prob
181
+ logits, threshold map and binary map.
182
+ - ``predict``: Run the binarzation part and return the prob
183
+ map only.
184
+ - ``both``: Run the full network and return prob logits,
185
+ threshold map, binary map and prob map.
186
+
187
+ Returns:
188
+ Tensor or tuple(Tensor): Its type depends on ``mode``, read its
189
+ docstring for details. Each has the shape of
190
+ :math:`(N, 4H, 4W)`.
191
+ """
192
+ if self.with_m2f_mask:
193
+ masks = self.generate_masks(data_samples)
194
+ masks = masks.to(img.device)
195
+ else:
196
+ masks = None
197
+
198
+ # N, H, W
199
+ prob_logits = self.binarize.forward_pass(img, mask=masks).squeeze(1)
200
+ prob_map = self.sigmoid(prob_logits)
201
+ if mode == 'predict':
202
+ return prob_map
203
+ thr_map = self.threshold.forward_pass(img, mask=masks).squeeze(1)
204
+ binary_map = self._diff_binarize(prob_map, thr_map, k=50).squeeze(1)
205
+ if mode == 'loss':
206
+ return prob_logits, thr_map, binary_map
207
+ return prob_logits, thr_map, binary_map, prob_map
208
+
209
+
210
+ @MODELS.register_module()
211
+ class PANSegHistHead(BaseTextDetHead):
212
+ def __init__(self,
213
+ in_channels: int,
214
+ num_blocks: int,
215
+ shallow_channels: int,
216
+ output_channels: int = 1,
217
+ num_query: int = 8,
218
+ embedding_channels: int = 128,
219
+ bridge_heads: int = 4,
220
+ former_heads: int = 8,
221
+ use_dyrelu: bool = True,
222
+ dyrelu_mode: str = 'shared',
223
+ with_bias: bool = True,
224
+ with_m2f_mask: bool = True,
225
+ module_loss: Dict = None,
226
+ postprocessor: Dict = None,
227
+ init_cfg: Optional[Union[Dict, List[Dict]]] = [
228
+ dict(type='Kaiming', layer='Conv'),
229
+ dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4)
230
+ ]
231
+ ) -> None:
232
+ super().__init__(module_loss=module_loss,
233
+ postprocessor=postprocessor,
234
+ init_cfg=init_cfg)
235
+
236
+ # binarization(logit in losses)
237
+ self.pred = SegHistHead(in_channels=in_channels,
238
+ num_blocks=num_blocks,
239
+ shallow_channels=shallow_channels,
240
+ output_channels=output_channels,
241
+ num_query=num_query,
242
+ embedding_channels=embedding_channels,
243
+ bridge_heads=bridge_heads,
244
+ former_heads=former_heads,
245
+ with_bias=with_bias,
246
+ use_dyrelu=use_dyrelu,
247
+ dyrelu_mode=dyrelu_mode,
248
+ with_sigmoid=False,
249
+ init_cfg=init_cfg)
250
+
251
+ self.with_m2f_mask = with_m2f_mask
252
+
253
+ def generate_masks(self, data_samples: List[TextDetDataSample]):
254
+ '''Generate mask for M2F(mobile2former), mask = 0 means masking a place.
255
+ '''
256
+ masks_h, masks_w = multi_apply(self._get_mask_single, data_samples)
257
+ masks_h = torch.cat(masks_h, dim=0) # N, H
258
+ masks_w = torch.cat(masks_w, dim=0) # N, W
259
+ return torch.cat([masks_h, masks_w], dim=1) # N, H+W
260
+
261
+ def _get_mask_single(self, data_sample: TextDetDataSample):
262
+ mask_h = torch.ones(data_sample.batch_input_shape[0] // 4)
263
+ mask_w = torch.ones(data_sample.batch_input_shape[1] // 4) # H, W
264
+ mask_h[data_sample.valid_shape[0] // 4:] = 0
265
+ mask_w[data_sample.valid_shape[1] // 4:] = 0
266
+ return mask_h.unsqueeze(0), mask_w.unsqueeze(0)
267
+
268
+ def forward(self,
269
+ img: Tensor,
270
+ data_samples: Optional[List[TextDetDataSample]]
271
+ ) -> Tuple[Tensor, Tensor, Tensor]:
272
+ if self.with_m2f_mask:
273
+ masks = self.generate_masks(data_samples)
274
+ masks = masks.to(img.device)
275
+ else:
276
+ masks = None
277
+
278
+ # N, H, W
279
+ outputs = self.pred.forward_pass(img, mask=masks)
280
+ return outputs
seghist/model/layer/dyrelu.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor, nn
3
+
4
+ class DyReLU(nn.Module):
5
+ """Modified from PaddleViT.
6
+
7
+ Params Info:
8
+ in_channels: input feature map channels
9
+ embed_dims: input token embed_dims
10
+ k: the number of parameters is in Dynamic ReLU
11
+ coefs: the init value of coefficient parameters
12
+ consts: the init value of constant parameters
13
+ reduce: the mlp hidden scale,
14
+ means 1/reduce = mlp_ratio
15
+ """
16
+ def __init__(self,
17
+ in_channels,
18
+ embed_dims,
19
+ k=2, # a_1, a_2 coef, b_1, b_2 bias
20
+ coefs=[1.0, 0.5], # coef init value
21
+ consts=[1.0, 0.0], # const init value
22
+ reduce=4,
23
+ dropout=0.1,
24
+ mode='shared'):
25
+ super().__init__()
26
+ assert mode in ['shared', 'awared']
27
+ self.mode = mode
28
+
29
+ self.embed_dims = embed_dims
30
+ self.in_channels = in_channels
31
+ self.k = k
32
+
33
+ self.mid_channels = 2 * k * in_channels
34
+
35
+ # 4 values
36
+ # a_k = alpha_k + coef_k*x, 2
37
+ # b_k = belta_k + coef_k*x, 2
38
+ self.coef = nn.Parameter(torch.tensor([coefs[0]]*k + [coefs[1]]*k))
39
+ self.coef.requires_grad = False
40
+ self.const = nn.Parameter(torch.tensor([consts[0]] + [consts[1]]*(2*k-1)))
41
+ self.const.requires_grad = False
42
+
43
+ self.project = nn.Sequential(
44
+ nn.Linear(embed_dims, int(embed_dims/reduce)),
45
+ nn.GELU(),
46
+ nn.Dropout(dropout),
47
+ nn.Linear(int(embed_dims/reduce), self.mid_channels),
48
+ nn.GELU(),
49
+ nn.Dropout(dropout),
50
+ nn.LayerNorm(self.mid_channels)
51
+ )
52
+
53
+ def forward(self,
54
+ feature_map:Tensor,
55
+ tokens: Tensor,
56
+ attn_map: Tensor):
57
+ '''
58
+ Args:
59
+ attn_score(Tensor): attn map of mobile2former before softmax operation,
60
+ reusing for saving computation, with shape: (B, heads, H*W, M).
61
+ '''
62
+ B, M, D = tokens.size()
63
+ B, C, H, W = feature_map.size()
64
+ if self.mode == 'shared':
65
+ # shared mode only pick out first token
66
+ dy_params = self.project(tokens[:, 0]) # B, 2kC
67
+ dy_params = dy_params.view(B, self.in_channels, 2*self.k) # B, C, 2*k
68
+ elif self.mode == 'awared':
69
+ # part 2: deal with decoupled attention map, keeping prob. attributes
70
+ attn_map = torch.mean(attn_map, dim=1) # B, HW, M
71
+ attn_map = attn_map.view(B, H, W, M)
72
+
73
+ # part 3: projecting tokens
74
+ dy_params = self.project(tokens).unsqueeze(1) # B, 1, M, 2kC
75
+
76
+ # part 4: compute dynamic parameters for spatial pixel
77
+ dy_params = torch.matmul(attn_map, dy_params).view(B, H, W, self.in_channels, 2*self.k) # B, H, W, C, 2k
78
+ dy_params = dy_params.permute(1, 2, 0, 3, 4).contiguous() # H, W, B, C, 2k
79
+
80
+ dy_init_params = dy_params * self.coef + self.const
81
+ f = feature_map.permute(2, 3, 0, 1).contiguous().unsqueeze(-1) # H, W, B, C, 1
82
+
83
+ # output shape: H, W, B, C, k
84
+ output = f * dy_init_params[..., :self.k] + dy_init_params[..., self.k:]
85
+ output = torch.max(output, dim=-1)[0] # H, W, B, C(fetch out max values)
86
+ output = output.permute(2, 3, 0, 1).contiguous() # B, C, H, W
87
+
88
+ return output
seghist/model/layer/layout_enhanced_block.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, List, Tuple
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+
6
+ from mmcv.cnn import ConvModule
7
+ from mmengine.model import BaseModule
8
+ from mmocr.models.common.layers import TFEncoderLayer
9
+ from mmocr.models.common.modules import ScaledDotProductAttention
10
+
11
+ from seghist.model.layer.dyrelu import DyReLU
12
+
13
+
14
+ class Local(nn.Module):
15
+ def __init__(self,
16
+ in_channels,
17
+ embedding_channels,
18
+ bottleneck_channels,
19
+ bottleneck_group,
20
+ n_heads,
21
+ use_dyrelu=True,
22
+ dropout=0.1,
23
+ dyrelu_mode='awared',
24
+ with_bias=True):
25
+ super().__init__()
26
+ self.bottleneck_channels = bottleneck_channels
27
+ self.n_heads = n_heads
28
+
29
+ self.pointwise_conv = nn.Conv2d(in_channels,
30
+ bottleneck_channels,
31
+ kernel_size=1)
32
+ self.group_conv = nn.Conv2d(bottleneck_channels,
33
+ bottleneck_channels,
34
+ kernel_size=7,
35
+ padding=3,
36
+ groups=bottleneck_group)
37
+
38
+ self.pointwise_norm = nn.BatchNorm2d(bottleneck_channels)
39
+ self.group_norm = nn.BatchNorm2d(bottleneck_channels)
40
+
41
+ self.linear_k = nn.Linear(embedding_channels, bottleneck_channels, bias=with_bias)
42
+ self.linear_v = nn.Linear(embedding_channels, bottleneck_channels, bias=with_bias)
43
+ self.pre_attn = ScaledDotProductAttention((self.bottleneck_channels / n_heads)**0.5, dropout)
44
+
45
+ self.use_dyrelu = use_dyrelu
46
+ if use_dyrelu:
47
+ self.act1 = DyReLU(bottleneck_channels,
48
+ embedding_channels,
49
+ mode=dyrelu_mode)
50
+ self.act2 = DyReLU(bottleneck_channels,
51
+ embedding_channels,
52
+ mode=dyrelu_mode)
53
+ else:
54
+ self.act1 = nn.ReLU()
55
+ self.act2 = nn.ReLU()
56
+
57
+ def forward(self, x, z, mask=None):
58
+ """x: N, C, H, W
59
+ z: N, M, d
60
+ """
61
+ x = self.pointwise_conv(x)
62
+ x = self.pointwise_norm(x)
63
+
64
+ # compute attention map for multiple uses!
65
+ bs, num_queries, _ = z.size()
66
+ z_k = self.linear_k(z).view(bs, num_queries,
67
+ self.n_heads,
68
+ self.bottleneck_channels // self.n_heads).transpose(1, 2).contiguous()
69
+ z_v = self.linear_v(z).view(bs, num_queries,
70
+ self.n_heads,
71
+ self.bottleneck_channels // self.n_heads).transpose(1, 2).contiguous()
72
+ x_q = x.view(bs, self.n_heads,
73
+ self.bottleneck_channels//self.n_heads, -1).transpose(2, 3).contiguous() # N, h, HW, C_b/h
74
+ attn_out, attn_map = self.pre_attn(x_q, z_k, z_v, mask)
75
+
76
+ if self.use_dyrelu:
77
+ x = self.act1(x, z, attn_map)
78
+ else:
79
+ x = self.act1(x)
80
+
81
+ x = self.group_conv(x)
82
+ x = self.group_norm(x)
83
+ if self.use_dyrelu:
84
+ x = self.act2(x, z, attn_map)
85
+ else:
86
+ x = self.act2(x)
87
+
88
+ return x, attn_out # N, h, HW, C//h
89
+
90
+
91
+ class Local2Layout(nn.Module):
92
+ def __init__(self,
93
+ n_heads,
94
+ in_channels,
95
+ embedding_channels,
96
+ dropout=0.1,
97
+ with_bias=True) -> None:
98
+ super().__init__()
99
+ assert in_channels % n_heads == 0, 'n_heads must divide in_channels'
100
+ assert in_channels == embedding_channels, \
101
+ 'input channels should be same as embed channels for simplicity'
102
+ self.n_heads = n_heads
103
+ self.in_channels = in_channels
104
+ self.embedding_channels = embedding_channels
105
+
106
+ self.norm1 = nn.LayerNorm(embedding_channels)
107
+ self.norm2 = nn.LayerNorm(in_channels)
108
+
109
+ self.linear_q = nn.Linear(self.embedding_channels, self.in_channels, bias=with_bias)
110
+ self.ffn = nn.Sequential(
111
+ nn.Linear(self.in_channels, self.in_channels // 2, bias=with_bias),
112
+ nn.GELU(),
113
+ nn.Linear(self.in_channels // 2, self.embedding_channels, bias=with_bias),
114
+ nn.Dropout(dropout)
115
+ )
116
+
117
+ self.attention = ScaledDotProductAttention((self.in_channels / n_heads)**0.5, dropout)
118
+
119
+ def forward(self, x: Tensor, z: Tensor, mask=None):
120
+ '''
121
+ x: N, H+W, C
122
+ z: N, M, d
123
+ M: N, H+W
124
+ '''
125
+ bs, length, _ = x.shape
126
+ num_queries = z.shape[1]
127
+ residue = z
128
+
129
+ # part 1: pre norm
130
+ z = self.norm1(z)
131
+
132
+ # part 2: linear z & shape to bs, heads, H/W, C/heads
133
+ z: Tensor = self.linear_q(z) # N, M, C
134
+ z = z.view(bs, num_queries, self.n_heads,
135
+ self.in_channels // self.n_heads).transpose(1, 2).contiguous()
136
+ x = x.view(bs, length, self.n_heads,
137
+ self.in_channels // self.n_heads).transpose(1, 2).contiguous()
138
+
139
+ # part 3: attend mask(N, 1(h), 1(M), H+W)
140
+ if mask is not None:
141
+ if mask.dim() == 3:
142
+ mask = mask.unsqueeze(1)
143
+ elif mask.dim() == 2:
144
+ mask = mask.unsqueeze(1).unsqueeze(1)
145
+
146
+ # part 4: attention
147
+ attn_out, _ = self.attention(z, x, x, mask) # N, h, M, C/h
148
+ attn_out = attn_out.transpose(1, 2).contiguous().view(bs, num_queries, -1) # N, M, C
149
+ residue = residue + attn_out # N, M, C
150
+
151
+ # part 5: projection(output = MHA's output)
152
+ z = self.norm2(residue)
153
+ z = self.ffn(z) # N, M, d
154
+
155
+ # part 6: residue link
156
+ z = z + residue
157
+
158
+ return z
159
+
160
+
161
+ class Layout2Local(nn.Module):
162
+ def __init__(self,
163
+ n_heads,
164
+ in_channels,
165
+ embedding_channels,
166
+ dropout=0.1,
167
+ with_bias=True) -> None:
168
+ super().__init__()
169
+ assert in_channels % n_heads == 0, 'n_heads must divide in_channels'
170
+ self.n_heads = n_heads
171
+ self.in_channels = in_channels
172
+ self.embedding_channels = embedding_channels
173
+
174
+ self.norm2 = nn.LayerNorm(in_channels)
175
+
176
+ self.ffn = nn.Sequential(
177
+ nn.Linear(self.in_channels, self.in_channels // 2, bias=with_bias),
178
+ nn.GELU(),
179
+ nn.Linear(self.in_channels // 2, self.in_channels, bias=with_bias),
180
+ nn.Dropout(dropout)
181
+ )
182
+
183
+ def forward(self, x: Tensor, attn_f2m: Tensor):
184
+ '''
185
+ x: N, HW, C
186
+ attn_f2m: N, h, HW, C//h
187
+ mask: N, H, W
188
+ '''
189
+ bs, length, _ = x.shape
190
+
191
+ # part 1: add precomputed attention
192
+ attn_out = attn_f2m.transpose(1, 2).contiguous().view(bs, length, -1) # N, HW, C
193
+ residue = x + attn_out
194
+
195
+ # part 2: norm+ffn
196
+ x = self.norm2(residue)
197
+ x = self.ffn(x)
198
+
199
+ # part 3: residue link, return N, HW, C
200
+ x = x + residue
201
+ return x
202
+
203
+
204
+ class LayoutEnhancedBlock(BaseModule):
205
+ def __init__(self,
206
+ in_channels,
207
+ bottleneck_channels,
208
+ bottleneck_group,
209
+ embedding_channels=256,
210
+ bridge_heads=4,
211
+ former_heads=8,
212
+ use_dyrelu=True,
213
+ dyrelu_mode='awared',
214
+ with_bias=True,
215
+ init_cfg: Union[dict, List[dict], None] = [
216
+ dict(type='Kaiming', layer='Conv'),
217
+ dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4)
218
+ ]):
219
+ super().__init__(init_cfg)
220
+
221
+ self.in_channels = in_channels
222
+ self.bottleneck_channels = bottleneck_channels
223
+ self.embedding_channels = embedding_channels
224
+ self.bridge_heads = bridge_heads
225
+ self.former_heads = former_heads
226
+ self.bottleneck_group = bottleneck_group
227
+
228
+ self.local = Local(in_channels=in_channels,
229
+ embedding_channels=embedding_channels,
230
+ bottleneck_channels=bottleneck_channels,
231
+ bottleneck_group=bottleneck_group,
232
+ use_dyrelu=use_dyrelu,
233
+ n_heads=bridge_heads,
234
+ dyrelu_mode=dyrelu_mode,
235
+ with_bias=with_bias)
236
+ self.dyrelu_mode = dyrelu_mode if use_dyrelu else 'none'
237
+
238
+ self.out_conv = ConvModule(bottleneck_channels, in_channels,
239
+ kernel_size=1,
240
+ bias=with_bias,
241
+ norm_cfg=dict(type='BN'),
242
+ act_cfg=dict(type='ReLU'))
243
+ self.pooling = nn.AdaptiveMaxPool1d(1)
244
+
245
+ self.local2layout = Local2Layout(n_heads=bridge_heads,
246
+ in_channels=in_channels,
247
+ embedding_channels=embedding_channels,
248
+ with_bias=with_bias)
249
+ self.layout2local = Layout2Local(n_heads=bridge_heads,
250
+ in_channels=bottleneck_channels,
251
+ embedding_channels=embedding_channels,
252
+ with_bias=with_bias)
253
+ self.layout = TFEncoderLayer(d_model=embedding_channels,
254
+ d_inner=embedding_channels // 2,
255
+ d_k=embedding_channels // former_heads,
256
+ d_v=embedding_channels // former_heads,
257
+ qkv_bias=with_bias,
258
+ n_head=former_heads) # using GELU in FFN
259
+
260
+ def forward(self, input: Tuple):
261
+ '''
262
+ x: N, C, H, W
263
+ z: N, M, d
264
+ masks: N, H, W
265
+ '''
266
+ x, z, mask = input # now mask is N, H+W
267
+ bs, _, h, w = x.size()
268
+
269
+ # part 2: m2f(need to prepare mask)
270
+ global_h = self.pooling(x.view(bs, -1, w)).view(bs, -1, h)
271
+ global_h = global_h.transpose(1,2).contiguous() # N, H, C
272
+ global_w = self.pooling(x.transpose(2,3).contiguous().view(bs, -1, h)).view(bs, -1, w)
273
+ global_w = global_w.transpose(1,2).contiguous() # N, W, C
274
+ global_x = torch.cat([global_h, global_w], dim=1) # N, (H+W), C
275
+
276
+ z = self.local2layout(global_x, z, mask)
277
+
278
+ # part 3: Layout
279
+ z = self.layout(z)
280
+
281
+ # part 4: Local
282
+ x_, attn_f2m = self.local(x, z) # contains activation DY-ReLU
283
+
284
+ # part 5: f2m
285
+ x_ = self.layout2local(x_.view(bs, self.bottleneck_channels, -1).transpose(1,2).contiguous(),
286
+ attn_f2m) # x_ is like N, HW, C_bottleneck
287
+
288
+ # part 6: residue link
289
+ x_ = x_.transpose(1,2).contiguous().view(bs, self.bottleneck_channels, h, w)
290
+ x = x + self.out_conv(x_)
291
+
292
+ return x, z, mask # for sequential input
seghist/model/module_loss/db_tks.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ import copy
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+
8
+ from mmocr.registry import MODELS
9
+ from mmocr.models.textdet.module_losses import DBModuleLoss
10
+ from mmocr.structures import TextDetDataSample
11
+
12
+ from seghist.utils import expand_poly, get_distance
13
+ from seghist.model import TKSModuleLoss
14
+
15
+ @MODELS.register_module()
16
+ class DBTKSModuleLoss(TKSModuleLoss, DBModuleLoss):
17
+ def __init__(self, stretch_ratio: float = 2, **kwargs):
18
+ TKSModuleLoss.__init__(self, stretch_ratio)
19
+ DBModuleLoss.__init__(self, **kwargs)
20
+
21
+ def _generate_thr_map(self,
22
+ img_size: Tuple[int, int],
23
+ polygons) -> np.ndarray:
24
+ """Generate threshold map.
25
+
26
+ Args:
27
+ img_size (tuple(int)): The image size (h, w)
28
+ polygons (Sequence[ndarray]): 2-d array, representing all the
29
+ polygons of the text region.
30
+
31
+ Returns:
32
+ tuple:
33
+
34
+ - thr_map (ndarray): The generated threshold map.
35
+ - thr_mask (ndarray): The effective mask of threshold map.
36
+ """
37
+ thr_map = np.zeros(img_size, dtype=np.float32)
38
+ thr_mask = np.zeros(img_size, dtype=np.uint8)
39
+
40
+ for polygon in polygons:
41
+ self._draw_border_map(polygon, thr_map,
42
+ mask=thr_mask,
43
+ shrink_ratio=self.shrink_ratio,
44
+ stretch_ratio=self.stretch_ratio)
45
+ thr_map = thr_map * (self.thr_max - self.thr_min) + self.thr_min
46
+
47
+ return thr_map, thr_mask
48
+
49
+ def _draw_border_map(self,
50
+ polygon: np.ndarray,
51
+ canvas: np.ndarray,
52
+ shrink_ratio: float,
53
+ stretch_ratio: float,
54
+ mask: np.ndarray) -> None:
55
+ """Generate threshold map for one polygon.
56
+
57
+ Args:
58
+ polygon (np.ndarray): The polygon.
59
+ canvas (np.ndarray): The generated threshold map.
60
+ mask (np.ndarray): The generated threshold mask.
61
+ """
62
+ # 按照相同加权方法进行扩张(便于之后加权计算thr map)
63
+ polygon = copy.deepcopy(polygon).reshape(-1, 2)
64
+ distance = get_distance(polygon, shrink_ratio)
65
+ expanded_polygon = expand_poly(polygon,
66
+ shrink_ratio,
67
+ stretch_ratio)
68
+ if len(expanded_polygon) == 0:
69
+ print(f'Padding {polygon} gets {expanded_polygon}')
70
+ expanded_polygon = polygon.copy().astype(np.int32)
71
+ else:
72
+ expanded_polygon = expanded_polygon.reshape(-1, 2).astype(np.int32)
73
+ x_min = expanded_polygon[:, 0].min()
74
+ x_max = expanded_polygon[:, 0].max()
75
+ y_min = expanded_polygon[:, 1].min()
76
+ y_max = expanded_polygon[:, 1].max()
77
+
78
+ width = x_max - x_min + 1
79
+ height = y_max - y_min + 1
80
+
81
+ polygon[:, 0] = (polygon[:, 0] - x_min) * stretch_ratio
82
+ polygon[:, 1] = polygon[:, 1] - y_min
83
+
84
+ # 构建坐标grid
85
+ xs = np.broadcast_to(
86
+ np.linspace(0, width - 1, num=width).reshape(1, width),
87
+ (height, width)) * stretch_ratio # 横向坐标加权计算
88
+ ys = np.broadcast_to(
89
+ np.linspace(0, height - 1, num=height).reshape(height, 1),
90
+ (height, width))
91
+
92
+ # 原polygon的每条边对应一个map,最后取最小距离
93
+ distance_map = np.zeros((polygon.shape[0], height, width),
94
+ dtype=np.float32)
95
+ # 统计区域内每个点到每一条边的距离
96
+ for i in range(polygon.shape[0]):
97
+ j = (i + 1) % polygon.shape[0]
98
+ absolute_distance = self._dist_points2line(xs, ys, polygon[i],
99
+ polygon[j])
100
+ # 最后会用 1-distance_map 做thresh
101
+ distance_map[i] = np.clip(absolute_distance / distance, 0, 1)
102
+ distance_map = distance_map.min(axis=0) # 每个点的距离由最小距离决定
103
+
104
+ x_min_valid = min(max(0, x_min), canvas.shape[1] - 1)
105
+ x_max_valid = min(max(0, x_max), canvas.shape[1] - 1)
106
+ y_min_valid = min(max(0, y_min), canvas.shape[0] - 1)
107
+ y_max_valid = min(max(0, y_max), canvas.shape[0] - 1)
108
+
109
+ if x_min_valid - x_min >= width or y_min_valid - y_min >= height:
110
+ return
111
+
112
+ # 位于扩张后多边形区域内的点会被考虑(thr有效)
113
+ cv2.fillPoly(mask, [expanded_polygon.astype(np.int32)], 1)
114
+ canvas[y_min_valid:y_max_valid + 1,
115
+ x_min_valid:x_max_valid + 1] = np.fmax(
116
+ 1 - distance_map[y_min_valid - y_min: y_max_valid - y_max +
117
+ height, x_min_valid - x_min: x_max_valid -
118
+ x_max + width],
119
+ canvas[y_min_valid:y_max_valid + 1,
120
+ x_min_valid:x_max_valid + 1])
121
+
122
+ def _get_target_single(self, data_sample: TextDetDataSample) -> Tuple:
123
+ """Generate loss target from a data sample.
124
+ Modified to adapt to batch padding
125
+
126
+ Args:
127
+ data_sample (TextDetDataSample): The data sample.
128
+
129
+ Returns:
130
+ tuple: A tuple of four tensors as the targets of one prediction.
131
+ """
132
+
133
+ gt_shrink, gt_shrink_mask = TKSModuleLoss._get_target_single(self, data_sample)
134
+ gt_instances = data_sample.gt_instances
135
+ ignore_flags = gt_instances.ignored
136
+
137
+ # thr mask is only effective around the text area, so there's no need to mask the padding.
138
+ gt_thr, gt_thr_mask = self._generate_thr_map(
139
+ data_sample.batch_input_shape, gt_instances[~ignore_flags].polygons)
140
+
141
+ gt_thr = torch.from_numpy(gt_thr).unsqueeze(0).float()
142
+ gt_thr_mask = torch.from_numpy(gt_thr_mask).unsqueeze(0).float()
143
+ return gt_shrink, gt_shrink_mask, gt_thr, gt_thr_mask
seghist/model/module_loss/pan_tks.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from typing import Tuple
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ from mmocr.registry import MODELS
8
+ from mmocr.structures import TextDetDataSample
9
+ from mmocr.models.textdet.module_losses import PANModuleLoss
10
+
11
+ from seghist.model import TKSModuleLoss
12
+
13
+ @MODELS.register_module()
14
+ class PANTKSModuleLoss(TKSModuleLoss, PANModuleLoss):
15
+ """PAN generates multiple targets using series of ratios.
16
+ Rewrite function _get_target_single based on TKS.
17
+ """
18
+ def __init__(self, stretch_ratio: float = 2, **kwargs):
19
+ TKSModuleLoss.__init__(self, stretch_ratio)
20
+ PANModuleLoss.__init__(self, **kwargs)
21
+
22
+ def _get_target_single(self, data_sample: TextDetDataSample
23
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
24
+ """Generate loss target from a data sample.
25
+
26
+ Args:
27
+ data_sample (TextDetDataSample): The data sample.
28
+
29
+ Returns:
30
+ tuple: A tuple of four tensors as the targets of one prediction.
31
+ """
32
+ gt_polygons = data_sample.gt_instances.polygons
33
+ gt_ignored = data_sample.gt_instances.ignored
34
+
35
+ gt_kernels = []
36
+ for ratio in self.shrink_ratio:
37
+ gt_kernel, gt_ignored = self._generate_kernels(
38
+ data_sample.batch_input_shape,
39
+ gt_polygons,
40
+ ratio,
41
+ self.stretch_ratio,
42
+ ignore_flags=gt_ignored)
43
+ gt_kernels.append(gt_kernel)
44
+ gt_polygons_ignored = data_sample.gt_instances[gt_ignored].polygons
45
+ gt_mask = self._generate_effective_mask(data_sample.batch_input_shape,
46
+ gt_polygons_ignored)
47
+ gt_mask[data_sample.valid_shape[0]:data_sample.batch_input_shape[0],
48
+ data_sample.valid_shape[1]:data_sample.batch_input_shape[1]] = 0
49
+
50
+ gt_kernels = np.stack(gt_kernels, axis=0) #K, H, W
51
+ gt_kernels = torch.from_numpy(gt_kernels).float()
52
+ gt_mask = torch.from_numpy(gt_mask).float()
53
+ return gt_kernels, gt_mask
seghist/model/module_loss/pse_tks.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mmocr.registry import MODELS
2
+ from mmocr.models.textdet.module_losses import PSEModuleLoss
3
+
4
+ from seghist.model import PANTKSModuleLoss
5
+
6
+ @MODELS.register_module()
7
+ class PSETKSModuleLoss(PANTKSModuleLoss, PSEModuleLoss):
8
+ """Almost same from PANTKS, except forward method.
9
+ """
10
+ def __init__(self, stretch_ratio: float = 2, **kwargs):
11
+ PANTKSModuleLoss.__init__(self, stretch_ratio)
12
+ PSEModuleLoss.__init__(self, **kwargs)
13
+
14
+ def forward(self, *args, **kwargs):
15
+ return PSEModuleLoss.forward(self, *args, **kwargs)
seghist/model/module_loss/tks.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Sequence, Tuple, Optional, Dict, Union
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from torch import Tensor
7
+
8
+ from mmocr.registry import MODELS
9
+ from mmocr.models.textdet.module_losses import SegBasedModuleLoss
10
+ from mmocr.structures import TextDetDataSample
11
+
12
+ from seghist.utils import stretch_kernel
13
+
14
+ class TKSModuleLoss(SegBasedModuleLoss):
15
+ """Computing module loss using the Text Kernel Stretching method.
16
+ Generating targets for a segmentation-based model that only predicts
17
+ text kernel. Also serves as a subclass for the SegHist implementation
18
+ of a specific segmentation-based model.
19
+
20
+ Args:
21
+ stretch_ratio: Horizontal stretching ratio (s>1).
22
+ """
23
+ def __init__(self, stretch_ratio: float = 2, **kwargs):
24
+ super().__init__(**kwargs)
25
+ self.stretch_ratio = stretch_ratio
26
+
27
+ def _generate_kernels(
28
+ self,
29
+ img_size: Tuple[int, int],
30
+ text_polys: Sequence[np.ndarray],
31
+ shrink_ratio: float,
32
+ stretch_ratio: float,
33
+ ignore_flags: Optional[np.ndarray] = None,
34
+ ) -> Tuple[np.ndarray, np.ndarray]:
35
+ """Generate text instance kernels according to a shrink ratio.
36
+
37
+ Args:
38
+ img_size (tuple(int, int)): The image size of (height, width).
39
+ text_polys (Sequence[np.ndarray]): 2D array of text polygons.
40
+ shrink_ratio (float or int): The shrink ratio of kernel.
41
+ stretch_ratio (float or int): The stretch ratio of kernel.
42
+ ignore_flags (torch.BoolTensor, optional): Indicate whether the
43
+ corresponding text polygon is ignored. Defaults to None.
44
+
45
+ Returns:
46
+ tuple(ndarray, ndarray): The text instance kernels of shape
47
+ (height, width) and updated ignorance flags.
48
+ """
49
+ assert isinstance(img_size, tuple)
50
+ assert isinstance(shrink_ratio, (float, int))
51
+
52
+ if ignore_flags is None:
53
+ ignore_flags = [False for _ in text_polys]
54
+
55
+ text_kernel = np.zeros(img_size, dtype=np.float32)
56
+
57
+ for text_ind, poly in enumerate(text_polys):
58
+ if ignore_flags[text_ind]:
59
+ continue
60
+
61
+ shrunk_poly = stretch_kernel(poly, shrink_ratio, stretch_ratio)
62
+
63
+ # Split while shrinkage, resulted in empty list.
64
+ if len(shrunk_poly) == 0:
65
+ ignore_flags[text_ind] = True
66
+ continue
67
+
68
+ cv2.fillPoly(text_kernel,
69
+ [shrunk_poly.astype(np.int32)],
70
+ 1)
71
+
72
+ return text_kernel, ignore_flags
73
+
74
+ def _get_target_single(self, data_sample: TextDetDataSample) -> Tuple:
75
+ """Generate loss target from a data sample.
76
+ Modified to adapt to batch padding
77
+
78
+ Args:
79
+ data_sample (TextDetDataSample): The data sample.
80
+
81
+ Returns:
82
+ tuple: A tuple of four tensors as the targets of one prediction.
83
+ """
84
+
85
+ gt_instances = data_sample.gt_instances
86
+ ignore_flags = gt_instances.ignored
87
+ for idx, polygon in enumerate(gt_instances.polygons):
88
+ if self._is_poly_invalid(polygon.astype(np.float32)):
89
+ ignore_flags[idx] = True
90
+
91
+ gt_shrink, ignore_flags = self._generate_kernels(
92
+ data_sample.batch_input_shape, # adapt to batch input shape
93
+ gt_instances.polygons,
94
+ self.shrink_ratio,
95
+ self.stretch_ratio,
96
+ ignore_flags=ignore_flags)
97
+
98
+ # Get boolean mask where Trues indicate text instance pixels
99
+ gt_shrink = gt_shrink > 0
100
+
101
+ gt_shrink_mask = self._generate_effective_mask(
102
+ data_sample.batch_input_shape, gt_instances[ignore_flags].polygons)
103
+
104
+ # mask padding area
105
+ gt_shrink_mask[data_sample.valid_shape[0]:data_sample.batch_input_shape[0],
106
+ data_sample.valid_shape[1]:data_sample.batch_input_shape[1]] = 0
107
+
108
+ # to_tensor
109
+ gt_shrink = torch.from_numpy(gt_shrink).unsqueeze(0).float()
110
+ gt_shrink_mask = torch.from_numpy(gt_shrink_mask).unsqueeze(0).float()
111
+ return gt_shrink, gt_shrink_mask
112
+
113
+
114
+ @MODELS.register_module()
115
+ class SegHistModuleLoss(TKSModuleLoss):
116
+ def __init__(self,
117
+ loss_prob: Dict = dict(
118
+ type='MaskedBalancedBCEWithLogitsLoss'),
119
+ weight_prob: float = 5.,
120
+ min_sidelength: Union[int, float] = 8) -> None:
121
+ super().__init__()
122
+ self.loss_prob = MODELS.build(loss_prob)
123
+ self.weight_prob = weight_prob
124
+ self.min_sidelength = min_sidelength
125
+
126
+ def forward(self, preds: Tuple[Tensor],
127
+ data_samples: Sequence[TextDetDataSample]) -> Dict:
128
+
129
+ prob_logits = preds
130
+ gt_shrinks, gt_shrink_masks = self.get_targets(data_samples)
131
+ gt_shrinks = gt_shrinks.to(prob_logits.device)
132
+ gt_shrink_masks = gt_shrink_masks.to(prob_logits.device)
133
+
134
+ loss_prob = self.loss_prob(prob_logits, gt_shrinks, gt_shrink_masks)
135
+
136
+ results = dict(loss_prob=self.weight_prob * loss_prob)
137
+
138
+ return results
seghist/model/postprocessor/iedp.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from torch import Tensor
7
+ from shapely.geometry import Polygon
8
+
9
+ from mmengine.structures import InstanceData
10
+ from mmocr.structures import TextDetDataSample
11
+ from mmocr.registry import MODELS
12
+ from mmocr.models.textdet.postprocessors import DBPostprocessor
13
+
14
+ from seghist.utils import unstretch_kernel
15
+
16
+ @MODELS.register_module()
17
+ class IterExpandPostprocessor(DBPostprocessor):
18
+ """Implementation for Iterative Expansion Distance Post-Processor.
19
+
20
+ Args:
21
+ shrink_ratio: r<1
22
+ stretch_ratio: s>=1
23
+ min_text_area: min regional area in origin scale.
24
+ refine: refine or unclip kernel only once.
25
+ unclip_ratio: u>0, used when refine is false.
26
+ """
27
+ def __init__(self,
28
+ shrink_ratio: float = 0.,
29
+ stretch_ratio: float = 2.0,
30
+ min_text_area: int = 200, # area respect to original size
31
+ refine: bool = True,
32
+ unclip_ratio: Optional[float] = None,
33
+ **kwargs):
34
+ super().__init__(**kwargs)
35
+ self.stretch_ratio = stretch_ratio
36
+ self.shrink_ratio = shrink_ratio
37
+ self.min_text_area = min_text_area
38
+ self.refine = refine
39
+ if not refine:
40
+ assert unclip_ratio > 0, 'must set unclip ratio u when not refine'
41
+ self.unclip_ratio = unclip_ratio
42
+
43
+ def get_text_instances(self, prob_map: Tensor,
44
+ data_sample: TextDetDataSample
45
+ ) -> TextDetDataSample:
46
+ """Get text instance predictions of one image.
47
+
48
+ Args:
49
+ pred_result (Tensor): DBNet's output ``prob_map`` of shape
50
+ :math:`(H, W)`.
51
+ data_sample (TextDetDataSample): Datasample of an image.
52
+
53
+ Returns:
54
+ TextDetDataSample: A new DataSample with predictions filled in.
55
+ Polygons and results are saved in
56
+ ``TextDetDataSample.pred_instances.polygons``. The confidence
57
+ scores are saved in ``TextDetDataSample.pred_instances.scores``.
58
+ """
59
+ prob_map = prob_map[..., :data_sample.valid_shape[0], :data_sample.valid_shape[1]]
60
+
61
+ data_sample.pred_instances = InstanceData()
62
+ data_sample.pred_instances.polygons = []
63
+ data_sample.pred_instances.scores = []
64
+
65
+ text_mask = prob_map > self.mask_thr
66
+
67
+ score_map = prob_map.data.cpu().numpy().astype(np.float32)
68
+ text_mask = text_mask.data.cpu().numpy() * 255
69
+ text_mask = text_mask.astype(np.uint8) # to numpy
70
+
71
+ contours, _ = cv2.findContours(text_mask,
72
+ cv2.RETR_EXTERNAL,
73
+ cv2.CHAIN_APPROX_SIMPLE)
74
+
75
+ for i, poly in enumerate(contours):
76
+ if i > self.max_candidates:
77
+ break
78
+ epsilon = self.epsilon_ratio * cv2.arcLength(poly, True)
79
+ approx = cv2.approxPolyDP(poly, epsilon, True)
80
+ poly_pts = approx.reshape(-1, 2)
81
+ if poly_pts.shape[0] < 4:
82
+ continue
83
+ score = self._get_bbox_score(score_map, poly_pts)
84
+ if score < self.min_text_score:
85
+ continue
86
+
87
+ # trying recover kernel in iterative mode
88
+ try:
89
+ poly = unstretch_kernel(poly_pts,
90
+ self.shrink_ratio,
91
+ self.stretch_ratio,
92
+ refinement=self.refine,
93
+ unclip_ratio=self.unclip_ratio)
94
+ except Exception as e:
95
+ print(f'Error {e} find when unstretching kernel {poly_pts}.')
96
+
97
+ # If the result polygon does not exist, or it is split into
98
+ # multiple polygons, skip it.
99
+ if len(poly) == 0:
100
+ continue
101
+ poly = poly.reshape(-1, 2)
102
+
103
+ if self.text_repr_type == 'quad':
104
+ rect = cv2.minAreaRect(poly.astype(np.int32))
105
+ vertices = cv2.boxPoints(rect)
106
+ poly = vertices.flatten() if min(
107
+ rect[1]) >= self.min_text_width else []
108
+ elif self.text_repr_type == 'poly':
109
+ scale = data_sample.scale_factor[0] * data_sample.scale_factor[1]
110
+ poly = poly.flatten() if Polygon(
111
+ poly).area / scale > self.min_text_area else []
112
+
113
+ if len(poly) < 8:
114
+ poly = np.array([], dtype=np.float32)
115
+
116
+ if len(poly) > 0:
117
+ data_sample.pred_instances.polygons.append(poly)
118
+ data_sample.pred_instances.scores.append(score)
119
+
120
+ data_sample.pred_instances.scores = torch.FloatTensor(
121
+ data_sample.pred_instances.scores)
122
+
123
+ return data_sample
seghist/utils/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .poly_utils import *
2
+ from .image_utils import ImageToolkits