dlxj commited on
Commit ·
ce0144c
1
Parent(s): 03d4c37
init
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- .gitignoreAdded+47
- LICENSEAdded+202
- README.mdAdded+106
- config/_base_/datasets/complete_data.pyAdded+152
- config/_base_/datasets/iacc2022_chdac.pyAdded+28
- config/_base_/datasets/iacc2022_chdac_toy.pyAdded+12
- config/_base_/datasets/icdar2019hdrc.pyAdded+30
- config/_base_/datasets/mthv2.pyAdded+19
- config/_base_/default_runtime.pyAdded+46
- config/_base_/schedules/schedule_adam_600e.pyAdded+13
- config/_base_/schedules/schedule_sgd_500e.pyAdded+13
- config/_base_/textdet_runtime.pyAdded+36
- config/baseline/config.pyAdded+96
- config/baseline/model/dbnetpp.pyAdded+37
- config/baseline/model/psenet.pyAdded+44
- config/baseline/pipeline.pyAdded+51
- config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.pyAdded+47
- config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.pyAdded+44
- config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.pyAdded+44
- config/seghist/_base_seghist_resnet50-dcnv2_fpnc.pyAdded+48
- config/seghist/pipeline/seghist_pipeline_basic.pyAdded+50
- config/seghist/pipeline/seghist_pipeline_basic_rotate.pyAdded+58
- config/seghist/pipeline/seghist_pipeline_color_jitter.pyAdded+48
- config/seghist/pipeline/seghist_pipeline_large_rotate.pyAdded+57
- config/seghist/pipeline/seghist_pipeline_largescale.pyAdded+49
- config/seghist/seghist_resnet50-dcnv2_fpnc.pyAdded+89
- config/seghist/seghist_resnet50-dcnv2_fpnc_large.pyAdded+75
- config/seghist/seghist_resnet50-dcnv2_fpnc_toy.pyAdded+67
- environment.ymlAdded+198
- readme.txtAdded+1
- samples/gt1.pngAdded
- samples/gt2.pngAdded
- samples/pred1.pngAdded
- samples/pred2.pngAdded
- seghist/__init__.pyAdded+2
- seghist/datasets/__init__.pyAdded+1
- seghist/datasets/transforms/__init__.pyAdded+5
- seghist/datasets/transforms/colorspace.pyAdded+30
- seghist/datasets/transforms/textdet_transforms.pyAdded+164
- seghist/model/__init__.pyAdded+10
- seghist/model/heads/seghist_heads.pyAdded+280
- seghist/model/layer/dyrelu.pyAdded+88
- seghist/model/layer/layout_enhanced_block.pyAdded+292
- seghist/model/module_loss/db_tks.pyAdded+143
- seghist/model/module_loss/pan_tks.pyAdded+53
- seghist/model/module_loss/pse_tks.pyAdded+15
- seghist/model/module_loss/tks.pyAdded+138
- seghist/model/postprocessor/iedp.pyAdded+123
- seghist/utils/__init__.pyAdded+2
1234*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text12345*.7z filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# 操作系统生成的文件.DS_StoreThumbs.db
# 日志文件*.log
# Python 编译生成的文件*.pyc*.pyo
# 虚拟环境env/venv/.venv/
# 配置文件.env.env.local.env.*.local
# 项目依赖.mypy_cache/.tox/.coverage.cachenosetests.xmlcoverage.xml*.cover
# 临时文件和目录.dist_test/*.swp.idea/.vscode/*.ipynb
# 忽略所有目录,不包含 config 和 seghist,同时忽略下面的pycache*/data!config/!config/**!seghist/!seghist/**!samples/!samples/****/__pycache__/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2024 Xingjian Hu from Peking University.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# (ICDAR 2024) SegHist: A General Segmentation-based Framework for Chinese Historical Document Text Line Detection
<div align="center"> [](https://arxiv.org/abs/2406.15485)
[](https://github.com/LumionHXJ/SegHist/watchers)
[](https://github.com/LumionHXJ/SegHist/stargazers)
[](https://github.com/LumionHXJ/SegHist)</div>
**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).**
## 🔍 **Examples**
| Groundtruth | Prediction || --------------------------- | ------------------------------- ||  |  ||  |  |
## 📄 Abstract
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.
## ⚙️ **Requirements**
Installing using config:
```bashconda env create -f environment.yml```
Or installing step-by-step:
```bashconda create --name openmmlab python=3.8 -yconda activate openmmlabconda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 -c pytorchpip install -U openmimmim install mmengine==0.10.4 mmcv==2.0.1 mmdet==3.0.0 mmocr==1.0.0rc5```
## 🚀 **Training**
Training DB-SegHist as example (training other model by changing checkpoint):
```bashpython -m torch.distributed.run --nproc_per_node=4 train.py --launcher pytorch --work-dir work_dirs/ config/seghist/seghist_resnet50-dcnv2_fpnc.py```
## 🧠 **Inferencing**
```bashpython test.py --work-dir work_dirs/ config/seghist/seghist_resnet50-dcnv2_fpnc.py [your_checkpoint]```
## 📚 **Acquiring Data**
The data we used can be accessed as follows:
- CHDAC: Contact their [email](iacc_pazhoulab_hp@163.com) or visit their [official website](https://iacc.pazhoulab-huangpu.com/).- MTHv2: https://github.com/HCIILAB/MTHv2_Datasets_Release- ICDAR2019: https://tc11.cvc.uab.es/datasets/ICDAR2019HDRC
## 🏆 **Our Results on CHDAC**
| Method | P | R | F ||-------------------------|--------|--------|--------|| EAST [Zhou et al. 2017] | 61.41 | 73.13 | 66.76 || Mask R-CNN [He et al. 2017] | 89.03 | 80.90 | 84.77 || Cascade R-CNN [Cai et al. 2018] | 92.82 | 83.63 | 87.98 || OBD [Liu et al. 2021] | 94.73 | 81.52 | 87.63 || TextSnake [Long et al. 2018] | 96.33 | 89.62 | 92.85 || PSENet [Wang et al. 2019] | 76.99 | 89.62 | 82.83 || PAN [Wang et al. 2019] | 92.74 | 85.71 | 89.09 || FCENet [Zhu et al. 2021] | 88.42 | 85.04 | 86.70 || DBNet++ [Liao et al. 2022] | 91.39 | 89.15 | 90.26 || HisDoc R-CNN [Jian et al. 2023] | _98.19_ | 93.74 | 95.92 || **PSE-SegHist (ours)** | 97.00 | _95.31_ | _96.15_ || **PAN-SegHist (ours)** | 97.52 | 94.77 | 96.12 || **DB-SegHist (ours)** | **98.36** | **95.88** | **97.11** |
*_P_, _R_, and _F_ indicate the precision, recall, and F-measure, respectively, at an IoU threshold of 0.5.
## 🔒 **LICENSE**
This code is distributed under the Apache License. Please note that the datasets we rely on may not be allowed for commercial use.
## 🔗 **CITATION**
```@inproceedings{hu2024seghist, title={SegHist: A General Segmentation-Based Framework for Chinese Historical Document Text Line Detection}, author={Hu, Xingjian and Wei, Baole and Gao, Liangcai and Wang, Jun}, booktitle={International Conference on Document Analysis and Recognition}, pages={391--410}, year={2024}, organization={Springer}}```
## 📧 **CONTACT US**
If you have any question, please contact: huxingjian@pku.edu.cn.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152<<<<<<< HEADdata_root = 'data/historical_document/IACC2022_CHDAC/official_dataset'=======data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'>>>>>>> origin/main
chdac_train_preliminary = dict( type='OCRDataset', data_root=data_root, ann_file='preliminary/train/ocr_train.json', data_prefix=dict(img_path='preliminary/train/image'), pipeline=None)
chdac_train_final = dict( type='OCRDataset', data_root=data_root, ann_file='final/train/ocr_train.json', data_prefix=dict(img_path='final/train/image'), pipeline=None)
chdac_test = dict( type='OCRDataset', data_root=data_root, ann_file='final/test/ocr_test.json', data_prefix=dict(img_path='final/test/image'), test_mode=True, pipeline=None)
<<<<<<< HEADdata_root = 'data/historical_document/IACC2022_CHDAC/private_dataset'=======data_root = './data/historical_document/IACC2022_CHDAC/private_dataset'>>>>>>> origin/main
chdac_train_private1 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_1/train/ocr_train.json', data_prefix=dict(img_path='dataset_1/train/image'), pipeline=None)
chdac_test_private1 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_1/test/ocr_test.json', data_prefix=dict(img_path='dataset_1/test/image'), test_mode=True, pipeline=None)
chdac_train_private2 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_2/train/ocr_train.json', data_prefix=dict(img_path='dataset_2/train/image'), pipeline=None)
chdac_test_private2 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_2/test/ocr_test.json', data_prefix=dict(img_path='dataset_2/test/image'), test_mode=True, pipeline=None)
chdac_train_private3 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_3/train/ocr_train.json', data_prefix=dict(img_path='dataset_3/train/image'), pipeline=None)
chdac_test_private3 = dict( type='OCRDataset', data_root=data_root, ann_file='dataset_3/test/ocr_test.json', data_prefix=dict(img_path='dataset_3/test/image'), test_mode=True, pipeline=None)
data_root = './data/historical_document/ICDAR2019HDRC_Chinese/'
icdar2019_trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label_comp.json', data_prefix=dict(img_path='images'), pipeline=None)
icdar2019_testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label_comp.json', test_mode=True, data_prefix=dict(img_path='images'), # indices=50 在更小的数据集上尝试验证效果 pipeline=None)
data_root = './data/historical_document/MTHv2/MTHv2'
mthv2_trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label.json', pipeline=None)
mthv2_testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label.json', test_mode=True, pipeline=None)
data_root = './data/historical_document/MTHv2/twist_MTHv2'
twist_mthv2_trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label.json', pipeline=None)
twist_mthv2_testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label.json', test_mode=True, pipeline=None)
data_root = './data/historical_document/Huayan'
huayan_trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label.json', data_prefix=dict(img_path='images'), pipeline=None)
huayan_testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label.json', data_prefix=dict(img_path='images'), test_mode=True, pipeline=None)# 没有使用mthv2train_list = [chdac_train_preliminary, chdac_train_final, icdar2019_trainset, twist_mthv2_trainset, huayan_trainset, chdac_train_private1, chdac_train_private2, chdac_train_private3]test_list = [chdac_test, icdar2019_testset, huayan_testset, twist_mthv2_testset, chdac_test_private1, chdac_test_private2, chdac_test_private3]val_list = test_list12345678910111213141516171819202122232425262728data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'
chdac_train_preliminary = dict( type='OCRDataset', data_root=data_root, ann_file='preliminary/train/ocr_train.json', data_prefix=dict(img_path='preliminary/train/image'), pipeline=None)
chdac_train_final = dict( type='OCRDataset', data_root=data_root, ann_file='final/train/ocr_train.json', data_prefix=dict(img_path='final/train/image'), pipeline=None)
chdac_test = dict( type='OCRDataset', data_root=data_root, ann_file='final/test/ocr_test.json', data_prefix=dict(img_path='final/test/image'), test_mode=True, #indices=150, #在更小的数据集上尝试验证效果 pipeline=None)
train_list = [chdac_train_preliminary, chdac_train_final]test_list = [chdac_test]val_list = test_list123456789101112data_root = './data/historical_document/IACC2022_CHDAC/official_dataset'
chdac_toy = dict( type='OCRDataset', data_root=data_root, ann_file='final/train/ocr_toy.json', data_prefix=dict(img_path='final/train/image'), pipeline=None)
train_list = [chdac_toy]test_list = [chdac_toy]val_list = [chdac_toy]123456789101112131415161718192021222324252627282930data_root = './data/historical_document/ICDAR2019HDRC_Chinese/'
trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label.json', data_prefix=dict(img_path='images'), pipeline=None)
valset = dict( type='OCRDataset', data_root=data_root, ann_file='val_label.json', test_mode=True, data_prefix=dict(img_path='images'), # indices=50 在更小的数据集上尝试验证效果 pipeline=None)
testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label.json', test_mode=True, data_prefix=dict(img_path='images'), # indices=50 在更小的数据集上尝试验证效果 pipeline=None)
train_list = [trainset]val_list = [valset]test_list = [testset]12345678910111213141516171819data_root = './data/historical_document/MTHv2/MTHv2'
trainset = dict( type='OCRDataset', data_root=data_root, ann_file='train_label.json', pipeline=None)
testset = dict( type='OCRDataset', data_root=data_root, ann_file='test_label.json', test_mode=True, # indices=50 在更小的数据集上尝试验证效果 pipeline=None)
train_list = [trainset]test_list = [testset]val_list = [testset]12345678910111213141516171819202122232425262728293031323334353637383940414243444546default_scope = 'mmocr'env_cfg = dict( cudnn_benchmark=True, mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), dist_cfg=dict(backend='nccl'),)randomness = dict(seed=None)
default_hooks = dict( timer=dict(type='IterTimerHook'), logger=dict(type='LoggerHook', interval=10), # param_scheduler=dict(type='ParamSchedulerHook'), checkpoint=dict(type='CheckpointHook', interval=5, max_keep_ckpts=3), sampler_seed=dict(type='DistSamplerSeedHook'), sync_buffer=dict(type='SyncBuffersHook'), visualization=dict( type='VisualizationHook', interval=1, enable=False, show=False, draw_gt=False, draw_pred=False),)
custom_hooks = [dict(type='EmptyCacheHook', after_iter=True), dict(type='SyncBuffersHook')]
# Logginglog_level = 'INFO'log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True)
# Evaluationval_evaluator = [dict(type='E2EHmeanIOUMetric'), dict(type='HmeanIOUMetric'), dict(type='E2ENEDMetric')]test_evaluator = val_evaluator
# Visualizationvis_backends = [dict(type='LocalVisBackend'), dict(type='TensorboardVisBackend')]visualizer = dict( type='TextSpottingLocalVisualizer', name='visualizer', vis_backends=vis_backends)12345678910111213# optimizer# 不同层采用不同学习率,下调学习率后scheduler也要调整optim_wrapper = dict(type='OptimWrapper', optimizer=dict(type='AdamW', lr=1e-3))train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=200, val_interval=10)
val_cfg = dict(type='ValLoop')test_cfg = dict(type='TestLoop')
#param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[50, 120], gamma=0.1)12345678910111213
# optimizeroptim_wrapper = dict( type='OptimWrapper', optimizer=dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0001), clip_grad=dict(type='value', clip_value=1))train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=1, val_interval=50)val_cfg = dict(type='ValLoop')test_cfg = dict(type='TestLoop')# learning policyparam_scheduler = [ dict(type='LinearLR', end=1000, start_factor=0.001, by_epoch=False),]123456789101112131415161718192021222324252627282930313233343536default_scope = 'mmocr'env_cfg = dict( cudnn_benchmark=True, mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), dist_cfg=dict(backend='nccl'),)
default_hooks = dict( timer=dict(type='IterTimerHook'), logger=dict(type='LoggerHook', interval=10), param_scheduler=dict(type='ParamSchedulerHook'), checkpoint=dict(type='CheckpointHook', interval=5, max_keep_ckpts=10), sampler_seed=dict(type='DistSamplerSeedHook'), sync_buffer=dict(type='SyncBuffersHook'), visualization=dict( type='VisualizationHook', interval=1, enable=False, show=False, draw_gt=False, draw_pred=False),)
# Logginglog_level = 'INFO'log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True)
# Visualizationvis_backends = [dict(type='LocalVisBackend'), dict(type='TensorboardVisBackend')]visualizer = dict( type='TextDetLocalVisualizer', name='visualizer', vis_backends=vis_backends)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596_base_ = [ './model/dbnetpp.py', './pipeline.py', '../_base_/textdet_runtime.py', '../_base_/datasets/iacc2022_chdac.py']
# dataset settingstrain_list = _base_.train_listtest_list = _base_.test_listval_list = _base_.val_list
train_dataloader = dict( batch_size=8, num_workers=8, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), dataset=dict( type='ConcatDataset', datasets=train_list, pipeline=_base_.train_pipeline))
test_dataloader = dict( batch_size=1, num_workers=1, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=test_list, pipeline=_base_.test_pipeline))
val_dataloader = dict( batch_size=1, num_workers=1, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=val_list, pipeline=_base_.test_pipeline))
auto_scale_lr = dict(base_batch_size=16)
test_evaluator = [dict(type='HmeanIOUMetric', prefix='Iacc', match_iou_thr=0.5, pred_score_thrs=dict(start=0.3, stop=0.9, step=0.05)), dict(type='HmeanIOUMetric', prefix='Iacc75', match_iou_thr=0.75, pred_score_thrs=dict(start=0.3, stop=0.9, step=0.05))]val_evaluator = test_evaluator
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=250, val_interval=10)default_hooks = dict( checkpoint=dict(type='CheckpointHook', interval=5, max_keep_ckpts=10))
val_cfg = dict(type='ValLoop')test_cfg = dict(type='TestLoop')
<<<<<<< HEAD======='''param_scheduler = dict( type='MultiStepLR', by_epoch=True, milestones=[110], gamma=0.1)'''>>>>>>> origin/mainparam_scheduler = [dict(type='ReduceOnPlateauLR', rule='greater', monitor='Iacc/recall', factor=0.3, patience=1, threshold=1e-4)] # use arg last_step when resuming optim!
custom_imports = dict( imports=['seghist'], # not support relative import allow_failed_imports=False)
optim_wrapper = dict( type='AmpOptimWrapper', optimizer=dict(type='AdamW', lr=1e-4))
<<<<<<< HEAD======='''optim_wrapper = dict( type='OptimWrapper', optimizer=dict(type='AdamW', lr=1e-3))'''
>>>>>>> origin/main#resume = True#load_from = '/home/huxingjian/model/mmocr/projects/SegHist/work_dirs_baseline/dbnetpp/epoch_5.pth'12345678910111213141516171819202122232425262728293031323334353637model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='DBHead', in_channels=256, module_loss=dict(type='DBModuleLoss'), postprocessor=dict( type='IterExpandPostprocessor', text_repr_type='poly', epsilon_ratio=0.002, shrink_ratio=0.16, stretch_ratio=1, refine=True, unclip_ratio=2.5)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))1234567891011121314151617181920212223242526272829303132333435363738394041424344model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='PANSegHistHead', in_channels=256, num_blocks=0, num_query=8, output_channels=7, shallow_channels=128, embedding_channels=128, # = shallow channels use_dyrelu=True, dyrelu_mode='awared', with_m2f_mask=True, module_loss=dict(type='PSETKSModuleLoss', shrink_ratio=(1, 0.81, 0.64, 0.49, 0.36, 0.25, 0.16), stretch_ratio=1), postprocessor=dict(type='PSEPostprocessor', text_repr_type='poly', min_text_area=200, score_threshold=0.3, downsample_ratio=1)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict( type='TorchVisionWrapper', op='ColorJitter', brightness=0.12549019607843137, saturation=0.5), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='RandomChoiceResize', scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800), (1333, 832), (1333, 864), (1333, 896)], keep_ratio=True, clip_object_border=False), # clip the object when outside border dict(type='TextDetRandomCrop', target_size=(640, 640)), dict(type='Pad', size=(640, 640)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='Resize', scale=(1333, 800), keep_ratio=True, clip_object_border=True), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647r = 0. # shrink_ratiostretch_ratio = 2. # 1.5model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='DBSegHistHead', in_channels=256, num_blocks=3, num_query=8, shallow_channels=128, embedding_channels=128, # = shallow channels use_dyrelu=True, dyrelu_mode='awared', with_m2f_mask=True, module_loss=dict(type='DBTKSModuleLoss', shrink_ratio=r, stretch_ratio=stretch_ratio), postprocessor=dict( type='IterExpandPostprocessor', text_repr_type='poly', shrink_ratio=r, stretch_ratio=stretch_ratio, epsilon_ratio=0.002, mask_thr=0.6)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))1234567891011121314151617181920212223242526272829303132333435363738394041424344model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='PANSegHistHead', in_channels=256, num_blocks=3, num_query=8, output_channels=6, shallow_channels=128, embedding_channels=128, # = shallow channels use_dyrelu=True, dyrelu_mode='awared', with_m2f_mask=True, module_loss=dict(type='PANTKSModuleLoss', shrink_ratio=(1, 0), stretch_ratio=2), postprocessor=dict(type='PANPostprocessor', text_repr_type='poly', min_text_area=200, downsample_ratio=1, score_threshold=0.6)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))1234567891011121314151617181920212223242526272829303132333435363738394041424344model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='PANSegHistHead', in_channels=256, num_blocks=3, num_query=8, output_channels=6, shallow_channels=128, embedding_channels=128, # = shallow channels use_dyrelu=True, dyrelu_mode='awared', with_m2f_mask=True, module_loss=dict(type='PSETKSModuleLoss', shrink_ratio=(1, 0.8, 0.6, 0.4, 0.2, 0), stretch_ratio=2), postprocessor=dict(type='PSEPostprocessor', text_repr_type='poly', min_text_area=200, score_threshold=0.6, downsample_ratio=1)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748r = 0. # shrink_ratiostretch_ratio = 2. # 1.5model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, style='pytorch', dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='FPNC', in_channels=[256, 512, 1024, 2048], lateral_channels=256, asf_cfg=dict(attention_type='ScaleChannelSpatial')), det_head=dict( type='SegHistHead', in_channels=256, num_blocks=3, num_query=8, shallow_channels=128, embedding_channels=128, # = shallow channels use_dyrelu=True, dyrelu_mode='awared', with_m2f_mask=True, with_sigmoid=False, module_loss=dict(type='SegHistModuleLoss', shrink_ratio=r, stretch_ratio=stretch_ratio), postprocessor=dict( type='IterExpandPostprocessor', text_repr_type='poly', shrink_ratio=r, stretch_ratio=stretch_ratio, epsilon_ratio=0.002, mask_thr=0.6)), data_preprocessor=dict( type='TextDetDataPreprocessor', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], bgr_to_rgb=True, pad_size_divisor=32))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict( type='TorchVisionWrapper', op='ColorJitter', brightness=0.12549019607843137, saturation=0.5), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='RandomChoiceResize', scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800), (1333, 832), (1333, 864), (1333, 896)], keep_ratio=True, clip_object_border=False), # clip the object when outside border dict(type='TextDetRandomCrop', target_size=(640, 640)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='Resize', scale=(1333, 800), keep_ratio=True, clip_object_border=True), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict( type='TorchVisionWrapper', op='ColorJitter', brightness=0.12549019607843137, saturation=0.5), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='RandomChoiceResize', scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800), (1333, 832), (1333, 864), (1333, 896)], keep_ratio=True, clip_object_border=False), # clip the object when outside border dict(type='TextDetRandomCrop', target_size=(640, 640)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict( type='Resize', scale=(1333, 800), keep_ratio=True, clip_object_border=True), dict(type='RandomRotate', max_angle=15), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]model = dict( det_head=dict( postprocessor=dict( rescale_fields=[], # test time: first load annotations then transform ) ))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='RandomChoiceResize', scales=[(1333, 704), (1333, 736), (1333, 768), (1333, 800), (1333, 832), (1333, 864), (1333, 896)], keep_ratio=True, clip_object_border=False), # clip the object when outside border dict(type='ChannelShuffle', prob=0.2), dict(type='GaussianBlur', blur_limit=(3, 7), prob=0.5), dict(type='mmdet.PhotoMetricDistortion'), dict(type='TextDetRandomCrop', target_size=(640, 640)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='Resize', scale=(1333, 800), keep_ratio=True, clip_object_border=True), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict( type='TorchVisionWrapper', op='ColorJitter', brightness=0.12549019607843137, saturation=0.5), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='MultiScaleResizeShorterSide', fixed_longer_side=2000, shorter_side_ratio=(0.8, 1.2), clip_object_border=True), # clip the object when outside border dict(type='RatioAwareCrop', crop_ratio=(0.7, 0.5)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict( type='Resize', scale=(1600, 1600), keep_ratio=True, clip_object_border=False), dict(type='RandomRotate', max_angle=15), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]model = dict( det_head=dict( postprocessor=dict( rescale_fields=[], # test time: first load annotations then transform ) ))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849train_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='LoadOCRAnnotations', with_bbox=False, with_polygon=True, with_label=True), dict( type='TorchVisionWrapper', op='ColorJitter', brightness=0.12549019607843137, saturation=0.5), dict(type='RandomFlip', prob=0.5, direction=['horizontal', 'vertical']), # both direction dict( type='RandomRotate', max_angle=10 # [-10, 10] ), dict( type='MultiScaleResizeShorterSide', fixed_longer_side=2000, shorter_side_ratio=(0.8, 1.2), clip_object_border=True), # clip the object when outside border dict(type='RatioAwareCrop', crop_ratio=(0.7, 0.5)), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_shape'))]test_pipeline = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='Resize', scale=(1600, 1600), keep_ratio=True, clip_object_border=False), dict( type='LoadOCRAnnotations', with_polygon=True, with_bbox=False, with_label=True), dict(type='PadDivisor', size_divisor=32), # PadDivisor must placed at last! dict( type='PackTextDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor', 'valid_shape', 'instances'))]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889_base_ = [ '_base_db_seghist_resnet50-dcnv2_fpnc.py', './pipeline/seghist_pipeline_basic.py', '../_base_/textdet_runtime.py', '../_base_/datasets/iacc2022_chdac.py']
# dataset settingstrain_list = _base_.train_listtest_list = _base_.test_listval_list = _base_.val_list
train_dataloader = dict( batch_size=8, num_workers=8, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), dataset=dict( type='ConcatDataset', datasets=train_list, verify_meta=False, pipeline=_base_.train_pipeline))
test_dataloader = dict( batch_size=1, num_workers=1, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=test_list, verify_meta=False, pipeline=_base_.test_pipeline))
val_dataloader = dict( batch_size=1, num_workers=1, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=val_list, verify_meta=False, pipeline=_base_.test_pipeline))
auto_scale_lr = dict(base_batch_size=16)
test_evaluator = [dict(type='HmeanIOUMetric', pred_score_thrs=dict(start=0.6, stop=1.0, step=0.05), prefix='Iacc', match_iou_thr=0.5)]val_evaluator = test_evaluator
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=200, val_interval=5)default_hooks = dict( checkpoint=dict(type='CheckpointHook', interval=5))
val_cfg = dict(type='ValLoop')test_cfg = dict(type='TestLoop')
param_scheduler = [dict(type='ReduceOnPlateauLR', rule='greater', monitor='Iacc/recall', factor=0.3, patience=1, threshold=1e-4)] # use arg last_step when resuming optim!'''#param_scheduler = dict(# type='MultiStepLR', by_epoch=True, milestones=[80, 128], gamma=0.1)
custom_imports = dict( imports=['seghist'], # not support relative import allow_failed_imports=False)
optim_wrapper = dict( type='AmpOptimWrapper',<<<<<<< HEAD optimizer=dict(type='AdamW', lr=1e-4))
#resume = False#load_from = './work_dirs_icdar2019/pse-seghist/epoch_600.pth'======= optimizer=dict(type='AdamW', lr=1e-4)) # 1e-3
#resume = Falseload_from = './work_dirs_chdac/seghist/final_9712.pth'>>>>>>> origin/main123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475_base_ = [ '_base_seghist_resnet50-dcnv2_fpnc.py', './pipeline/seghist_pipeline_largescale.py', '../_base_/textdet_runtime.py', '../_base_/datasets/iacc2022_chdac.py', '../_base_/schedules/schedule_adam_600e.py',]
# dataset settingstrain_list = _base_.train_listtest_list = _base_.test_listval_list = _base_.val_list
train_dataloader = dict( batch_size=8, num_workers=4, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), dataset=dict( type='ConcatDataset', datasets=train_list, pipeline=_base_.train_pipeline))
test_dataloader = dict( batch_size=4, num_workers=4, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=test_list, pipeline=_base_.test_pipeline))
val_dataloader = dict( batch_size=4, num_workers=4, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=val_list, pipeline=_base_.test_pipeline))
test_dataloader = val_dataloader
auto_scale_lr = dict(base_batch_size=16) # 对不同大小的batch_size应用不同的系数,但是设置学习率可以根据base_batch设置
val_evaluator = [dict(type='HmeanIOUMetric', pred_score_thrs=dict(start=0.6, stop=1.0, step=0.1))]test_evaluator = val_evaluator
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=200, val_interval=10)
'''param_scheduler = dict( type='MultiStepLR', by_epoch=True, milestones=[50, 125], gamma=0.1)'''param_scheduler = [dict(type='LinearLR', start_factor=1e-5, by_epoch=False, begin=0, end=125), dict(type='ReduceOnPlateauLR', rule='greater', factor=0.33, patience=1, threshold=1e-4)] # use arg last_step when resuming optim!
custom_imports = dict( imports=['seghist'], # not support relative import allow_failed_imports=False)
optim_wrapper = dict( type='OptimWrapper', optimizer=dict(type='AdamW', lr=1e-3))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667_base_ = [ '_base_seghist_resnet50-dcnv2_fpnc.py', './pipeline/seghist_pipeline_basic.py', '../_base_/textdet_runtime.py', '../_base_/datasets/iacc2022_chdac_toy.py']
# dataset settingstrain_list = _base_.train_listtest_list = _base_.test_listval_list = _base_.val_list
train_dataloader = dict( batch_size=8, num_workers=4, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), dataset=dict( type='ConcatDataset', datasets=train_list, pipeline=_base_.train_pipeline))
test_dataloader = dict( batch_size=4, num_workers=4, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=test_list, pipeline=_base_.test_pipeline))
val_dataloader = dict( batch_size=4, num_workers=4, persistent_workers=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=dict( type='ConcatDataset', datasets=val_list, pipeline=_base_.test_pipeline))
test_dataloader = val_dataloader
auto_scale_lr = dict(base_batch_size=16) # 对不同大小的batch_size应用不同的系数,但是设置学习率可以根据base_batch设置
val_evaluator = [dict(type='HmeanIOUMetric', pred_score_thrs=dict(start=0.6, stop=1.0, step=0.1))]test_evaluator = val_evaluator
param_scheduler = dict( type='MultiStepLR', by_epoch=True, milestones=[50, 125], gamma=0.1)
custom_imports = dict( imports=['seghist'], # not support relative import allow_failed_imports=False)
optim_wrapper = dict( type='OptimWrapper', optimizer=dict(type='AdamW', lr=0.001), accumulative_counts=4)
train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=1)
val_cfg = dict(type='ValLoop')test_cfg = dict(type='TestLoop')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198name: openmmlabchannels: - conda-forge - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - asttokens=2.2.1=pyhd8ed1ab_0 - backcall=0.2.0=pyh9f0ad1d_0 - backports=1.0=pyhd8ed1ab_3 - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0 - ca-certificates=2022.12.7=ha878542_0 - certifi=2022.12.7=pyhd8ed1ab_0 - debugpy=1.5.1=py38h295c915_0 - decorator=5.1.1=pyhd8ed1ab_0 - entrypoints=0.4=pyhd8ed1ab_0 - executing=1.2.0=pyhd8ed1ab_0 - ipykernel=6.15.0=pyh210e3f2_0 - ipython=8.11.0=pyh41d4057_0 - jedi=0.18.2=pyhd8ed1ab_0 - jupyter_client=7.0.6=pyhd8ed1ab_0 - jupyter_core=5.2.0=py38h578d9bd_0 - ld_impl_linux-64=2.38=h1181459_1 - libffi=3.4.2=h6a678d5_6 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libsodium=1.0.18=h36c2ea0_1 - libstdcxx-ng=11.2.0=h1234567_1 - matplotlib-inline=0.1.6=pyhd8ed1ab_0 - ncurses=6.4=h6a678d5_0 - nest-asyncio=1.5.6=pyhd8ed1ab_0 - openssl=1.1.1t=h7f8727e_0 - packaging=23.0=pyhd8ed1ab_0 - parso=0.8.3=pyhd8ed1ab_0 - pexpect=4.8.0=pyh1a96a4e_2 - pickleshare=0.7.5=py_1003 - pip=22.3.1=py38h06a4308_0 - prompt-toolkit=3.0.38=pyha770c72_0 - prompt_toolkit=3.0.38=hd8ed1ab_0 - psutil=5.9.0=py38h5eee18b_0 - ptyprocess=0.7.0=pyhd3deb0d_0 - pure_eval=0.2.2=pyhd8ed1ab_0 - pygments=2.14.0=pyhd8ed1ab_0 - python=3.8.16=h7a1cb2a_2 - python-dateutil=2.8.2=pyhd8ed1ab_0 - python_abi=3.8=2_cp38 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py38h06a4308_0 - six=1.16.0=pyh6c4a22f_0 - sqlite=3.40.1=h5082296_0 - stack_data=0.6.2=pyhd8ed1ab_0 - tk=8.6.12=h1ccaba5_0 - traitlets=5.9.0=pyhd8ed1ab_0 - typing-extensions=4.5.0=hd8ed1ab_0 - typing_extensions=4.5.0=pyha770c72_0 - wcwidth=0.2.6=pyhd8ed1ab_0 - wheel=0.38.4=py38h06a4308_0 - xz=5.2.10=h5eee18b_1 - zeromq=4.3.4=h9c3ff4c_1 - zlib=1.2.13=h5eee18b_0 - pip: - absl-py==1.4.0 - addict==2.4.0 - albumentations==1.3.1 - asynctest==0.13.0 - attrs==22.2.0 - beautifulsoup4==4.11.2 - bleach==6.0.0 - blessed==1.20.0 - cachetools==5.3.0 - charset-normalizer==3.0.1 - click==8.1.3 - codecov==2.1.12 - colorama==0.4.6 - contourpy==1.0.7 - coverage==7.2.0 - cycler==0.11.0 - defusedxml==0.7.1 - einops==0.8.0 - exceptiongroup==1.1.0 - fastjsonschema==2.16.2 - filelock==3.14.0 - flake8==6.0.0 - flask==2.2.5 - fonttools==4.38.0 - fsspec==2024.6.0 - google-auth==2.16.1 - google-auth-oauthlib==0.4.6 - gpustat==1.1.1 - grpcio==1.51.3 - huggingface-hub==0.23.3 - idna==3.4 - imageio==2.25.1 - imgaug==0.4.0 - importlib-metadata==6.0.0 - importlib-resources==5.12.0 - iniconfig==2.0.0 - interrogate==1.5.0 - isort==5.12.0 - itsdangerous==2.1.2 - jinja2==3.1.2 - joblib==1.3.2 - jsonschema==4.17.3 - jupyter-client==8.0.3 - jupyterlab-pygments==0.2.2 - kiwisolver==1.4.4 - kwarray==0.6.9 - lanms-neo==1.0.2 - levenshtein==0.25.1 - lmdb==1.4.0 - lxml==5.1.0 - markdown==3.4.1 - markdown-it-py==2.2.0 - markupsafe==2.1.2 - mat4py==0.6.0 - matplotlib==3.7.0 - mccabe==0.7.0 - mdurl==0.1.2 - mistune==2.0.5 - mmcv==2.0.1 - mmdet==3.0.0 - mmengine==0.10.4 - mmocr==1.0.0rc5 - model-index==0.1.11 - modelindex==0.0.2 - nbclient==0.7.2 - nbconvert==7.2.9 - nbformat==5.7.3 - networkx==3.0 - numpy==1.24.4 - nvidia-ml-py==12.535.133 - oauthlib==3.2.2 - opencc==1.1.2 - opencv-python==4.7.0.72 - openmim==0.3.6 - ordered-set==4.1.0 - pandas==1.5.3 - pandocfilters==1.5.0 - parameterized==0.8.1 - pillow==9.4.0 - pkgutil-resolve-name==1.3.10 - platformdirs==3.0.0 - pluggy==1.0.0 - protobuf==4.22.0 - py==1.11.0 - pyasn1==0.4.8 - pyasn1-modules==0.2.8 - pyclipper==1.3.0.post4 - pycocotools==2.0.6 - pycodestyle==2.10.0 - pyflakes==3.0.1 - pyparsing==3.0.9 - pyrsistent==0.19.3 - pytest==7.2.1 - pytest-cov==4.0.0 - pytest-runner==6.0.0 - pytz==2022.7.1 - pywavelets==1.4.1 - pyyaml==6.0 - pyzmq==25.0.0 - qudida==0.0.4 - rapidfuzz==3.9.0 - requests==2.28.2 - requests-oauthlib==1.3.1 - rich==13.3.1 - rsa==4.9 - safetensors==0.4.3 - scikit-image==0.19.3 - scikit-learn==1.3.2 - scipy==1.10.1 - seaborn==0.13.2 - shapely==2.0.2 - soupsieve==2.4 - tabulate==0.9.0 - tensorboard==2.12.0 - tensorboard-data-server==0.7.0 - tensorboard-plugin-wit==1.8.1 - termcolor==2.2.0 - terminaltables==3.1.10 - threadpoolctl==3.2.0 - tifffile==2023.2.3 - tinycss2==1.2.1 - toml==0.10.2 - tomli==2.0.1 - torch==1.12.1+cu102 - torchaudio==0.12.1+cu102 - torchvision==0.13.1+cu102 - tornado==6.2 - tqdm==4.65.0 - ubelt==1.2.3 - urllib3==1.26.14 - webencodings==0.5.1 - werkzeug==2.2.2 - xdoctest==1.1.1 - yapf==0.32.0 - zipp==3.14.01see https://github.com/LumionHXJ/SegHist12from .datasets import * # NOQAfrom .model import * # NOQA1from .transforms import *12345from .textdet_transforms import MultiScaleResizeShorterSide, RatioAwareCrop, PadDivisorfrom .colorspace import GaussianBlur, ChannelShuffle
__all__ = ['MultiScaleResizeShorterSide', 'RatioAwareCrop', 'PadDivisor', 'GaussianBlur', 'ChannelShuffle']123456789101112131415161718192021222324252627282930from mmocr.registry import TRANSFORMSimport numpy as npimport cv2from mmdet.datasets.transforms import ColorTransform
@TRANSFORMS.register_module()class ChannelShuffle(ColorTransform): def _transform_img(self, results: dict, mag: float) -> None: """Invert the image.""" img = results['img'] channels = img.shape[-1] shuffle_result = np.arange(0, channels) np.random.shuffle(shuffle_result) results['img'] = results['img'][..., shuffle_result]
@TRANSFORMS.register_module()class GaussianBlur(ColorTransform): def __init__(self, blur_limit = (3, 7), sigma = 0, **kwargs): self.blur_limit = blur_limit self.sigma = sigma super().__init__(**kwargs)
def _transform_img(self, results: dict, mag: float) -> None: kernel_size = np.random.choice(np.arange(self.blur_limit[0], self.blur_limit[1] + 2, 2)) results['img'] = cv2.GaussianBlur(results['img'], (kernel_size, kernel_size), self.sigma)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164from typing import Dict, List, Optional, Tuple, Unionfrom mmocr.registry import TRANSFORMSfrom mmocr.datasets.transforms import Resize, TextDetRandomCropimport numpy as npfrom mmcv.transforms.processing import Pad
@TRANSFORMS.register_module()class MultiScaleResizeShorterSide(Resize): """Resize historical image by fixing longer side and using multi-scale strategy to shorter side.
Required Keys:
- img - img_shape - gt_bboxes - gt_polygons
Modified Keys:
- img - img_shape - gt_bboxes - gt_polygons
Added Keys:
- scale - scale_factor - keep_ratio
Args: fixed_longer_side(int): length of longer side (no matter it's height or width) shorter_side_ratio(Tuple[float, float]): range of multi-scale ratio on resizing the shorter side, thus we don't keep the aspect ratio. clip_object_border (bool): Whether to clip the objects outside the border of the image. Defaults to True. """ def __init__(self, fixed_longer_side: int = 2000, shorter_side_ratio: Tuple[float, float] = (0.8, 1.2), clip_object_border: bool = True) -> None: super().__init__(scale_factor=1., keep_ratio=False, clip_object_border=clip_object_border) self.fixed_longer_side = fixed_longer_side self.shorter_side_ratio = shorter_side_ratio @staticmethod def _random_sample_ratio(ratio_range: Tuple[float, float]) -> float: """Private function to randomly sample ratio for shorter side from a tuple.
A ratio will be randomly sampled from the range specified by ``ratio_range``.
Args: ratio_range (tuple[float]): The minimum and maximum ratio to scale the ``scale``.
Returns: float: The targeted ratio of the shorter side to be resized. """
min_ratio, max_ratio = ratio_range assert min_ratio <= max_ratio ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio return ratio def transform(self, results: dict) -> dict: """Transform function to resize images, bounding boxes, semantic segmentation map and keypoints.
NOTE: Scale in mmcv is in (w, h)-style.
Args: results (dict): Result dict from loading pipeline. Returns: dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map', 'gt_keypoints', 'scale', 'scale_factor', 'img_shape', and 'keep_ratio' keys are updated in result dict. """ h, w = results['img'].shape[:2] if h > w: scale_factor = self.fixed_longer_side / h scale_factor *= MultiScaleResizeShorterSide._random_sample_ratio(self.shorter_side_ratio) results['scale'] = (int(w * scale_factor), self.fixed_longer_side) # wh-style else: scale_factor = self.fixed_longer_side / w scale_factor *= MultiScaleResizeShorterSide._random_sample_ratio(self.shorter_side_ratio) results['scale'] = (self.fixed_longer_side, int(h * scale_factor))
self._resize_img(results) self._resize_bboxes(results) self._resize_seg(results) self._resize_keypoints(results) self._resize_polygons(results) return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(fixed_longer_side={self.fixed_longer_side}, ' repr_str += f'shorter_side_ratio={self.shorter_side_ratio}, ' repr_str += f'clip_object_border={self.clip_object_border}), ' return repr_str
@TRANSFORMS.register_module()class RatioAwareCrop(TextDetRandomCrop): """Due to many vertical text lines in historical document, set different different crop ratio for height and width.
Targets size will be computed dynamically.
NOTE: crop ratio in hw-style but target_size should in wh-style
Required Keys:
- img - gt_polygons - gt_bboxes - gt_bboxes_labels - gt_ignored
Modified Keys:
- img - img_shape - gt_polygons - gt_bboxes - gt_bboxes_labels - gt_ignored
Args: crop_ratio (Tuple[float, float] or float): ratio for height and width. i.e. crop_ratio is in hw-style positive_sample_ratio (float): The probability of sampling regions that go through text regions. Defaults to 5. / 8. """ def __init__(self, crop_ratio: Tuple[float, float] or float = (0.7, 0.5), # h, w positive_sample_ratio: float = 5.0 / 8.0) -> None: super().__init__(target_size=None, positive_sample_ratio=positive_sample_ratio) if isinstance(crop_ratio, float): self.crop_ratio = (crop_ratio, crop_ratio) else: self.crop_ratio = crop_ratio
def transform(self, results: Dict) -> Dict: self.target_size = (int(results['img'].shape[0] * self.crop_ratio[0]), int(results['img'].shape[1] * self.crop_ratio[1]))[::-1] return super().transform(results)
@TRANSFORMS.register_module()class PadDivisor(Pad): def transform(self, results: dict) -> dict: results['valid_shape'] = results['img_shape'] return super().transform(results)12345678910from .heads.seghist_heads import DBSegHistHead, PANSegHistHead, SegHistHeadfrom .postprocessor.iedp import IterExpandPostprocessorfrom .module_loss.tks import SegHistModuleLoss, TKSModuleLossfrom .module_loss.db_tks import DBTKSModuleLossfrom .module_loss.pan_tks import PANTKSModuleLossfrom .module_loss.pse_tks import PSETKSModuleLoss
__all__ = ['SegHistModuleLoss', 'DBSegHistHead', 'IterExpandPostprocessor', 'DBTKSModuleLoss', 'PANTKSModuleLoss', 'PSETKSModuleLoss', 'PANSegHistHead', 'SegHistHead', 'TKSModuleLoss']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280from typing import Dict, List, Optional, Tuple, Union
import torchimport torch.nn as nnfrom torch import Tensor
from mmcv.cnn import ConvModulefrom mmengine.model import BaseModulefrom mmdet.models.utils import multi_applyfrom mmocr.models.textdet.heads import BaseTextDetHead, DBHeadfrom mmocr.registry import MODELSfrom mmocr.structures import TextDetDataSample
from seghist.model.layer.layout_enhanced_block import LayoutEnhancedBlock
@MODELS.register_module()class SegHistHead(BaseModule): def __init__(self, in_channels: int, num_blocks: int, shallow_channels: int, embedding_channels: int, output_channels: int = 1, num_query: int = 6, bridge_heads: int = 4, former_heads: int = 8, with_bias: bool = True, with_sigmoid: bool = True, use_dyrelu: bool = True, dyrelu_mode: str = 'shared', init_cfg: Optional[Union[Dict, List[Dict]]] = [ dict(type='Kaiming', layer='Conv'), dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4) ]): super().__init__(init_cfg) self.conv1 = ConvModule(in_channels, shallow_channels, 3, padding=1, bias=with_bias, norm_cfg=dict(type='BN')) bottleneck_channels = shallow_channels // 4 # 128 / 4 = 32 bottleneck_groups = bottleneck_channels // 4 # 32 / 4 = 8 if num_blocks == 0: self.lem = None else: self.lem = nn.Sequential(*[LayoutEnhancedBlock(in_channels=shallow_channels, bottleneck_channels=bottleneck_channels, bottleneck_group=bottleneck_groups, embedding_channels=embedding_channels, bridge_heads=bridge_heads, former_heads=former_heads, use_dyrelu=use_dyrelu, dyrelu_mode=dyrelu_mode, with_bias=with_bias ) for _ in range(num_blocks)]) self.query = nn.Parameter(torch.randn(num_query, embedding_channels)) self.with_sigmoid = with_sigmoid self.sigmoid = nn.Sigmoid() self.upconv = nn.Sequential( nn.ConvTranspose2d(shallow_channels, shallow_channels // 4, 2, 2), nn.BatchNorm2d(shallow_channels // 4), nn.ReLU(), nn.ConvTranspose2d(shallow_channels // 4, output_channels, 2, 2) ) self.num_query= num_query self.embedding_channels = embedding_channels def forward(self, img: Tensor, data_samples: Optional[List[TextDetDataSample]], mode: str = 'predict') -> Tuple[Tensor, Tensor, Tensor]: # N, H, W prob_logits = self.forward_pass(img).squeeze(1) prob_map = self.sigmoid(prob_logits) if mode == 'predict': return prob_map return prob_logits def forward_pass(self, x, mask=None): bs = x.size()[0] x = self.conv1(x) if self.lem is not None: x, _, _ = self.lem((x, self.query.expand(bs, self.num_query, self.embedding_channels), mask)) x = self.upconv(x) if self.with_sigmoid: x = self.sigmoid(x) return x # return prob map
@MODELS.register_module()class DBSegHistHead(DBHead): def __init__(self, in_channels: int, num_blocks: int, shallow_channels: int, output_channels: int = 1, num_query: int = 8, embedding_channels: int = 128, bridge_heads: int = 4, former_heads: int = 8, use_dyrelu: bool = True, dyrelu_mode: str = 'awared', with_bias: bool = True, with_m2f_mask: bool = True, module_loss: Dict = None, postprocessor: Dict = None, init_cfg: Optional[Union[Dict, List[Dict]]] = [ dict(type='Kaiming', layer='Conv'), dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4) ] ) -> None: BaseTextDetHead.__init__(self, module_loss=module_loss, postprocessor=postprocessor, init_cfg=init_cfg) # binarization(logit in losses) self.binarize = SegHistHead(in_channels=in_channels, num_blocks=num_blocks, shallow_channels=shallow_channels, output_channels=output_channels, num_query=num_query, embedding_channels=embedding_channels, bridge_heads=bridge_heads, former_heads=former_heads, with_bias=with_bias, use_dyrelu=use_dyrelu, dyrelu_mode=dyrelu_mode, with_sigmoid=False, init_cfg=init_cfg) self.sigmoid = nn.Sigmoid() # threshold: no separation in threshold self.threshold = SegHistHead(in_channels=in_channels, num_blocks=num_blocks, shallow_channels=shallow_channels, output_channels=output_channels, num_query=num_query, embedding_channels=embedding_channels, bridge_heads=bridge_heads, former_heads=former_heads, with_bias=with_bias, use_dyrelu=use_dyrelu, dyrelu_mode=dyrelu_mode, with_sigmoid=True, init_cfg=init_cfg) self.with_m2f_mask = with_m2f_mask def generate_masks(self, data_samples: List[TextDetDataSample]): '''Generate mask for M2F(mobile2former), mask = 0 means masking a place. ''' masks_h, masks_w = multi_apply(self._get_mask_single, data_samples) masks_h = torch.cat(masks_h, dim=0) # N, H masks_w = torch.cat(masks_w, dim=0) # N, W return torch.cat([masks_h, masks_w], dim=1) # N, H+W def _get_mask_single(self, data_sample: TextDetDataSample): mask_h = torch.ones(data_sample.batch_input_shape[0] // 4) mask_w = torch.ones(data_sample.batch_input_shape[1] // 4) # H, W mask_h[data_sample.valid_shape[0] // 4:] = 0 mask_w[data_sample.valid_shape[1] // 4:] = 0 return mask_h.unsqueeze(0), mask_w.unsqueeze(0)
def forward(self, img: Tensor, data_samples: Optional[List[TextDetDataSample]], mode: str = 'predict') -> Tuple[Tensor, Tensor, Tensor]: """ Args: img (Tensor): Shape :math:`(N, C, H, W)`. data_samples (list[TextDetDataSample], optional): A list of data samples. Defaults to None. mode (str): Forward mode. It affects the return values. Options are "loss", "predict" and "both". Defaults to "predict".
- ``loss``: Run the full network and return the prob logits, threshold map and binary map. - ``predict``: Run the binarzation part and return the prob map only. - ``both``: Run the full network and return prob logits, threshold map, binary map and prob map.
Returns: Tensor or tuple(Tensor): Its type depends on ``mode``, read its docstring for details. Each has the shape of :math:`(N, 4H, 4W)`. """ if self.with_m2f_mask: masks = self.generate_masks(data_samples) masks = masks.to(img.device) else: masks = None # N, H, W prob_logits = self.binarize.forward_pass(img, mask=masks).squeeze(1) prob_map = self.sigmoid(prob_logits) if mode == 'predict': return prob_map thr_map = self.threshold.forward_pass(img, mask=masks).squeeze(1) binary_map = self._diff_binarize(prob_map, thr_map, k=50).squeeze(1) if mode == 'loss': return prob_logits, thr_map, binary_map return prob_logits, thr_map, binary_map, prob_map
@MODELS.register_module()class PANSegHistHead(BaseTextDetHead): def __init__(self, in_channels: int, num_blocks: int, shallow_channels: int, output_channels: int = 1, num_query: int = 8, embedding_channels: int = 128, bridge_heads: int = 4, former_heads: int = 8, use_dyrelu: bool = True, dyrelu_mode: str = 'shared', with_bias: bool = True, with_m2f_mask: bool = True, module_loss: Dict = None, postprocessor: Dict = None, init_cfg: Optional[Union[Dict, List[Dict]]] = [ dict(type='Kaiming', layer='Conv'), dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4) ] ) -> None: super().__init__(module_loss=module_loss, postprocessor=postprocessor, init_cfg=init_cfg) # binarization(logit in losses) self.pred = SegHistHead(in_channels=in_channels, num_blocks=num_blocks, shallow_channels=shallow_channels, output_channels=output_channels, num_query=num_query, embedding_channels=embedding_channels, bridge_heads=bridge_heads, former_heads=former_heads, with_bias=with_bias, use_dyrelu=use_dyrelu, dyrelu_mode=dyrelu_mode, with_sigmoid=False, init_cfg=init_cfg) self.with_m2f_mask = with_m2f_mask def generate_masks(self, data_samples: List[TextDetDataSample]): '''Generate mask for M2F(mobile2former), mask = 0 means masking a place. ''' masks_h, masks_w = multi_apply(self._get_mask_single, data_samples) masks_h = torch.cat(masks_h, dim=0) # N, H masks_w = torch.cat(masks_w, dim=0) # N, W return torch.cat([masks_h, masks_w], dim=1) # N, H+W def _get_mask_single(self, data_sample: TextDetDataSample): mask_h = torch.ones(data_sample.batch_input_shape[0] // 4) mask_w = torch.ones(data_sample.batch_input_shape[1] // 4) # H, W mask_h[data_sample.valid_shape[0] // 4:] = 0 mask_w[data_sample.valid_shape[1] // 4:] = 0 return mask_h.unsqueeze(0), mask_w.unsqueeze(0)
def forward(self, img: Tensor, data_samples: Optional[List[TextDetDataSample]] ) -> Tuple[Tensor, Tensor, Tensor]: if self.with_m2f_mask: masks = self.generate_masks(data_samples) masks = masks.to(img.device) else: masks = None # N, H, W outputs = self.pred.forward_pass(img, mask=masks) return outputs12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import torchfrom torch import Tensor, nn
class DyReLU(nn.Module): """Modified from PaddleViT.
Params Info: in_channels: input feature map channels embed_dims: input token embed_dims k: the number of parameters is in Dynamic ReLU coefs: the init value of coefficient parameters consts: the init value of constant parameters reduce: the mlp hidden scale, means 1/reduce = mlp_ratio """ def __init__(self, in_channels, embed_dims, k=2, # a_1, a_2 coef, b_1, b_2 bias coefs=[1.0, 0.5], # coef init value consts=[1.0, 0.0], # const init value reduce=4, dropout=0.1, mode='shared'): super().__init__() assert mode in ['shared', 'awared'] self.mode = mode
self.embed_dims = embed_dims self.in_channels = in_channels self.k = k
self.mid_channels = 2 * k * in_channels
# 4 values # a_k = alpha_k + coef_k*x, 2 # b_k = belta_k + coef_k*x, 2 self.coef = nn.Parameter(torch.tensor([coefs[0]]*k + [coefs[1]]*k)) self.coef.requires_grad = False self.const = nn.Parameter(torch.tensor([consts[0]] + [consts[1]]*(2*k-1))) self.const.requires_grad = False
self.project = nn.Sequential( nn.Linear(embed_dims, int(embed_dims/reduce)), nn.GELU(), nn.Dropout(dropout), nn.Linear(int(embed_dims/reduce), self.mid_channels), nn.GELU(), nn.Dropout(dropout), nn.LayerNorm(self.mid_channels) )
def forward(self, feature_map:Tensor, tokens: Tensor, attn_map: Tensor): ''' Args: attn_score(Tensor): attn map of mobile2former before softmax operation, reusing for saving computation, with shape: (B, heads, H*W, M). ''' B, M, D = tokens.size() B, C, H, W = feature_map.size() if self.mode == 'shared': # shared mode only pick out first token dy_params = self.project(tokens[:, 0]) # B, 2kC dy_params = dy_params.view(B, self.in_channels, 2*self.k) # B, C, 2*k elif self.mode == 'awared': # part 2: deal with decoupled attention map, keeping prob. attributes attn_map = torch.mean(attn_map, dim=1) # B, HW, M attn_map = attn_map.view(B, H, W, M)
# part 3: projecting tokens dy_params = self.project(tokens).unsqueeze(1) # B, 1, M, 2kC
# part 4: compute dynamic parameters for spatial pixel dy_params = torch.matmul(attn_map, dy_params).view(B, H, W, self.in_channels, 2*self.k) # B, H, W, C, 2k dy_params = dy_params.permute(1, 2, 0, 3, 4).contiguous() # H, W, B, C, 2k
dy_init_params = dy_params * self.coef + self.const f = feature_map.permute(2, 3, 0, 1).contiguous().unsqueeze(-1) # H, W, B, C, 1
# output shape: H, W, B, C, k output = f * dy_init_params[..., :self.k] + dy_init_params[..., self.k:] output = torch.max(output, dim=-1)[0] # H, W, B, C(fetch out max values) output = output.permute(2, 3, 0, 1).contiguous() # B, C, H, W
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292from typing import Union, List, Tuple
import torchfrom torch import Tensor, nn
from mmcv.cnn import ConvModulefrom mmengine.model import BaseModulefrom mmocr.models.common.layers import TFEncoderLayerfrom mmocr.models.common.modules import ScaledDotProductAttention
from seghist.model.layer.dyrelu import DyReLU
class Local(nn.Module): def __init__(self, in_channels, embedding_channels, bottleneck_channels, bottleneck_group, n_heads, use_dyrelu=True, dropout=0.1, dyrelu_mode='awared', with_bias=True): super().__init__() self.bottleneck_channels = bottleneck_channels self.n_heads = n_heads
self.pointwise_conv = nn.Conv2d(in_channels, bottleneck_channels, kernel_size=1) self.group_conv = nn.Conv2d(bottleneck_channels, bottleneck_channels, kernel_size=7, padding=3, groups=bottleneck_group) self.pointwise_norm = nn.BatchNorm2d(bottleneck_channels) self.group_norm = nn.BatchNorm2d(bottleneck_channels)
self.linear_k = nn.Linear(embedding_channels, bottleneck_channels, bias=with_bias) self.linear_v = nn.Linear(embedding_channels, bottleneck_channels, bias=with_bias) self.pre_attn = ScaledDotProductAttention((self.bottleneck_channels / n_heads)**0.5, dropout) self.use_dyrelu = use_dyrelu if use_dyrelu: self.act1 = DyReLU(bottleneck_channels, embedding_channels, mode=dyrelu_mode) self.act2 = DyReLU(bottleneck_channels, embedding_channels, mode=dyrelu_mode) else: self.act1 = nn.ReLU() self.act2 = nn.ReLU()
def forward(self, x, z, mask=None): """x: N, C, H, W z: N, M, d """ x = self.pointwise_conv(x) x = self.pointwise_norm(x)
# compute attention map for multiple uses! bs, num_queries, _ = z.size() z_k = self.linear_k(z).view(bs, num_queries, self.n_heads, self.bottleneck_channels // self.n_heads).transpose(1, 2).contiguous() z_v = self.linear_v(z).view(bs, num_queries, self.n_heads, self.bottleneck_channels // self.n_heads).transpose(1, 2).contiguous() x_q = x.view(bs, self.n_heads, self.bottleneck_channels//self.n_heads, -1).transpose(2, 3).contiguous() # N, h, HW, C_b/h attn_out, attn_map = self.pre_attn(x_q, z_k, z_v, mask)
if self.use_dyrelu: x = self.act1(x, z, attn_map) else: x = self.act1(x)
x = self.group_conv(x) x = self.group_norm(x) if self.use_dyrelu: x = self.act2(x, z, attn_map) else: x = self.act2(x)
return x, attn_out # N, h, HW, C//h
class Local2Layout(nn.Module): def __init__(self, n_heads, in_channels, embedding_channels, dropout=0.1, with_bias=True) -> None: super().__init__() assert in_channels % n_heads == 0, 'n_heads must divide in_channels' assert in_channels == embedding_channels, \ 'input channels should be same as embed channels for simplicity' self.n_heads = n_heads self.in_channels = in_channels self.embedding_channels = embedding_channels
self.norm1 = nn.LayerNorm(embedding_channels) self.norm2 = nn.LayerNorm(in_channels) self.linear_q = nn.Linear(self.embedding_channels, self.in_channels, bias=with_bias) self.ffn = nn.Sequential( nn.Linear(self.in_channels, self.in_channels // 2, bias=with_bias), nn.GELU(), nn.Linear(self.in_channels // 2, self.embedding_channels, bias=with_bias), nn.Dropout(dropout) )
self.attention = ScaledDotProductAttention((self.in_channels / n_heads)**0.5, dropout)
def forward(self, x: Tensor, z: Tensor, mask=None): ''' x: N, H+W, C z: N, M, d M: N, H+W ''' bs, length, _ = x.shape num_queries = z.shape[1] residue = z
# part 1: pre norm z = self.norm1(z)
# part 2: linear z & shape to bs, heads, H/W, C/heads z: Tensor = self.linear_q(z) # N, M, C z = z.view(bs, num_queries, self.n_heads, self.in_channels // self.n_heads).transpose(1, 2).contiguous() x = x.view(bs, length, self.n_heads, self.in_channels // self.n_heads).transpose(1, 2).contiguous()
# part 3: attend mask(N, 1(h), 1(M), H+W) if mask is not None: if mask.dim() == 3: mask = mask.unsqueeze(1) elif mask.dim() == 2: mask = mask.unsqueeze(1).unsqueeze(1)
# part 4: attention attn_out, _ = self.attention(z, x, x, mask) # N, h, M, C/h attn_out = attn_out.transpose(1, 2).contiguous().view(bs, num_queries, -1) # N, M, C residue = residue + attn_out # N, M, C
# part 5: projection(output = MHA's output) z = self.norm2(residue) z = self.ffn(z) # N, M, d
# part 6: residue link z = z + residue
return z
class Layout2Local(nn.Module): def __init__(self, n_heads, in_channels, embedding_channels, dropout=0.1, with_bias=True) -> None: super().__init__() assert in_channels % n_heads == 0, 'n_heads must divide in_channels' self.n_heads = n_heads self.in_channels = in_channels self.embedding_channels = embedding_channels
self.norm2 = nn.LayerNorm(in_channels)
self.ffn = nn.Sequential( nn.Linear(self.in_channels, self.in_channels // 2, bias=with_bias), nn.GELU(), nn.Linear(self.in_channels // 2, self.in_channels, bias=with_bias), nn.Dropout(dropout) )
def forward(self, x: Tensor, attn_f2m: Tensor): ''' x: N, HW, C attn_f2m: N, h, HW, C//h mask: N, H, W ''' bs, length, _ = x.shape
# part 1: add precomputed attention attn_out = attn_f2m.transpose(1, 2).contiguous().view(bs, length, -1) # N, HW, C residue = x + attn_out
# part 2: norm+ffn x = self.norm2(residue) x = self.ffn(x)
# part 3: residue link, return N, HW, C x = x + residue return x
class LayoutEnhancedBlock(BaseModule): def __init__(self, in_channels, bottleneck_channels, bottleneck_group, embedding_channels=256, bridge_heads=4, former_heads=8, use_dyrelu=True, dyrelu_mode='awared', with_bias=True, init_cfg: Union[dict, List[dict], None] = [ dict(type='Kaiming', layer='Conv'), dict(type='Constant', layer='BatchNorm', val=1., bias=1e-4) ]): super().__init__(init_cfg)
self.in_channels = in_channels self.bottleneck_channels = bottleneck_channels self.embedding_channels = embedding_channels self.bridge_heads = bridge_heads self.former_heads = former_heads self.bottleneck_group = bottleneck_group self.local = Local(in_channels=in_channels, embedding_channels=embedding_channels, bottleneck_channels=bottleneck_channels, bottleneck_group=bottleneck_group, use_dyrelu=use_dyrelu, n_heads=bridge_heads, dyrelu_mode=dyrelu_mode, with_bias=with_bias) self.dyrelu_mode = dyrelu_mode if use_dyrelu else 'none'
self.out_conv = ConvModule(bottleneck_channels, in_channels, kernel_size=1, bias=with_bias, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU')) self.pooling = nn.AdaptiveMaxPool1d(1) self.local2layout = Local2Layout(n_heads=bridge_heads, in_channels=in_channels, embedding_channels=embedding_channels, with_bias=with_bias) self.layout2local = Layout2Local(n_heads=bridge_heads, in_channels=bottleneck_channels, embedding_channels=embedding_channels, with_bias=with_bias) self.layout = TFEncoderLayer(d_model=embedding_channels, d_inner=embedding_channels // 2, d_k=embedding_channels // former_heads, d_v=embedding_channels // former_heads, qkv_bias=with_bias, n_head=former_heads) # using GELU in FFN
def forward(self, input: Tuple): ''' x: N, C, H, W z: N, M, d masks: N, H, W ''' x, z, mask = input # now mask is N, H+W bs, _, h, w = x.size()
# part 2: m2f(need to prepare mask) global_h = self.pooling(x.view(bs, -1, w)).view(bs, -1, h) global_h = global_h.transpose(1,2).contiguous() # N, H, C global_w = self.pooling(x.transpose(2,3).contiguous().view(bs, -1, h)).view(bs, -1, w) global_w = global_w.transpose(1,2).contiguous() # N, W, C global_x = torch.cat([global_h, global_w], dim=1) # N, (H+W), C
z = self.local2layout(global_x, z, mask)
# part 3: Layout z = self.layout(z)
# part 4: Local x_, attn_f2m = self.local(x, z) # contains activation DY-ReLU
# part 5: f2m x_ = self.layout2local(x_.view(bs, self.bottleneck_channels, -1).transpose(1,2).contiguous(), attn_f2m) # x_ is like N, HW, C_bottleneck # part 6: residue link x_ = x_.transpose(1,2).contiguous().view(bs, self.bottleneck_channels, h, w) x = x + self.out_conv(x_)
return x, z, mask # for sequential input123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from typing import Tupleimport copy
import cv2import numpy as npimport torch
from mmocr.registry import MODELSfrom mmocr.models.textdet.module_losses import DBModuleLossfrom mmocr.structures import TextDetDataSample
from seghist.utils import expand_poly, get_distancefrom seghist.model import TKSModuleLoss
@MODELS.register_module()class DBTKSModuleLoss(TKSModuleLoss, DBModuleLoss): def __init__(self, stretch_ratio: float = 2, **kwargs): TKSModuleLoss.__init__(self, stretch_ratio) DBModuleLoss.__init__(self, **kwargs)
def _generate_thr_map(self, img_size: Tuple[int, int], polygons) -> np.ndarray: """Generate threshold map.
Args: img_size (tuple(int)): The image size (h, w) polygons (Sequence[ndarray]): 2-d array, representing all the polygons of the text region.
Returns: tuple:
- thr_map (ndarray): The generated threshold map. - thr_mask (ndarray): The effective mask of threshold map. """ thr_map = np.zeros(img_size, dtype=np.float32) thr_mask = np.zeros(img_size, dtype=np.uint8)
for polygon in polygons: self._draw_border_map(polygon, thr_map, mask=thr_mask, shrink_ratio=self.shrink_ratio, stretch_ratio=self.stretch_ratio) thr_map = thr_map * (self.thr_max - self.thr_min) + self.thr_min
return thr_map, thr_mask def _draw_border_map(self, polygon: np.ndarray, canvas: np.ndarray, shrink_ratio: float, stretch_ratio: float, mask: np.ndarray) -> None: """Generate threshold map for one polygon.
Args: polygon (np.ndarray): The polygon. canvas (np.ndarray): The generated threshold map. mask (np.ndarray): The generated threshold mask. """ # 按照相同加权方法进行扩张(便于之后加权计算thr map) polygon = copy.deepcopy(polygon).reshape(-1, 2) distance = get_distance(polygon, shrink_ratio) expanded_polygon = expand_poly(polygon, shrink_ratio, stretch_ratio) if len(expanded_polygon) == 0: print(f'Padding {polygon} gets {expanded_polygon}') expanded_polygon = polygon.copy().astype(np.int32) else: expanded_polygon = expanded_polygon.reshape(-1, 2).astype(np.int32) x_min = expanded_polygon[:, 0].min() x_max = expanded_polygon[:, 0].max() y_min = expanded_polygon[:, 1].min() y_max = expanded_polygon[:, 1].max()
width = x_max - x_min + 1 height = y_max - y_min + 1
polygon[:, 0] = (polygon[:, 0] - x_min) * stretch_ratio polygon[:, 1] = polygon[:, 1] - y_min
# 构建坐标grid xs = np.broadcast_to( np.linspace(0, width - 1, num=width).reshape(1, width), (height, width)) * stretch_ratio # 横向坐标加权计算 ys = np.broadcast_to( np.linspace(0, height - 1, num=height).reshape(height, 1), (height, width))
# 原polygon的每条边对应一个map,最后取最小距离 distance_map = np.zeros((polygon.shape[0], height, width), dtype=np.float32) # 统计区域内每个点到每一条边的距离 for i in range(polygon.shape[0]): j = (i + 1) % polygon.shape[0] absolute_distance = self._dist_points2line(xs, ys, polygon[i], polygon[j]) # 最后会用 1-distance_map 做thresh distance_map[i] = np.clip(absolute_distance / distance, 0, 1) distance_map = distance_map.min(axis=0) # 每个点的距离由最小距离决定
x_min_valid = min(max(0, x_min), canvas.shape[1] - 1) x_max_valid = min(max(0, x_max), canvas.shape[1] - 1) y_min_valid = min(max(0, y_min), canvas.shape[0] - 1) y_max_valid = min(max(0, y_max), canvas.shape[0] - 1)
if x_min_valid - x_min >= width or y_min_valid - y_min >= height: return
# 位于扩张后多边形区域内的点会被考虑(thr有效) cv2.fillPoly(mask, [expanded_polygon.astype(np.int32)], 1) canvas[y_min_valid:y_max_valid + 1, x_min_valid:x_max_valid + 1] = np.fmax( 1 - distance_map[y_min_valid - y_min: y_max_valid - y_max + height, x_min_valid - x_min: x_max_valid - x_max + width], canvas[y_min_valid:y_max_valid + 1, x_min_valid:x_max_valid + 1]) def _get_target_single(self, data_sample: TextDetDataSample) -> Tuple: """Generate loss target from a data sample. Modified to adapt to batch padding
Args: data_sample (TextDetDataSample): The data sample.
Returns: tuple: A tuple of four tensors as the targets of one prediction. """
gt_shrink, gt_shrink_mask = TKSModuleLoss._get_target_single(self, data_sample) gt_instances = data_sample.gt_instances ignore_flags = gt_instances.ignored # thr mask is only effective around the text area, so there's no need to mask the padding. gt_thr, gt_thr_mask = self._generate_thr_map( data_sample.batch_input_shape, gt_instances[~ignore_flags].polygons)
gt_thr = torch.from_numpy(gt_thr).unsqueeze(0).float() gt_thr_mask = torch.from_numpy(gt_thr_mask).unsqueeze(0).float() return gt_shrink, gt_shrink_mask, gt_thr, gt_thr_mask1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# Copyright (c) OpenMMLab. All rights reserved.from typing import Tuple
import numpy as npimport torch
from mmocr.registry import MODELSfrom mmocr.structures import TextDetDataSamplefrom mmocr.models.textdet.module_losses import PANModuleLoss
from seghist.model import TKSModuleLoss
@MODELS.register_module()class PANTKSModuleLoss(TKSModuleLoss, PANModuleLoss): """PAN generates multiple targets using series of ratios. Rewrite function _get_target_single based on TKS. """ def __init__(self, stretch_ratio: float = 2, **kwargs): TKSModuleLoss.__init__(self, stretch_ratio) PANModuleLoss.__init__(self, **kwargs)
def _get_target_single(self, data_sample: TextDetDataSample ) -> Tuple[torch.Tensor, torch.Tensor]: """Generate loss target from a data sample.
Args: data_sample (TextDetDataSample): The data sample.
Returns: tuple: A tuple of four tensors as the targets of one prediction. """ gt_polygons = data_sample.gt_instances.polygons gt_ignored = data_sample.gt_instances.ignored
gt_kernels = [] for ratio in self.shrink_ratio: gt_kernel, gt_ignored = self._generate_kernels( data_sample.batch_input_shape, gt_polygons, ratio, self.stretch_ratio, ignore_flags=gt_ignored) gt_kernels.append(gt_kernel) gt_polygons_ignored = data_sample.gt_instances[gt_ignored].polygons gt_mask = self._generate_effective_mask(data_sample.batch_input_shape, gt_polygons_ignored) gt_mask[data_sample.valid_shape[0]:data_sample.batch_input_shape[0], data_sample.valid_shape[1]:data_sample.batch_input_shape[1]] = 0
gt_kernels = np.stack(gt_kernels, axis=0) #K, H, W gt_kernels = torch.from_numpy(gt_kernels).float() gt_mask = torch.from_numpy(gt_mask).float() return gt_kernels, gt_mask123456789101112131415from mmocr.registry import MODELSfrom mmocr.models.textdet.module_losses import PSEModuleLoss
from seghist.model import PANTKSModuleLoss
@MODELS.register_module()class PSETKSModuleLoss(PANTKSModuleLoss, PSEModuleLoss): """Almost same from PANTKS, except forward method. """ def __init__(self, stretch_ratio: float = 2, **kwargs): PANTKSModuleLoss.__init__(self, stretch_ratio) PSEModuleLoss.__init__(self, **kwargs)
def forward(self, *args, **kwargs): return PSEModuleLoss.forward(self, *args, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138from typing import Sequence, Tuple, Optional, Dict, Union
import cv2import numpy as npimport torchfrom torch import Tensor
from mmocr.registry import MODELSfrom mmocr.models.textdet.module_losses import SegBasedModuleLossfrom mmocr.structures import TextDetDataSample
from seghist.utils import stretch_kernel
class TKSModuleLoss(SegBasedModuleLoss): """Computing module loss using the Text Kernel Stretching method. Generating targets for a segmentation-based model that only predicts text kernel. Also serves as a subclass for the SegHist implementation of a specific segmentation-based model.
Args: stretch_ratio: Horizontal stretching ratio (s>1). """ def __init__(self, stretch_ratio: float = 2, **kwargs): super().__init__(**kwargs) self.stretch_ratio = stretch_ratio
def _generate_kernels( self, img_size: Tuple[int, int], text_polys: Sequence[np.ndarray], shrink_ratio: float, stretch_ratio: float, ignore_flags: Optional[np.ndarray] = None, ) -> Tuple[np.ndarray, np.ndarray]: """Generate text instance kernels according to a shrink ratio.
Args: img_size (tuple(int, int)): The image size of (height, width). text_polys (Sequence[np.ndarray]): 2D array of text polygons. shrink_ratio (float or int): The shrink ratio of kernel. stretch_ratio (float or int): The stretch ratio of kernel. ignore_flags (torch.BoolTensor, optional): Indicate whether the corresponding text polygon is ignored. Defaults to None.
Returns: tuple(ndarray, ndarray): The text instance kernels of shape (height, width) and updated ignorance flags. """ assert isinstance(img_size, tuple) assert isinstance(shrink_ratio, (float, int))
if ignore_flags is None: ignore_flags = [False for _ in text_polys]
text_kernel = np.zeros(img_size, dtype=np.float32)
for text_ind, poly in enumerate(text_polys): if ignore_flags[text_ind]: continue shrunk_poly = stretch_kernel(poly, shrink_ratio, stretch_ratio) # Split while shrinkage, resulted in empty list. if len(shrunk_poly) == 0: ignore_flags[text_ind] = True continue cv2.fillPoly(text_kernel, [shrunk_poly.astype(np.int32)], 1)
return text_kernel, ignore_flags def _get_target_single(self, data_sample: TextDetDataSample) -> Tuple: """Generate loss target from a data sample. Modified to adapt to batch padding
Args: data_sample (TextDetDataSample): The data sample.
Returns: tuple: A tuple of four tensors as the targets of one prediction. """
gt_instances = data_sample.gt_instances ignore_flags = gt_instances.ignored for idx, polygon in enumerate(gt_instances.polygons): if self._is_poly_invalid(polygon.astype(np.float32)): ignore_flags[idx] = True gt_shrink, ignore_flags = self._generate_kernels( data_sample.batch_input_shape, # adapt to batch input shape gt_instances.polygons, self.shrink_ratio, self.stretch_ratio, ignore_flags=ignore_flags) # Get boolean mask where Trues indicate text instance pixels gt_shrink = gt_shrink > 0
gt_shrink_mask = self._generate_effective_mask( data_sample.batch_input_shape, gt_instances[ignore_flags].polygons) # mask padding area gt_shrink_mask[data_sample.valid_shape[0]:data_sample.batch_input_shape[0], data_sample.valid_shape[1]:data_sample.batch_input_shape[1]] = 0
# to_tensor gt_shrink = torch.from_numpy(gt_shrink).unsqueeze(0).float() gt_shrink_mask = torch.from_numpy(gt_shrink_mask).unsqueeze(0).float() return gt_shrink, gt_shrink_mask
@MODELS.register_module()class SegHistModuleLoss(TKSModuleLoss): def __init__(self, loss_prob: Dict = dict( type='MaskedBalancedBCEWithLogitsLoss'), weight_prob: float = 5., min_sidelength: Union[int, float] = 8) -> None: super().__init__() self.loss_prob = MODELS.build(loss_prob) self.weight_prob = weight_prob self.min_sidelength = min_sidelength
def forward(self, preds: Tuple[Tensor], data_samples: Sequence[TextDetDataSample]) -> Dict:
prob_logits = preds gt_shrinks, gt_shrink_masks = self.get_targets(data_samples) gt_shrinks = gt_shrinks.to(prob_logits.device) gt_shrink_masks = gt_shrink_masks.to(prob_logits.device)
loss_prob = self.loss_prob(prob_logits, gt_shrinks, gt_shrink_masks)
results = dict(loss_prob=self.weight_prob * loss_prob) return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123from typing import Optional
import cv2import numpy as npimport torchfrom torch import Tensorfrom shapely.geometry import Polygon
from mmengine.structures import InstanceDatafrom mmocr.structures import TextDetDataSamplefrom mmocr.registry import MODELSfrom mmocr.models.textdet.postprocessors import DBPostprocessor
from seghist.utils import unstretch_kernel
@MODELS.register_module()class IterExpandPostprocessor(DBPostprocessor): """Implementation for Iterative Expansion Distance Post-Processor.
Args: shrink_ratio: r<1 stretch_ratio: s>=1 min_text_area: min regional area in origin scale. refine: refine or unclip kernel only once. unclip_ratio: u>0, used when refine is false. """ def __init__(self, shrink_ratio: float = 0., stretch_ratio: float = 2.0, min_text_area: int = 200, # area respect to original size refine: bool = True, unclip_ratio: Optional[float] = None, **kwargs): super().__init__(**kwargs) self.stretch_ratio = stretch_ratio self.shrink_ratio = shrink_ratio self.min_text_area = min_text_area self.refine = refine if not refine: assert unclip_ratio > 0, 'must set unclip ratio u when not refine' self.unclip_ratio = unclip_ratio
def get_text_instances(self, prob_map: Tensor, data_sample: TextDetDataSample ) -> TextDetDataSample: """Get text instance predictions of one image.
Args: pred_result (Tensor): DBNet's output ``prob_map`` of shape :math:`(H, W)`. data_sample (TextDetDataSample): Datasample of an image.
Returns: TextDetDataSample: A new DataSample with predictions filled in. Polygons and results are saved in ``TextDetDataSample.pred_instances.polygons``. The confidence scores are saved in ``TextDetDataSample.pred_instances.scores``. """ prob_map = prob_map[..., :data_sample.valid_shape[0], :data_sample.valid_shape[1]]
data_sample.pred_instances = InstanceData() data_sample.pred_instances.polygons = [] data_sample.pred_instances.scores = []
text_mask = prob_map > self.mask_thr
score_map = prob_map.data.cpu().numpy().astype(np.float32) text_mask = text_mask.data.cpu().numpy() * 255 text_mask = text_mask.astype(np.uint8) # to numpy contours, _ = cv2.findContours(text_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, poly in enumerate(contours): if i > self.max_candidates: break epsilon = self.epsilon_ratio * cv2.arcLength(poly, True) approx = cv2.approxPolyDP(poly, epsilon, True) poly_pts = approx.reshape(-1, 2) if poly_pts.shape[0] < 4: continue score = self._get_bbox_score(score_map, poly_pts) if score < self.min_text_score: continue # trying recover kernel in iterative mode try: poly = unstretch_kernel(poly_pts, self.shrink_ratio, self.stretch_ratio, refinement=self.refine, unclip_ratio=self.unclip_ratio) except Exception as e: print(f'Error {e} find when unstretching kernel {poly_pts}.') # If the result polygon does not exist, or it is split into # multiple polygons, skip it. if len(poly) == 0: continue poly = poly.reshape(-1, 2)
if self.text_repr_type == 'quad': rect = cv2.minAreaRect(poly.astype(np.int32)) vertices = cv2.boxPoints(rect) poly = vertices.flatten() if min( rect[1]) >= self.min_text_width else [] elif self.text_repr_type == 'poly': scale = data_sample.scale_factor[0] * data_sample.scale_factor[1] poly = poly.flatten() if Polygon( poly).area / scale > self.min_text_area else []
if len(poly) < 8: poly = np.array([], dtype=np.float32)
if len(poly) > 0: data_sample.pred_instances.polygons.append(poly) data_sample.pred_instances.scores.append(score)
data_sample.pred_instances.scores = torch.FloatTensor( data_sample.pred_instances.scores)
return data_sample12from .poly_utils import *from .image_utils import ImageToolkits.gitattributes+1
.gitignoreAdded+47
LICENSEAdded+202
README.mdAdded+106
config/_base_/datasets/complete_data.pyAdded+152
config/_base_/datasets/iacc2022_chdac.pyAdded+28
config/_base_/datasets/iacc2022_chdac_toy.pyAdded+12
config/_base_/datasets/icdar2019hdrc.pyAdded+30
config/_base_/datasets/mthv2.pyAdded+19
config/_base_/default_runtime.pyAdded+46
config/_base_/schedules/schedule_adam_600e.pyAdded+13
config/_base_/schedules/schedule_sgd_500e.pyAdded+13
config/_base_/textdet_runtime.pyAdded+36
config/baseline/config.pyAdded+96
config/baseline/model/dbnetpp.pyAdded+37
config/baseline/model/psenet.pyAdded+44
config/baseline/pipeline.pyAdded+51
config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.pyAdded+47
config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.pyAdded+44
config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.pyAdded+44
config/seghist/_base_seghist_resnet50-dcnv2_fpnc.pyAdded+48
config/seghist/pipeline/seghist_pipeline_basic.pyAdded+50
config/seghist/pipeline/seghist_pipeline_basic_rotate.pyAdded+58
config/seghist/pipeline/seghist_pipeline_color_jitter.pyAdded+48
config/seghist/pipeline/seghist_pipeline_large_rotate.pyAdded+57
config/seghist/pipeline/seghist_pipeline_largescale.pyAdded+49
config/seghist/seghist_resnet50-dcnv2_fpnc.pyAdded+89
config/seghist/seghist_resnet50-dcnv2_fpnc_large.pyAdded+75
config/seghist/seghist_resnet50-dcnv2_fpnc_toy.pyAdded+67
environment.ymlAdded+198
readme.txtAdded+1
samples/gt1.pngAdded

Large File Pointer Details
- SHA256: a72383f5a996098df47b47bd4e9e4987e78cd6a4dcac946444301c00189a39fc
- Pointer size: 132 Bytes
- Size of remote file: 2.57 MB
samples/gt2.pngAdded

Large File Pointer Details
- SHA256: b81624e7aeed4948efbe47a2e701ea034a805c78e825557a2f3c7eb316e08a6a
- Pointer size: 132 Bytes
- Size of remote file: 2.49 MB
samples/pred1.pngAdded

Large File Pointer Details
- SHA256: 8e2cc2ae1832dbb4a335c8d72b6109773d9039274557fc55a63ce400282b43bf
- Pointer size: 132 Bytes
- Size of remote file: 2.57 MB
samples/pred2.pngAdded

Large File Pointer Details
- SHA256: 070525d284425af3c2ec6f102c3b0ba063daf69632255e4a3dfa7542f5a6b9e0
- Pointer size: 132 Bytes
- Size of remote file: 2.5 MB
seghist/__init__.pyAdded+2
seghist/datasets/__init__.pyAdded+1
seghist/datasets/transforms/__init__.pyAdded+5
seghist/datasets/transforms/colorspace.pyAdded+30
seghist/datasets/transforms/textdet_transforms.pyAdded+164
seghist/model/__init__.pyAdded+10
seghist/model/heads/seghist_heads.pyAdded+280
seghist/model/layer/dyrelu.pyAdded+88
seghist/model/layer/layout_enhanced_block.pyAdded+292
seghist/model/module_loss/db_tks.pyAdded+143
seghist/model/module_loss/pan_tks.pyAdded+53
seghist/model/module_loss/pse_tks.pyAdded+15
seghist/model/module_loss/tks.pyAdded+138
seghist/model/postprocessor/iedp.pyAdded+123
seghist/utils/__init__.pyAdded+2