diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..cc56dc866f0b16803abe94de9e2a6c95ea31c4c5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ *.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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..62cf648949159e879e0694d18927c9733041aa8b --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# 操作系统生成的文件 +.DS_Store +Thumbs.db + +# 日志文件 +*.log + +# Python 编译生成的文件 +*.pyc +*.pyo + +# 虚拟环境 +env/ +venv/ +.venv/ + +# 配置文件 +.env +.env.local +.env.*.local + +# 项目依赖 +.mypy_cache/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml +*.cover + +# 临时文件和目录 +.dist_test/ +*.swp +.idea/ +.vscode/ +*.ipynb + +# 忽略所有目录,不包含 config 和 seghist,同时忽略下面的pycache +*/ +data +!config/ +!config/** +!seghist/ +!seghist/** +!samples/ +!samples/** +**/__pycache__/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..db9ef060bb1667a13da873bd3b68974c8f073cf9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + 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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a97cfc7275fe7bd7d38971ca58e78f722e5471c2 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# (ICDAR 2024) SegHist: A General Segmentation-based Framework for Chinese Historical Document Text Line Detection + +
+ +[![arXiv](https://img.shields.io/badge/Arxiv-2406.15485-A42C25?style=flat&logo=arXiv&logoColor=A42C25)](https://arxiv.org/abs/2406.15485) + +[![GitHub watchers](https://img.shields.io/github/watchers/LumionHXJ/SegHist?style=social)](https://github.com/LumionHXJ/SegHist/watchers) + +[![GitHub stars](https://img.shields.io/github/stars/LumionHXJ/SegHist?style=social)](https://github.com/LumionHXJ/SegHist/stargazers) + +[![Visits Badge](https://badges.pufler.dev/visits/LumionHXJ/SegHist)](https://github.com/LumionHXJ/SegHist) +
+ +**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 | +| --------------------------- | ------------------------------- | +| ![gt1](samples/gt1.png) | ![pred1](samples/pred1.png) | +| ![gt2](samples/gt2.png) | ![pred2](samples/pred2.png) | + +## 📄 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: + +```bash +conda env create -f environment.yml +``` + +Or installing step-by-step: + +```bash +conda create --name openmmlab python=3.8 -y +conda activate openmmlab +conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 -c pytorch +pip install -U openmim +mim 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): + +```bash +python -m torch.distributed.run --nproc_per_node=4 train.py --launcher pytorch --work-dir work_dirs/ config/seghist/seghist_resnet50-dcnv2_fpnc.py +``` + +## 🧠 **Inferencing** + +```bash +python 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. diff --git a/config/_base_/datasets/complete_data.py b/config/_base_/datasets/complete_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2617f3745a060abcecc122b81e5f95108ebc2f16 --- /dev/null +++ b/config/_base_/datasets/complete_data.py @@ -0,0 +1,152 @@ +<<<<<<< HEAD +data_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) + +<<<<<<< HEAD +data_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 +) +# 没有使用mthv2 +train_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_list \ No newline at end of file diff --git a/config/_base_/datasets/iacc2022_chdac.py b/config/_base_/datasets/iacc2022_chdac.py new file mode 100644 index 0000000000000000000000000000000000000000..98967e4c614adee3d284e14a6c7d009374e277b7 --- /dev/null +++ b/config/_base_/datasets/iacc2022_chdac.py @@ -0,0 +1,28 @@ +data_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_list \ No newline at end of file diff --git a/config/_base_/datasets/iacc2022_chdac_toy.py b/config/_base_/datasets/iacc2022_chdac_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3fa5f9ab28ac15bc83659909edd19cf29de313 --- /dev/null +++ b/config/_base_/datasets/iacc2022_chdac_toy.py @@ -0,0 +1,12 @@ +data_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] \ No newline at end of file diff --git a/config/_base_/datasets/icdar2019hdrc.py b/config/_base_/datasets/icdar2019hdrc.py new file mode 100644 index 0000000000000000000000000000000000000000..4e90f3a92b0c36ae1491a0a81d60f24fdb83f4fe --- /dev/null +++ b/config/_base_/datasets/icdar2019hdrc.py @@ -0,0 +1,30 @@ +data_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] \ No newline at end of file diff --git a/config/_base_/datasets/mthv2.py b/config/_base_/datasets/mthv2.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a2c2da0ee3e793e05829a06addb9f19275db06 --- /dev/null +++ b/config/_base_/datasets/mthv2.py @@ -0,0 +1,19 @@ +data_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] \ No newline at end of file diff --git a/config/_base_/default_runtime.py b/config/_base_/default_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..a38e965ba6860dcdff79caad4db34b3953980fb8 --- /dev/null +++ b/config/_base_/default_runtime.py @@ -0,0 +1,46 @@ +default_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')] + +# Logging +log_level = 'INFO' +log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True) + +# Evaluation +val_evaluator = [dict(type='E2EHmeanIOUMetric'), + dict(type='HmeanIOUMetric'), + dict(type='E2ENEDMetric')] +test_evaluator = val_evaluator + +# Visualization +vis_backends = [dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend')] +visualizer = dict( + type='TextSpottingLocalVisualizer', + name='visualizer', + vis_backends=vis_backends) diff --git a/config/_base_/schedules/schedule_adam_600e.py b/config/_base_/schedules/schedule_adam_600e.py new file mode 100644 index 0000000000000000000000000000000000000000..24a9d431935180a3861b4ab537654d9fcfe19f5f --- /dev/null +++ b/config/_base_/schedules/schedule_adam_600e.py @@ -0,0 +1,13 @@ +# 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) diff --git a/config/_base_/schedules/schedule_sgd_500e.py b/config/_base_/schedules/schedule_sgd_500e.py new file mode 100644 index 0000000000000000000000000000000000000000..cffdfdeb88683a4dee3efc5122e0edb45f9793af --- /dev/null +++ b/config/_base_/schedules/schedule_sgd_500e.py @@ -0,0 +1,13 @@ + +# optimizer +optim_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 policy +param_scheduler = [ + dict(type='LinearLR', end=1000, start_factor=0.001, by_epoch=False), +] diff --git a/config/_base_/textdet_runtime.py b/config/_base_/textdet_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..aae9092279b7f2cdbf2c9878ed969c200986724b --- /dev/null +++ b/config/_base_/textdet_runtime.py @@ -0,0 +1,36 @@ +default_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), +) + +# Logging +log_level = 'INFO' +log_processor = dict(type='LogProcessor', window_size=10, by_epoch=True) + + +# Visualization +vis_backends = [dict(type='LocalVisBackend'), dict(type='TensorboardVisBackend')] +visualizer = dict( + type='TextDetLocalVisualizer', + name='visualizer', + vis_backends=vis_backends) \ No newline at end of file diff --git a/config/baseline/config.py b/config/baseline/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b06b5497774c413a835da62156b8b1c7effc00 --- /dev/null +++ b/config/baseline/config.py @@ -0,0 +1,96 @@ +_base_ = [ + './model/dbnetpp.py', + './pipeline.py', + '../_base_/textdet_runtime.py', + '../_base_/datasets/iacc2022_chdac.py' +] + +# dataset settings +train_list = _base_.train_list +test_list = _base_.test_list +val_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/main +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! + +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' \ No newline at end of file diff --git a/config/baseline/model/dbnetpp.py b/config/baseline/model/dbnetpp.py new file mode 100644 index 0000000000000000000000000000000000000000..ef219a4558de6623784ff162c5ce59476bf86445 --- /dev/null +++ b/config/baseline/model/dbnetpp.py @@ -0,0 +1,37 @@ +model = 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)) \ No newline at end of file diff --git a/config/baseline/model/psenet.py b/config/baseline/model/psenet.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ae5b99afd55c34a14486b19e408f748feb8edf --- /dev/null +++ b/config/baseline/model/psenet.py @@ -0,0 +1,44 @@ +model = 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)) \ No newline at end of file diff --git a/config/baseline/pipeline.py b/config/baseline/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9c6f50534380bc813d9718770a6be02820c8a9 --- /dev/null +++ b/config/baseline/pipeline.py @@ -0,0 +1,51 @@ +train_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')) +] \ No newline at end of file diff --git a/config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.py b/config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.py new file mode 100644 index 0000000000000000000000000000000000000000..1682d001acc5faec0f0a5ed657cebdcf5deb6453 --- /dev/null +++ b/config/seghist/_base_db_seghist_resnet50-dcnv2_fpnc.py @@ -0,0 +1,47 @@ +r = 0. # shrink_ratio +stretch_ratio = 2. # 1.5 +model = 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)) diff --git a/config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.py b/config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.py new file mode 100644 index 0000000000000000000000000000000000000000..78e8a3eeb8a389ce5501bbff3b11f13db8f69ca5 --- /dev/null +++ b/config/seghist/_base_pan_seghist_resnet50-dcnv2_fpnc.py @@ -0,0 +1,44 @@ +model = 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)) diff --git a/config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.py b/config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.py new file mode 100644 index 0000000000000000000000000000000000000000..3a08e768460712fa86d9254a6ec8f2f49c4f0dea --- /dev/null +++ b/config/seghist/_base_pse_seghist_resnet50-dcnv2_fpnc.py @@ -0,0 +1,44 @@ +model = 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)) diff --git a/config/seghist/_base_seghist_resnet50-dcnv2_fpnc.py b/config/seghist/_base_seghist_resnet50-dcnv2_fpnc.py new file mode 100644 index 0000000000000000000000000000000000000000..51682324a65bc562a08d0ed3ac0f8ca2a91ab32d --- /dev/null +++ b/config/seghist/_base_seghist_resnet50-dcnv2_fpnc.py @@ -0,0 +1,48 @@ +r = 0. # shrink_ratio +stretch_ratio = 2. # 1.5 +model = 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)) diff --git a/config/seghist/pipeline/seghist_pipeline_basic.py b/config/seghist/pipeline/seghist_pipeline_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..a71fa8f3484b17462c41095e3fc537df6100b337 --- /dev/null +++ b/config/seghist/pipeline/seghist_pipeline_basic.py @@ -0,0 +1,50 @@ +train_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')) +] diff --git a/config/seghist/pipeline/seghist_pipeline_basic_rotate.py b/config/seghist/pipeline/seghist_pipeline_basic_rotate.py new file mode 100644 index 0000000000000000000000000000000000000000..811cbcbac0a1cb279a9d7a5eac52c83d29059a3e --- /dev/null +++ b/config/seghist/pipeline/seghist_pipeline_basic_rotate.py @@ -0,0 +1,58 @@ +train_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 + ) + ) +) \ No newline at end of file diff --git a/config/seghist/pipeline/seghist_pipeline_color_jitter.py b/config/seghist/pipeline/seghist_pipeline_color_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..1d73f2cf626a095a0a6cfc30186c0e690ee1eb71 --- /dev/null +++ b/config/seghist/pipeline/seghist_pipeline_color_jitter.py @@ -0,0 +1,48 @@ +train_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')) +] diff --git a/config/seghist/pipeline/seghist_pipeline_large_rotate.py b/config/seghist/pipeline/seghist_pipeline_large_rotate.py new file mode 100644 index 0000000000000000000000000000000000000000..fce6381e6d191dc2522e4a80c4324d8a69d5b8a3 --- /dev/null +++ b/config/seghist/pipeline/seghist_pipeline_large_rotate.py @@ -0,0 +1,57 @@ +train_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 + ) + ) +) \ No newline at end of file diff --git a/config/seghist/pipeline/seghist_pipeline_largescale.py b/config/seghist/pipeline/seghist_pipeline_largescale.py new file mode 100644 index 0000000000000000000000000000000000000000..1806f6d8c5855019349198e7bc29d4a0c83ff172 --- /dev/null +++ b/config/seghist/pipeline/seghist_pipeline_largescale.py @@ -0,0 +1,49 @@ +train_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')) +] \ No newline at end of file diff --git a/config/seghist/seghist_resnet50-dcnv2_fpnc.py b/config/seghist/seghist_resnet50-dcnv2_fpnc.py new file mode 100644 index 0000000000000000000000000000000000000000..590bc11dc4cdeedf2bac92e79022c22e2b7527b9 --- /dev/null +++ b/config/seghist/seghist_resnet50-dcnv2_fpnc.py @@ -0,0 +1,89 @@ +_base_ = [ + '_base_db_seghist_resnet50-dcnv2_fpnc.py', + './pipeline/seghist_pipeline_basic.py', + '../_base_/textdet_runtime.py', + '../_base_/datasets/iacc2022_chdac.py' +] + +# dataset settings +train_list = _base_.train_list +test_list = _base_.test_list +val_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 = False +load_from = './work_dirs_chdac/seghist/final_9712.pth' +>>>>>>> origin/main diff --git a/config/seghist/seghist_resnet50-dcnv2_fpnc_large.py b/config/seghist/seghist_resnet50-dcnv2_fpnc_large.py new file mode 100644 index 0000000000000000000000000000000000000000..040eeaec6451bd3640ff230a6db48b580461b9b5 --- /dev/null +++ b/config/seghist/seghist_resnet50-dcnv2_fpnc_large.py @@ -0,0 +1,75 @@ +_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 settings +train_list = _base_.train_list +test_list = _base_.test_list +val_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)) \ No newline at end of file diff --git a/config/seghist/seghist_resnet50-dcnv2_fpnc_toy.py b/config/seghist/seghist_resnet50-dcnv2_fpnc_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..5836fcc34eeb56f25a9211b309927b0ea58ebfce --- /dev/null +++ b/config/seghist/seghist_resnet50-dcnv2_fpnc_toy.py @@ -0,0 +1,67 @@ +_base_ = [ + '_base_seghist_resnet50-dcnv2_fpnc.py', + './pipeline/seghist_pipeline_basic.py', + '../_base_/textdet_runtime.py', + '../_base_/datasets/iacc2022_chdac_toy.py' +] + +# dataset settings +train_list = _base_.train_list +test_list = _base_.test_list +val_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') \ No newline at end of file diff --git a/environment.yml b/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..e276f7a4842d1b3187d244aefca16739758dde33 --- /dev/null +++ b/environment.yml @@ -0,0 +1,198 @@ +name: openmmlab +channels: + - 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/msys2 +dependencies: + - _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.0 \ No newline at end of file diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..1ecb34162978c66c8e2dd814fb6ab54cf72bff99 --- /dev/null +++ b/readme.txt @@ -0,0 +1 @@ +see https://github.com/LumionHXJ/SegHist \ No newline at end of file diff --git a/samples/gt1.png b/samples/gt1.png new file mode 100644 index 0000000000000000000000000000000000000000..c9d9a314c19ba07125b29f1bcf392b6f4fec463a --- /dev/null +++ b/samples/gt1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a72383f5a996098df47b47bd4e9e4987e78cd6a4dcac946444301c00189a39fc +size 2569731 diff --git a/samples/gt2.png b/samples/gt2.png new file mode 100644 index 0000000000000000000000000000000000000000..5e1b0f73feb5c2f67a4ebd302e4da21ffab96267 --- /dev/null +++ b/samples/gt2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b81624e7aeed4948efbe47a2e701ea034a805c78e825557a2f3c7eb316e08a6a +size 2491093 diff --git a/samples/pred1.png b/samples/pred1.png new file mode 100644 index 0000000000000000000000000000000000000000..91953ea5a1ac861cbe8532f3683968859546149b --- /dev/null +++ b/samples/pred1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e2cc2ae1832dbb4a335c8d72b6109773d9039274557fc55a63ce400282b43bf +size 2567194 diff --git a/samples/pred2.png b/samples/pred2.png new file mode 100644 index 0000000000000000000000000000000000000000..3e3fe2ba67b6662a6af11902b923af913bdf63d5 --- /dev/null +++ b/samples/pred2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:070525d284425af3c2ec6f102c3b0ba063daf69632255e4a3dfa7542f5a6b9e0 +size 2500501 diff --git a/seghist/__init__.py b/seghist/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69357daea844c515edc61b19537552ff6142921f --- /dev/null +++ b/seghist/__init__.py @@ -0,0 +1,2 @@ +from .datasets import * # NOQA +from .model import * # NOQA \ No newline at end of file diff --git a/seghist/datasets/__init__.py b/seghist/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df1056721a6f8840bc7ae7f4036b84ca9e1ce3e1 --- /dev/null +++ b/seghist/datasets/__init__.py @@ -0,0 +1 @@ +from .transforms import * \ No newline at end of file diff --git a/seghist/datasets/transforms/__init__.py b/seghist/datasets/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32b8c3ba3a6d13961f4d4c9f55cf2e6dd3d45632 --- /dev/null +++ b/seghist/datasets/transforms/__init__.py @@ -0,0 +1,5 @@ +from .textdet_transforms import MultiScaleResizeShorterSide, RatioAwareCrop, PadDivisor +from .colorspace import GaussianBlur, ChannelShuffle + +__all__ = ['MultiScaleResizeShorterSide', 'RatioAwareCrop', 'PadDivisor', + 'GaussianBlur', 'ChannelShuffle'] \ No newline at end of file diff --git a/seghist/datasets/transforms/colorspace.py b/seghist/datasets/transforms/colorspace.py new file mode 100644 index 0000000000000000000000000000000000000000..eee9d32d6e7a8c6404531f4ba743c7eed66e2f70 --- /dev/null +++ b/seghist/datasets/transforms/colorspace.py @@ -0,0 +1,30 @@ +from mmocr.registry import TRANSFORMS +import numpy as np +import cv2 +from 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) diff --git a/seghist/datasets/transforms/textdet_transforms.py b/seghist/datasets/transforms/textdet_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..908bbf7a4f984bddd86415d74a3b7358bc297463 --- /dev/null +++ b/seghist/datasets/transforms/textdet_transforms.py @@ -0,0 +1,164 @@ +from typing import Dict, List, Optional, Tuple, Union +from mmocr.registry import TRANSFORMS +from mmocr.datasets.transforms import Resize, TextDetRandomCrop +import numpy as np +from 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) \ No newline at end of file diff --git a/seghist/model/__init__.py b/seghist/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4538c220608c28e7824c38efb1edfe184a9f43f --- /dev/null +++ b/seghist/model/__init__.py @@ -0,0 +1,10 @@ +from .heads.seghist_heads import DBSegHistHead, PANSegHistHead, SegHistHead +from .postprocessor.iedp import IterExpandPostprocessor +from .module_loss.tks import SegHistModuleLoss, TKSModuleLoss +from .module_loss.db_tks import DBTKSModuleLoss +from .module_loss.pan_tks import PANTKSModuleLoss +from .module_loss.pse_tks import PSETKSModuleLoss + +__all__ = ['SegHistModuleLoss', 'DBSegHistHead', 'IterExpandPostprocessor', + 'DBTKSModuleLoss', 'PANTKSModuleLoss', 'PSETKSModuleLoss', + 'PANSegHistHead', 'SegHistHead', 'TKSModuleLoss'] diff --git a/seghist/model/heads/seghist_heads.py b/seghist/model/heads/seghist_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..de12626f63dc6fdcd7fc33a2974113b792e535b3 --- /dev/null +++ b/seghist/model/heads/seghist_heads.py @@ -0,0 +1,280 @@ +from typing import Dict, List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch import Tensor + +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from mmdet.models.utils import multi_apply +from mmocr.models.textdet.heads import BaseTextDetHead, DBHead +from mmocr.registry import MODELS +from 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 outputs \ No newline at end of file diff --git a/seghist/model/layer/dyrelu.py b/seghist/model/layer/dyrelu.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1e6189ae7c7b0fb094072e713104c69b8116d0 --- /dev/null +++ b/seghist/model/layer/dyrelu.py @@ -0,0 +1,88 @@ +import torch +from 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 output \ No newline at end of file diff --git a/seghist/model/layer/layout_enhanced_block.py b/seghist/model/layer/layout_enhanced_block.py new file mode 100644 index 0000000000000000000000000000000000000000..dae7e05182df1df9289473b3caa4a8455a685c59 --- /dev/null +++ b/seghist/model/layer/layout_enhanced_block.py @@ -0,0 +1,292 @@ +from typing import Union, List, Tuple + +import torch +from torch import Tensor, nn + +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from mmocr.models.common.layers import TFEncoderLayer +from 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 input \ No newline at end of file diff --git a/seghist/model/module_loss/db_tks.py b/seghist/model/module_loss/db_tks.py new file mode 100644 index 0000000000000000000000000000000000000000..2957ed365ecfb6f7a29920e9893186c984a264b3 --- /dev/null +++ b/seghist/model/module_loss/db_tks.py @@ -0,0 +1,143 @@ +from typing import Tuple +import copy + +import cv2 +import numpy as np +import torch + +from mmocr.registry import MODELS +from mmocr.models.textdet.module_losses import DBModuleLoss +from mmocr.structures import TextDetDataSample + +from seghist.utils import expand_poly, get_distance +from 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_mask \ No newline at end of file diff --git a/seghist/model/module_loss/pan_tks.py b/seghist/model/module_loss/pan_tks.py new file mode 100644 index 0000000000000000000000000000000000000000..b12d0583a34ed45b13a28a8a647b530b8512ff73 --- /dev/null +++ b/seghist/model/module_loss/pan_tks.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple + +import numpy as np +import torch + +from mmocr.registry import MODELS +from mmocr.structures import TextDetDataSample +from 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_mask \ No newline at end of file diff --git a/seghist/model/module_loss/pse_tks.py b/seghist/model/module_loss/pse_tks.py new file mode 100644 index 0000000000000000000000000000000000000000..be148d4c859fcb2ba8ef2886f3e96426e0af5e58 --- /dev/null +++ b/seghist/model/module_loss/pse_tks.py @@ -0,0 +1,15 @@ +from mmocr.registry import MODELS +from 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) \ No newline at end of file diff --git a/seghist/model/module_loss/tks.py b/seghist/model/module_loss/tks.py new file mode 100644 index 0000000000000000000000000000000000000000..70b6795ebe28590ea501183bf8df2bbc8128e309 --- /dev/null +++ b/seghist/model/module_loss/tks.py @@ -0,0 +1,138 @@ +from typing import Sequence, Tuple, Optional, Dict, Union + +import cv2 +import numpy as np +import torch +from torch import Tensor + +from mmocr.registry import MODELS +from mmocr.models.textdet.module_losses import SegBasedModuleLoss +from 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 results diff --git a/seghist/model/postprocessor/iedp.py b/seghist/model/postprocessor/iedp.py new file mode 100644 index 0000000000000000000000000000000000000000..6c33680e703e107f66477180586c007d0c5b905d --- /dev/null +++ b/seghist/model/postprocessor/iedp.py @@ -0,0 +1,123 @@ +from typing import Optional + +import cv2 +import numpy as np +import torch +from torch import Tensor +from shapely.geometry import Polygon + +from mmengine.structures import InstanceData +from mmocr.structures import TextDetDataSample +from mmocr.registry import MODELS +from 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_sample \ No newline at end of file diff --git a/seghist/utils/__init__.py b/seghist/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5da3a4d7f444224d416d9c2531c2fc7f907d7655 --- /dev/null +++ b/seghist/utils/__init__.py @@ -0,0 +1,2 @@ +from .poly_utils import * +from .image_utils import ImageToolkits \ No newline at end of file diff --git a/seghist/utils/chdac_label_preprocess.py b/seghist/utils/chdac_label_preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e15fb413ca54dc8510378832712724265c17fd --- /dev/null +++ b/seghist/utils/chdac_label_preprocess.py @@ -0,0 +1,92 @@ +import json +from tqdm import tqdm +import os +import warnings + +import numpy as np +from PIL import Image +from sklearn.cluster import KMeans + +from seghist.utils.image_utils import ImageToolkits + +warnings.filterwarnings('ignore', category=np.RankWarning) + +def get_image_size(file_path): + with Image.open(file_path) as img: + return img.size + +def clean_redundant_points(poly): + ''' + clean redundant points when len(poly) % 2 != 0 + ''' + kmeans = KMeans(((len(poly)+1) // 2), n_init=3).fit(poly[:, 1:]) + cluster_counts = np.bincount(kmeans.labels_) + for i in range(len(cluster_counts)): + if cluster_counts[i] == 1: + for idx, l in enumerate(kmeans.labels_): + if l==i: + return np.concatenate([poly[:idx], poly[idx+1:]], axis=0) + +def main(root, + label_list, + data_prefix_list, + output_list, + separate_entry=True): + metainfo = {"dataset_type": "TextDetDataset", "task_name": "textdet", + "category": [{"id": 0, "name": "single_entry_text", + "id": 1, "name": "double_entry_text"}]} + for label, data_prefix, output in zip(label_list, data_prefix_list, output_list): + label = os.path.join(root, label) + datas = dict(metainfo=metainfo, data_list=[]) + with open(label) as f: + ann_file = json.load(f) + for img_path, instances in tqdm(ann_file.items()): + data = dict(img_path=img_path, instances=[]) + data['width'], data['height'] = get_image_size(os.path.join(root, data_prefix, img_path)) + for idx, inst in enumerate(instances): + # clean redundant points, if not in pair. + if len(inst['points']) % 4 != 0: + poly = np.array(inst['points']).reshape(-1, 2) + poly = clean_redundant_points(poly) + instances[idx]['points'] = poly.reshape(-1).tolist() + if separate_entry: + hi = ImageToolkits([np.array(d['points']).reshape(-1, 2) for d in instances], + np.array((data['height'], data['width'])), + img_path, + texts=[d['transcription'] for d in instances]) + hi.process() + data['instances'] = hi.output_json() + else: + for idx, inst in enumerate(instances): + data["instances"].append(dict( + ignore=False, + text=inst['transcription'], + bbox_label=0, + polygon=inst['points'] + )) + datas['data_list'].append(data) + with open(os.path.join(root, output), mode='w') as f: + json.dump(datas, f) + +root = './data/historical_document/IACC2022_CHDAC/private_dataset' + +label_list = ['dataset_1/test/label_test.json', + 'dataset_1/train/label_train.json', + 'dataset_2/test/label_test.json', + 'dataset_2/train/label_train.json', + 'dataset_3/test/label_test.json', + 'dataset_3/train/label_train.json',] +data_prefix_list = ['dataset_1/test/image', + 'dataset_1/train/image', + 'dataset_2/test/image', + 'dataset_2/train/image', + 'dataset_3/test/image', + 'dataset_3/train/image'] +output_list = ['dataset_1/test/ocr_test.json', + 'dataset_1/train/ocr_train.json', + 'dataset_2/test/ocr_test.json', + 'dataset_2/train/ocr_train.json', + 'dataset_3/test/ocr_test.json', + 'dataset_3/train/ocr_train.json'] + +main(root, label_list, data_prefix_list, output_list, separate_entry=False) diff --git a/seghist/utils/high_resolution_det.py b/seghist/utils/high_resolution_det.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d62c1bddb31875aff545ffce1182903f9f83fc --- /dev/null +++ b/seghist/utils/high_resolution_det.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +import math +import os +from typing import Tuple, Union, List, Optional +import warnings + +import numpy as np +from numpy.typing import * +import cv2 +from tqdm import tqdm +from shapely.geometry import Polygon, box +from shapely.affinity import translate + +from mmocr.apis import TextDetInferencer +from seghist.utils import iou + +class DetectionResult: + """Saving single text line detection result of split images. + + Args: + polygon(Union[Polygon, NDArray]): part of text line. + score(float): sum of confidence of text line. + weight(int): number of merged text lines. + """ + VERTICLE= 1 + HORIZENTAL = 0 # x: the zero dim + def __init__(self, + polygon: Union[Polygon, NDArray], + score: float, + weight: int = 1): + if isinstance(polygon, Polygon): + self.polygon = polygon + else: + self.polygon = Polygon(np.array(polygon).reshape(-1, 2)) + self.score = score + self.weight = weight + + def merge(self, other: DetectionResult): + poly = self.polygon.union(other.polygon) + assert isinstance(poly, Polygon), \ + 'Merging result isn\'t Polygon, maybe a MultiPolygon, please check your code.' + score = self.score + other.score + weight = self.weight + other.weight + return DetectionResult(poly, score, weight) + + def translate(self, offset, direction): + if direction == self.HORIZENTAL: + self.polygon = translate(self.polygon, xoff=offset) + else: + self.polygon = translate(self.polygon, yoff=offset) + + def max(self, direction): + return np.max(np.array(self.polygon.exterior.coords)[:, direction]) + + def min(self, direction): + return np.min(np.array(self.polygon.exterior.coords)[:, direction]) + + +class SplitImage: + """Part of original image. + + Args: + image(np.ndarray): part of image, in h-w-c style. + corner(np.ndarray): top left corner of split images, xy-style. + """ + SWITCH_INPUT = 2 + VERTICLE_MERGE = 1 + HORIZENTAL_MERGE = 0 + CANNOT_MERGE = -1 + CONTAIN = -2 + def __init__(self, + image: np.ndarray, + corner: Tuple): + self.image = image + self.height, self.width, self.channels = image.shape + self.corner = corner + + def save_det_results(self, results: Union[dict, List[DetectionResult]]): + """Handle detection results from mmocr inferencer and save raw results + in object. + Raw results represents that polygons' coordinates are offsets corresbonded + to the top left corner. + The polygons are transformed to numpy.ndarray, with shape (k, 2). + + Args: + results: + - detection results mmocr inferencer, containing keys 'polygons' and 'scores'. + - results generate by merging splited images. + """ + if isinstance(results, dict): + self.results = [DetectionResult(p, s) for p, s in zip(results['polygons'], results['scores'])] + else: + self.results = results + + @classmethod + def mergable(cls, first: SplitImage, second: SplitImage): + """Determine whether first can merge with second. + We request first in the top/left direction of second, otherwise demand to switch them. + """ + if first.corner[1] == second.corner[1] and first.height == second.height: + # STRICT: first is on the left side + if first.corner[0] > second.corner[0]: + return SplitImage.SWITCH_INPUT + + # no overlapping in horizental + if first.corner[0] + first.width <= second.corner[0]: + return SplitImage.CANNOT_MERGE + # first contain second + if first.corner[0] + first.width >= second.corner[0] + second.width: + return SplitImage.CONTAIN + return SplitImage.HORIZENTAL_MERGE + + elif first.corner[0] == second.corner[0] and first.width == second.width: + if first.corner[1] > second.corner[1]: + return SplitImage.SWITCH_INPUT + if first.corner[1] + first.height <= second.corner[1]: + return SplitImage.CANNOT_MERGE + if first.corner[1] + first.height >= second.corner[1] + second.height: + return SplitImage.CONTAIN + return SplitImage.VERTICLE_MERGE + + return SplitImage.CANNOT_MERGE + + @classmethod + def intersect(cls, + first_res: List[DetectionResult], + second_res: List[DetectionResult], + overlap: box, + iou_thresh: float = 0.5): + """Merging the results of first and second that touch the overlap area. + Translated in SplitImage.merge_results + """ + intersect_results = [] + + # fetching polygons that touches overlap area. + first_overlap = [] + second_overlap = [] + for fr in first_res: + first_overlap.append(fr.polygon.intersection(overlap)) + for sr in second_res: + second_overlap.append(sr.polygon.intersection(overlap)) + + for fr, fo in zip(first_res, first_overlap): + _iou = [] + for sr, so in zip(second_res, second_overlap): + _iou.append(iou(fo, so)) + + # if second_res is empty! + if _iou == []: + intersect_results.append(fr) + continue + + argmax_iou = np.argmax(_iou) + if _iou[argmax_iou] < iou_thresh: + intersect_results.append(fr) + else: + # merge split results + intersect_results.append(fr.merge(second_res[argmax_iou])) + del second_res[argmax_iou] + del second_overlap[argmax_iou] + + for sr in second_res: + intersect_results.append(sr) + + return intersect_results + + @classmethod + def merge_results(cls, + first: SplitImage, + second: SplitImage, + merge_direction: int, + iou_thresh: float = 0.5): + """Merging first and second in merge_direction. + Results set of a,b are divided into a-b, b-a and a∩b. + a∩b part is dealed with function SplitImage.intersect. + """ + merge_results = [] # list of detection results + + if merge_direction == cls.HORIZENTAL_MERGE: + # add offset + offset = second.corner[0] - first.corner[0] + second_res = second.results + for p in second_res: + p.translate(offset, merge_direction) + + dividing_first = second.corner[0] - first.corner[0] + dividing_second = first.width + + intersect_first = [] + intersect_second = [] + overlap = box(dividing_first, 0, dividing_second, first.height) + for fr in first.results: + if fr.max(merge_direction) > dividing_first: + intersect_first.append(fr) # a∩b + else: + merge_results.append(fr) # a-b + for sr in second_res: + if sr.min(merge_direction) < dividing_second: + intersect_second.append(sr) # a∩b + else: + merge_results.append(sr) # b-a + + merge_results += cls.intersect(intersect_first, + intersect_second, + overlap, + iou_thresh) + + else: + # add offset + offset = second.corner[1] - first.corner[1] + second_res = second.results + for p in second_res: + p.translate(offset, merge_direction) + + dividing_first = second.corner[1] - first.corner[1] + dividing_second = first.height + + intersect_first = [] + intersect_second = [] + for fr in first.results: + if fr.max(merge_direction) > dividing_first: + intersect_first.append(fr) + else: + merge_results.append(fr) + for sr in second_res: + if sr.min(merge_direction) < dividing_second: + intersect_second.append(sr) + else: + merge_results.append(sr) + + overlap = box(0, dividing_first, first.width, dividing_second) + merge_results += cls.intersect(intersect_first, + intersect_second, + overlap, + iou_thresh) + return merge_results + + @classmethod + def merge(cls, + first: SplitImage, + second: SplitImage, + iou_thresh: float = 0.5): + assert first.channels == second.channels, 'Images to merge must have same number of channels' + assert hasattr(first, "results") and hasattr(second, "results"), \ + 'Image to merge must already have detection results.' + + merge_flag = cls.mergable(first, second) + assert merge_flag != cls.CANNOT_MERGE, 'First cannot merge with second, please check your code.' + if merge_flag == cls.CONTAIN: + warnings.warn("Object containing in the other, returning the bigger one.") + return first + + if merge_flag == cls.SWITCH_INPUT: + return cls.merge(second, first) + + # geometry info. + if merge_flag == cls.HORIZENTAL_MERGE: + corner = first.corner + height = first.height + width = max(first.width, second.width + second.corner[0] - first.corner[0]) + else: + corner = first.corner + width = first.width + height = max(first.height, second.height + second.corner[1] - first.corner[1]) + + # combine images + image = np.zeros((height, width, first.channels)) + image[:first.height, :first.width] = first.image + image[-second.height:, -second.width:] = second.image + merge_image = SplitImage(image, corner) + + # next merging results of first and second + results = cls.merge_results(first, second, merge_flag, iou_thresh) + + merge_image.save_det_results(results) + + return merge_image + + def save_result_to_file(self, output_file): + """Save detection results to output_file. + Usually used after merging all sub-images. + """ + polygons = [np.array(p.polygon.exterior.coords) for p in self.results] + np.savez(output_file, *polygons) + + +def split_image(image: np.ndarray, + split_size: Tuple[int, int]=None, + overlap_size: Tuple[int, int]=None): + """Split high resolution image to several low resolution image of split size. + Adjacent splits shared overlap, define by overlap_size. + + Args: + image(np.ndarray): high resolution image to split, in shape (H, W, C). + split_size(tuple): (s_h, s_w) represents the size after split. + overlap_size(tuple): (ol_h, oh_w) represents the overlapping of verticle and horizental respectively. + + Returns: + results(two-dim array of SplitImage): image after spliting + """ + if split_size is None: + split_size = image.shape[:2] + overlap_size = (0, 0) + assert split_size[0] > overlap_size[0] and split_size[1] > overlap_size[1], \ + 'split size must larger that overlap size.' + + img_h, img_w = image.shape[:2] + n = math.ceil((img_h - overlap_size[0]) / (split_size[0] - overlap_size[0])) + m = math.ceil((img_w - overlap_size[1]) / (split_size[1] - overlap_size[1])) + results = np.zeros((n, m), dtype=object) + + for i in range(n): + corner_y = min(i * (split_size[0] - overlap_size[0]), + img_h - split_size[0]) + for j in range(m): + corner_x = min(j * (split_size[1] - overlap_size[1]), + img_w - split_size[1]) + results[i, j] = SplitImage(image[corner_y: corner_y + split_size[0], corner_x: corner_x + split_size[1]], + (corner_x, corner_y)) + + return results + + +def inference(split_images: np.ndarray[np.ndarray[SplitImage]], + inferencer: TextDetInferencer): + """Inferencing splited images in serial. + """ + for _ in tqdm(split_images, desc='verticle'): + for si in tqdm(_, desc='horizental'): + det_results = inferencer(si.image) + si.save_det_results(det_results) + + +def merging_results(split_images: np.ndarray[np.ndarray[SplitImage]], + iou_thresh: float = 0.5): + """Merging splited results by horizental->verticle order.""" + n, m = split_images.shape + row_images = np.zeros((n, ), dtype=object) + for i in range(n): + curr_split = split_images[i, 0] + for j in range(1, m): + curr_split = SplitImage.merge(curr_split, split_images[i, j], iou_thresh) + row_images[i] = curr_split + + result = row_images[0] + for i in range(1, n): + result = SplitImage.merge(result, row_images[i], iou_thresh) + + return result + + +def main(): + img_root = './project_samples' + # split_size = (1024, 2048) # ij-style here but xy-style in mmcv + # overlap_size = (split_size[0] // 4, split_size[1] // 4) + split_size = None + overlap_size = None + iou_thresh = 0.5 + inferencer = TextDetInferencer(ckpt='/home/huxingjian/model/mmocr/projects/PFRNet/work_dirs/det.pth', + config='/home/huxingjian/model/mmocr/projects/PFRNet/work_dirs/dbnetpp_kernel/dbnetpp_resnet50-dcnv2_fpnc_quad.py', + device='cuda:0') + image_list = [f for f in os.listdir(img_root) if not os.path.isdir(os.path.join(img_root, f))] + for img_path in image_list: + img = cv2.imread(os.path.join(img_root, img_path)) + split_images = split_image(img, split_size, overlap_size) + inference(split_images, inferencer) + result = merging_results(split_images, iou_thresh) + result.save_result_to_file(os.path.join(img_root, "det_results", img_path.replace('png', 'npz'))) \ No newline at end of file diff --git a/seghist/utils/image_utils.py b/seghist/utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..39b0c0aa9e0895b1c0385d381c03b193dc1884ab --- /dev/null +++ b/seghist/utils/image_utils.py @@ -0,0 +1,651 @@ +from typing import Sequence, Sequence, Union +import warnings + +import numpy as np +from numpy.typing import * +import cv2 +from sklearn.cluster import KMeans + +def dist(p1: NDArray, p2: NDArray): + """Compute Euclid distance between p1 and p2. + + Args: + p1(NDArray) and p2(NDArray) have same shape (..., k). + """ + return np.sqrt(np.sum((p1-p2)**2, axis=-1)) + +def norm(p: NDArray): + """Perform L2-normalization on the given array. + + This function normalizes the input array `p` using the L2 norm, also known + as the Euclidean norm. The L2 norm is calculated as the square root of the + sum of the squared elements of `p`. The normalization process scales the + elements of `p` so that the length of the resultant vector is 1. This is + commonly used in machine learning and statistics to normalize the input + features or data points. + + Parameters: + p (NDArray): A numpy array of any shape, where the normalization is applied + along the last dimension. + + Returns: + NDArray: The L2-normalized array, having the same shape as the input array `p`. + + Example: + >>> import numpy as np + >>> p = np.array([[1, 2, 3], [4, 5, 6]]) + >>> norm(p) + array([[0.26726124, 0.53452248, 0.80178373], + [0.45584231, 0.56980288, 0.68376346]]) + + Note: + The function assumes that the input array `p` is not the zero vector, as the L2 + norm of a zero vector is undefined. + """ + return p / (np.sqrt(np.sum(p ** 2, axis=-1))) + +def section_iou(l1: NDArray, l2:NDArray): + """ + Calculate the Intersection over Union (IoU) of two one-dimensional sections. + Each sections contains k points, but only edge points are contributed. + + This function computes the IoU of two line segments, l1 and l2. Each segment + is represented by a series of points. The IoU is calculated as the length of + the intersection of the two segments divided by the length of their union. + + The segments are defined in an unordered manner, meaning that for each + segment, the start and end points are not necessarily in increasing order. + + Args: + l1 (NDArray): An array representing the first segment, shape (k, ). + l2 (NDArray): An array representing the second segment, shape (k, ). + + Returns: + float: The IoU of the two segments. The value ranges from + 0 (no overlap) to 1 (full overlap). + + Example: + >>> import numpy as np + >>> l1 = np.array([1, 3, 2]) + >>> l2 = np.array([2, 4, 3]) + >>> section_iou(l1, l2) + 0.3333333333333333 + + Note: + The function includes a small constant (1e-4) in the denominator to avoid + division by zero in case the union of the segments has zero length. + """ + less = (np.min(l1), np.min(l2)) + greater = (np.max(l1), np.max(l2)) + _iou = max(0, (np.min(greater) - np.max(less)) / (np.max(greater) - np.min(less) + 1e-4)) + return _iou + +def uniform_curve_sampling(curve: NDArray, points: int): + """Uniformly sample a specified number of points on a given curve. + + This function takes a curve represented by a series of points and samples + a fixed number of points from it in a uniform manner, based on the + cumulative length of the curve. It guarantees that the starting and + ending points of the curve are included in the sampled points. + + Args: + curve (NDArray): A numpy array representing the curve. The array + should have the shape (k, 2), where k is the number of points in + the curve and each point is a 2D coordinate (x, y). + points (int): The number of points to sample from the curve. + + Returns: + NDArray: A numpy array of the uniformly sampled points with the shape + (p, 2), where p is equal to the 'points' argument. + + The function works by first calculating the length of each segment of the + curve, then accumulating these lengths to find the total length of the curve. + It then determines the positions along the curve where the uniformly spaced + points should be, and interpolates these points based on the nearest segments + in the original curve. + """ + k = curve.shape[0] # points in original curve + + segment_length = dist(curve, np.concatenate([curve[0:1], curve[:-1]], axis=0)) # (k, ) + accumulate_length = np.cumsum(segment_length) # (k, ) + curve_length = accumulate_length[-1] + + sample_results = np.zeros((points, 2)) + sample_results[0] = curve[0] + for p in range(1, points): + curr_length = curve_length * p / (points - 1) + + # default return value v in (a(i-1), a(i)] + curr_segment = np.searchsorted(accumulate_length, curr_length) + curr_segment = min(k-1, curr_segment) # precision problem in division may ocurr + + theta = (accumulate_length[curr_segment] - curr_length) / segment_length[curr_segment] + sample_results[p] = theta * curve[curr_segment-1] + (1-theta) * curve[curr_segment] + + return sample_results + +def extra_sampling(array: NDArray, extra_points: int): + """Doing extra sampling to `array`, sample `extra_points` uniformly on each side. + + Args: + arrray(NDArray): supporting two-dim array. + """ + result = [] + + # sample each pair of neighboring elements + for i in range(len(array) - 1): + samples = np.linspace(array[i], array[i + 1], extra_points + 1, endpoint=False)[1:] + result.extend(samples) + + # adding last element + result.append(array[-1]) + + return np.array(result) + +def compute_text_direction(polygon: NDArray): + """Return normalized direction vector of a text region. + Direction vector is along the positive Y-axis. + """ + vec1 = polygon[len(polygon)//2-1] - polygon[0] + vec1 = vec1 if vec1[1] >= 0 else -vec1 + vec2 = polygon[len(polygon)//2] - polygon[-1] + vec2 = vec2 if vec2[1] >= 0 else -vec2 + mean = (vec1 + vec2) / 2 + return norm(mean) + +def find_top_bottom(polygon: NDArray): + """Receive reordered polygon, find its top and bottom. + Returns: + in top-bottom order + """ + line0 = np.array([polygon[0], polygon[-1]]) + line1 = np.array(polygon[len(polygon)//2-1:len(polygon)//2+1]) + if np.mean(line0[:, 1]) < np.mean(line1[:, 1]): + return line0, line1 + else: + return line1, line0 + +class ImageToolkits: + """ImageToolkits class can achieve the following functionalities: + 1. Separate single-line body text and double-line annotations in + historical document images, and output corresponding JSON annotations. + 2. Rectify the polygon representation of text lines, where the first + n points correspond to one long edge, the last n points correspond to + the opposite long edge, and the two long edges are joined end-to-end. + 3. Calculate the aspect ratio of text lines (defined as the ratio of + the long edge to the short edge). + 4. Calculate the vertical aspect ratio of text lines in historical + documents (defined as the ratio of the vertical edge to the horizontal + edge). + 5. Calculate the text center line(compared to the text kernel, there + is no shrinkage along text direction). + 6. Check the text line orientation in historical documents. + + Args: + polygons(Sequence[NDArray]): Text regions in the image. + image_shape(NDArray): The shape of the image in (height, width). + image_path(str): Path to the image. + texts(Sequence[str]): Text annotations for regions, aiding in text line + localization. + points(int): Number of samples taken along each long edge to determine + the length of the short edge. + cluster_thresh(float): Determines whether the historical document + contains only single-line body text. + shrink_ratio(Union[float, Sequence]): The width of the text central region + is 1/r times the width of the text region; using a single value indicates + the same shrinkage ratio for both single-line body text and double-line + annotations, while using two values indicates different shrinkage ratios. + reorder(bool): Whether it is necessary to rearrange the annotation order of + polygons. If the image is not a document image, please pass false. + """ + SINGLE_ENTRY = 0 + DOUBLE_ENTRY = 1 # having thinner width + TO_BE_DETERMINED = -1 + def __init__(self, + polygons: Sequence[NDArray], + image_shape: NDArray = None, + image_path: str = None, + texts: Sequence[str] = None, + points: int = 30, + cluster_thresh: float = 1.3, + shrink_ratio: Union[float, Sequence] = 3, + reorder: bool = False): + self.image_shape = image_shape + self.image_path = image_path + self.polygons = polygons + self.points = points + self.texts = texts + self.num_instance = len(polygons) + self.cluster_thresh = cluster_thresh + self.shrink_ratio = np.array(shrink_ratio) if isinstance(shrink_ratio, Sequence) \ + else np.array((shrink_ratio, shrink_ratio)) + for r in self.shrink_ratio: + assert r > 1, 'Centerline must have proper shrink ratio r > 1.' + self.reorder = reorder + + @classmethod + def fitting2reorder(cls, poly, m=0, k=5): + """ + Args: + m: extra sampling + k: degree of fitting polynominal + + Returns: + fit_mse: fitting error. + mse: fitting error of each side. + polynominal: coefficient of polynominal. + """ + fit_mse = [] + mse = [] + polynomimal = [] + for _ in range(len(poly) // 2): + # part 1: fetch out each curve in same order(top to down or vise versa) + curve_a = poly[_: _+len(poly)//2] + curve_b = np.concatenate([poly[_+len(poly)//2: ], poly[: _]], axis=0) + curve_b = curve_b[::-1] + + # part 2: extra sampling + curve_a = extra_sampling(curve_a, m) + curve_b = extra_sampling(curve_b, m) + + # part 3: fitting with polynominal: x = f(y) + poly_eff_a = np.polyfit(curve_a[:, 1], curve_a[:, 0], k) + poly_eff_b = np.polyfit(curve_b[:, 1], curve_b[:, 0], k) + + poly_a = np.poly1d(poly_eff_a) + poly_b = np.poly1d(poly_eff_b) + + # part 4: fitting + fit_aj = poly_a(curve_a[:, 1]) + fit_bj = poly_b(curve_b[:, 1]) + + # part 5: compute fitting error + mse_a = np.sum((fit_aj - curve_a[:, 0]) ** 2) + mse_b = np.sum((fit_bj - curve_b[:, 0]) ** 2) + + # part 6: append return list + polynomimal.append((poly_a, poly_b)) + mse.append((mse_a, mse_b)) + fit_mse.append(mse_a + mse_b) + + return fit_mse, mse, polynomimal + + def reorder_polygon(self, + k: int = 5, + line_ratio: float = 5.0, + extra_points: int = 2): + """Reorder all polygons and find out each long curve. The process keep the + order between `self.polygons` unchanged. + + If the instance is less-point annotated and hard to determine longerside, + then save it and wait for the help of overdetermined results. + + Long curve will be save in attribute `self.polygons`, `self.polygons` is a + list of np.array, which first half represents a long curve. + + Args: + k(int): the degree of polyfit + line_ratio(float): if the long length is `line_ratio` times as long as short + one, the long curve can be determined. + extra_points(int): extra points to sample when fitting the curve. + """ + if self.reorder: + return + + reordered_polygon = [] + to_be_determined = [] + to_be_determined_index = [] + text_direction = [] # end-start, (0, 1) + + for i, poly in enumerate(self.polygons): + assert len(poly) % 2 == 0 and len(poly) >= 4, \ + f'polygon must contains 2k(at least 4) points but receive {poly}.' + + # two-point(line) annotation: cannot determined + if len(poly) == 4: + + # dist compute: 0->3, 1->2 + dist_1 = np.sum(dist(poly[:2], poly[2:][::-1])) + + # dist compute: 0->1, 3->2 + dist_2 = np.sum(dist(np.array([poly[0], poly[-1]]), poly[1:3])) + + # if one set of sides is significantly longer + if dist_1 > dist_2 * line_ratio: + result = np.concatenate([poly[1:], poly[:1]], axis=0) + text_direction.append(compute_text_direction(result)) + reordered_polygon.append(result) + elif dist_2 > dist_1 * line_ratio: + result = poly + text_direction.append(compute_text_direction(result)) + reordered_polygon.append(result) + else: + # if the results cannot be determined now, reorder it later + # Note: keep the order inside polygons + to_be_determined.append(poly) + to_be_determined_index.append(i) + reordered_polygon.append([]) + continue + + # promise no underdetermined problem + if len(poly) <= 2 * (k + 1): + m = max(extra_points, np.ceil((len(poly)//2 - (k + 1)) / (len(poly) // 2 - 1)).astype(np.int32)) + else: + m = extra_points + + fit_mse, mse, polynomial = self.fitting2reorder(poly, m, k) + + min_fit_mse = np.argmin(fit_mse) + result = np.concatenate([poly[min_fit_mse:], poly[:min_fit_mse]], axis=0) + + # try refining if result isn't ideal + if not (1/3 < mse[min_fit_mse][0] / (mse[min_fit_mse][1] + 1e-6) < 3) and \ + fit_mse[min_fit_mse] > 10: + # deleting side with imbalance points + argmin = np.array(mse[min_fit_mse]).argmin() + if argmin == 0: + to_delete = poly[min_fit_mse: min_fit_mse+len(poly)//2] + else: + # second curve no need to reverse + to_delete = np.concatenate([poly[min_fit_mse+len(poly)//2: ], poly[: min_fit_mse]], axis=0) + + # remove two points with lowest fitting error + fit_error = polynomial[min_fit_mse][argmin](to_delete[:, 1]) - to_delete[:, 0] + del_points = fit_error.argsort()[:2] + + # construct new poly + avail_index = np.ones(to_delete.shape[:1], dtype=bool) + avail_index[del_points] = False + if argmin == 0: + another_curve = np.concatenate([poly[min_fit_mse+len(poly)//2: ], poly[: min_fit_mse]], axis=0) + poly = np.concatenate([to_delete[avail_index], another_curve], axis=0) + else: + another_curve = poly[min_fit_mse: min_fit_mse+len(poly)//2] + poly = np.concatenate([another_curve, to_delete[avail_index]], axis=0) + fit_mse_n, mse_n, _ = self.fitting2reorder(poly, m, k) + min_fit_mse_n = np.argmin(fit_mse_n) + + image_path = getattr(self, "image_path", "") + text = self.texts[i] if isinstance(getattr(self, "texts", None), list) and i < len(self.texts) else "" + if np.min(fit_mse) / (np.min(fit_mse_n) + 1e-3) > 5: + result = np.concatenate([poly[min_fit_mse_n:], poly[:min_fit_mse_n]], axis=0) + action = "replacing" + else: + action = "keep" + print(f"{image_path} {text}: {action} old {np.min(fit_mse)} by {'new' if action == 'replacing' else 'rejecting new'} {np.min(fit_mse_n)}") + + text_direction.append(compute_text_direction(result)) + reordered_polygon.append(result) + + document_direction = np.mean(text_direction, axis=0) # no need to normalize again + for i, poly in zip(to_be_determined_index, to_be_determined): + direct1 = compute_text_direction(poly) + direct2 = compute_text_direction(np.concatenate([poly[1:], poly[:1]], axis=0)) + if np.sum(direct1 * document_direction) > np.sum(direct2 * document_direction): + reordered_polygon[i] = poly + text_direction.append(direct1) + else: + reordered_polygon[i] = np.concatenate([poly[1:], poly[:1]], axis=0) + text_direction.append(direct2) + + self.polygons = reordered_polygon + self.direction = norm(np.mean(text_direction, axis=0)) + + self.check_polygon_order() + + def determine_short_length(self, + points_a: NDArray, + points_b: NDArray): + """Determine the shorter curve of polygon. + + Args: + points_a(NDArray): shape-like (n, p, 2). + points_b(NDArray): shape-like (n, p, 2). + points_a and points_b are return value of function `uniform_curve_sampling`. + + Returns: + short side length(NDArray): (n, ) + """ + + raw_dist = dist(points_a, points_b) # n, p + + # using IQR identify outliers + q1 = np.percentile(raw_dist, 25, axis=-1) # n, + q3 = np.percentile(raw_dist, 75, axis=-1) + iqr = q3 - q1 + lower_bound = q1 - 1 * iqr + upper_bound = q3 + 1 * iqr + + # need to filter outliers one by one (due to numbers of outliers isn't same) + mean = np.zeros((len(points_a), )) # n, + for i, raw in enumerate(raw_dist): + refine_dist = raw[(lower_bound[i] <= raw) & (raw <= upper_bound[i])] + mean[i] = np.mean(refine_dist, axis=-1) + return mean + + def clustering_polygons(self, + shorter_length: NDArray): + """Clustering polygons through shorter length by KMeans. + Returns: + label(NDArray): (n, ) + """ + kmeans = KMeans(n_clusters=2, n_init=3).fit(shorter_length.reshape(-1, 1)) + + cluster_center = kmeans.cluster_centers_ + label = kmeans.labels_ + # switching label when single entries are assigned smaller width + if cluster_center[self.SINGLE_ENTRY] < cluster_center[self.DOUBLE_ENTRY]: + label = np.where(label==self.SINGLE_ENTRY, self.DOUBLE_ENTRY, self.SINGLE_ENTRY) + cluster_center = cluster_center[::-1] + + # if the center of two clusters is close enough, merge them! + if cluster_center[self.SINGLE_ENTRY] < cluster_center[self.DOUBLE_ENTRY] * self.cluster_thresh: + label = np.ones_like(label) * self.SINGLE_ENTRY + cluster_center = (cluster_center[self.SINGLE_ENTRY],) + else: + # if keeping two cluster, using reading order to refine the result + determined = np.zeros_like(label) + + # step 1: picking out double entry + for i in range(len(label)-1): + if determined[i]: + continue + if label[i] == self.DOUBLE_ENTRY and label[i+1] == self.DOUBLE_ENTRY: + y_less = (np.min(self.polygons[i][:, 1]), np.min(self.polygons[i+1][:, 1])) + y_greater = (np.max(self.polygons[i][:, 1]), np.max(self.polygons[i+1][:, 1])) + _iou = max(0, (np.min(y_greater) - np.max(y_less)) / (np.max(y_greater) - np.min(y_less) + 1e-4)) + if _iou > 0.5: + determined[i] = determined[i+1] = True + + # step 2: recompute cluster center + if np.any(determined): + # keeping the minimum for maximize the gap between clsuter center. + cluster_center[self.DOUBLE_ENTRY] = min(np.mean(shorter_length[determined == True]), + cluster_center[self.DOUBLE_ENTRY]) + + # step 3: transformation according to reading order + # continuous text line in same column cannot have same label + for i in range(len(label)-1): + if determined[i] and determined[i+1]: + continue + + # step 1: find bottom line of line[i] + _, bottom_0 = find_top_bottom(self.polygons[i]) + + # step 2: find top line of line[i+1] + top_1, _ = find_top_bottom(self.polygons[i+1]) + + # step 3: projecting mid point of top and bottom line, prog = a·b/|b| + top_proj = np.dot(np.mean(top_1, axis=0), self.direction) + bot_proj = np.dot(np.mean(bottom_0, axis=0), self.direction) + + # step 4: computing normal vector of text direction + normal_vector = np.array([self.direction[1], -self.direction[0]]) + + # step 5: compute projection, avoid changing text blocks + _iou = section_iou(np.array([np.dot(top_1[0], normal_vector), np.dot(top_1[1], normal_vector)]), + np.array([np.dot(bottom_0[0], normal_vector), np.dot(bottom_0[1], normal_vector)])) + + # step 6: if in the same column (not switching blocks) + if bot_proj < top_proj and _iou > 0.1: + # step 7: promising continuous text line in same column cannot have same label + if determined[i]: + label[i + 1] = self.SINGLE_ENTRY if label[i]==self.DOUBLE_ENTRY else self.DOUBLE_ENTRY + elif determined[i+1]: + label[i] = self.SINGLE_ENTRY if label[i+1]==self.DOUBLE_ENTRY else self.DOUBLE_ENTRY + else: + if shorter_length[i] < shorter_length[i+1]: + label[i] = self.DOUBLE_ENTRY + label[i+1] = self.SINGLE_ENTRY + else: + label[i+1] = self.DOUBLE_ENTRY + label[i] = self.SINGLE_ENTRY + determined[i] = determined[i+1] = True + + # step 4: recompute cluster center + # using the mean of determined one to get the new center + if np.any((label == self.SINGLE_ENTRY) & (determined == True)): + cluster_center[self.SINGLE_ENTRY] = max(np.mean(shorter_length[(label == self.SINGLE_ENTRY) & (determined == True)]), + cluster_center[self.SINGLE_ENTRY]) + if np.any((label == self.DOUBLE_ENTRY) & (determined == True)): + cluster_center[self.DOUBLE_ENTRY] = min(np.mean(shorter_length[(label == self.DOUBLE_ENTRY) & (determined == True)]), + cluster_center[self.DOUBLE_ENTRY]) + + # step 5: using recompute center to determine the remain + for i in range(len(label)): + if determined[i]: + continue + label[i] = self.SINGLE_ENTRY if abs(shorter_length[i] - cluster_center[self.SINGLE_ENTRY]) \ + < abs(shorter_length[i] - cluster_center[self.DOUBLE_ENTRY]) else self.DOUBLE_ENTRY + determined[i] = True + + return label, cluster_center + + def compute_centerline(self, + points_a: NDArray, + points_b: NDArray): + """Computing centerline using sampled points and concatenate them nose + to tail. + Different shrink ratio may be used on single entries and double + entries. + + Args: + points_a(NDArray): shape-like (n, p, 2). + points_b(NDArray): shape-like (n, p, 2). + points_a and points_b are return value of function `uniform_curve_sampling`. + r(float): shrink ratio of centerline, the area will shrink to 1/r respect to + original polygon. + + Returns: + center_a, center_b(NDArray): having same shape as points_a, points_b. + center_a is the edge of centerline that near a, vice versa. + """ + r = self.shrink_ratio[self.labels][:, np.newaxis, np.newaxis] # (n, 1, 1) + theta = 0.5 - 1 / (2 * r) + + # (n, p, 2) + center_a = points_a * (1 - theta) + points_b * theta + center_b = points_a * theta + points_b * (1 - theta) + return np.concatenate([center_a, center_b[:, ::-1]], axis=1) # (n, 2p, 2) + + def preprocess(self): + self.reorder_polygon() + sample_a = np.zeros((self.num_instance, self.points, 2)) + sample_b = np.zeros((self.num_instance, self.points, 2)) + for i, poly in enumerate(self.polygons): + curve_a, curve_b = poly[:len(poly)//2], poly[len(poly)//2:][::-1] + sample_a[i] = uniform_curve_sampling(curve_a, self.points) + sample_b[i] = uniform_curve_sampling(curve_b, self.points) + shortside_length = self.determine_short_length(sample_a, sample_b) + self.labels, self.cluster_center = self.clustering_polygons(shortside_length) + self.preprocessed = True + + def get_length(self, curve): + segment_length = dist(curve, np.concatenate([curve[0:1], curve[:-1]], axis=0)) # (k, ) + accumulate_length = np.cumsum(segment_length) # (k, ) + curve_length = accumulate_length[-1] + return curve_length + + def vertical_aspect_ratio(self): + self.reorder_polygon() + sample_a = np.zeros((self.num_instance, self.points, 2)) + sample_b = np.zeros((self.num_instance, self.points, 2)) + longside_length = np.zeros((self.num_instance, )) + for i, poly in enumerate(self.polygons): + curve_a, curve_b = poly[:len(poly)//2], poly[len(poly)//2:][::-1] + sample_a[i] = uniform_curve_sampling(curve_a, self.points) + sample_b[i] = uniform_curve_sampling(curve_b, self.points) + longside_length[i] = (self.get_length(curve_a) + self.get_length(curve_b)) / 2 + shortside_length = self.determine_short_length(sample_a, sample_b) + return longside_length / shortside_length + + def aspect_ratio(self): + self.reorder_polygon() + sample_a = np.zeros((self.num_instance, self.points, 2)) + sample_b = np.zeros((self.num_instance, self.points, 2)) + longside_length = np.zeros((self.num_instance, )) + for i, poly in enumerate(self.polygons): + curve_a, curve_b = poly[:len(poly)//2], poly[len(poly)//2:][::-1] + sample_a[i] = uniform_curve_sampling(curve_a, self.points) + sample_b[i] = uniform_curve_sampling(curve_b, self.points) + longside_length[i] = (self.get_length(curve_a) + self.get_length(curve_b)) / 2 + shortside_length = self.determine_short_length(sample_a, sample_b) + return np.where(longside_length>shortside_length, + longside_length / shortside_length, + shortside_length / longside_length) + + def process(self): + self.reorder_polygon() + + sample_a = np.zeros((self.num_instance, self.points, 2)) + sample_b = np.zeros((self.num_instance, self.points, 2)) + for i, poly in enumerate(self.polygons): + curve_a, curve_b = poly[:len(poly)//2], poly[len(poly)//2:][::-1] + sample_a[i] = uniform_curve_sampling(curve_a, self.points) + sample_b[i] = uniform_curve_sampling(curve_b, self.points) + + if not getattr(self, "preprocessed", False): + shortside_length = self.determine_short_length(sample_a, sample_b) + self.labels, self.cluster_center = self.clustering_polygons(shortside_length) + + self.center_line = self.compute_centerline(sample_a, sample_b) # n, 2p, 2 + + def generate_kernelmap(self): + """Generate text center line map for single-line and double-line, respectively. + """ + if not getattr(self, 'image_shape', False): + warnings.warn('object don\'t have image_shape attr, cannot generate maps.') + return None, None + kernel_single = np.zeros(self.image_shape, dtype=np.uint8) + kernel_double = np.zeros(self.image_shape, dtype=np.uint8) + cv2.fillPoly(kernel_single, + self.center_line[self.labels==self.SINGLE_ENTRY].astype(np.int32), + 255) + cv2.fillPoly(kernel_double, + self.center_line[self.labels==self.DOUBLE_ENTRY].astype(np.int32), + 255) + return kernel_single, kernel_double + + def check_polygon_order(self): + """Checking polygon order after reorder polygons. + """ + for poly in self.polygons: + direction = compute_text_direction(poly) + if np.dot(direction, self.direction) < np.cos(np.pi/6): + print(f'may find fault direction in {getattr(self, "image_path", "")}, \ + direction difference: {np.dot(direction, self.direction)}') + + def output_json(self): + '''Adding labels to annotations when preprocessing. + Returning a list of dict that will behave as `data['instances']`. + ''' + results = [] + assert self.texts is not None, 'text is none, json cannot be creates.' + for poly, label, text in zip(self.polygons, self.labels, self.texts): + results.append(dict( + ignore=False, + text=text, + bbox_label=int(label), + polygon=poly.reshape(-1).astype(int).tolist() + )) + return results \ No newline at end of file diff --git a/seghist/utils/label_preprocess.py b/seghist/utils/label_preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf847be166ae0184128d8b5136eb01d43b0ca23 --- /dev/null +++ b/seghist/utils/label_preprocess.py @@ -0,0 +1,89 @@ +import json +from tqdm import tqdm +import os +import warnings + +import numpy as np +from PIL import Image +from sklearn.cluster import KMeans + +from seghist.utils.image_utils import ImageToolkits + +warnings.filterwarnings('ignore', category=np.RankWarning) + +def get_image_size(file_path): + with Image.open(file_path) as img: + return img.size + +def clean_redundant_points(poly): + ''' + clean redundant points when len(poly) % 2 != 0 + ''' + kmeans = KMeans(((len(poly)+1) // 2), n_init=3).fit(poly[:, 1:]) + cluster_counts = np.bincount(kmeans.labels_) + for i in range(len(cluster_counts)): + if cluster_counts[i] == 1: + for idx, l in enumerate(kmeans.labels_): + if l==i: + return np.concatenate([poly[:idx], poly[idx+1:]], axis=0) + +def main(root, + label_list, + data_prefix_list, + output_list, + separate_entry=True): + metainfo = {"dataset_type": "TextDetDataset", "task_name": "textdet", + "category": [{"id": 0, "name": "single_entry_text", + "id": 1, "name": "double_entry_text"}]} + for label, data_prefix, output in zip(label_list, data_prefix_list, output_list): + label = os.path.join(root, label) + datas = dict(metainfo=metainfo, data_list=[]) + with open(label) as f: + ann_file = json.load(f) + for img_path, instances in tqdm(ann_file.items()): + data = dict(img_path=img_path, instances=[]) + data['width'], data['height'] = get_image_size(os.path.join(root, data_prefix, img_path)) + for idx, inst in enumerate(instances): + # clean redundant points, if not in pair. + if len(inst['points']) % 4 != 0: + poly = np.array(inst['points']).reshape(-1, 2) + poly = clean_redundant_points(poly) + instances[idx]['points'] = poly.reshape(-1).tolist() + '''data["instances"].append(dict( + ignore=False, + text=inst['transcription'], + bbox_label=0, + polygon=inst['points'] + ))''' + if separate_entry: + hi = ImageToolkits([np.array(d['points']).reshape(-1, 2) for d in instances], + np.array((data['height'], data['width'])), + img_path, + texts=[d['transcription'] for d in instances]) + hi.process() + data['instances'] = hi.output_json() + else: + for idx, inst in enumerate(instances): + data["instances"].append(dict( + ignore=False, + text=inst['transcription'], + bbox_label=0, + polygon=inst['points'] + )) + datas['data_list'].append(data) + with open(os.path.join(root, output), mode='w') as f: + json.dump(datas, f) + +root = './data/historical_document/IACC2022_CHDAC/official_dataset' + +label_list = ['final/test/label_test.json', + 'final/train/label_train.json', + 'preliminary/train/label_train.json'] +data_prefix_list = ['final/test/image', + 'final/train/image', + 'preliminary/train/image'] +output_list = ['final/test/ocr_test.json', + 'final/train/ocr_train.json', + 'preliminary/train/ocr_train.json'] + +main(root, label_list, data_prefix_list, output_list) diff --git a/seghist/utils/poly_utils.py b/seghist/utils/poly_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..061776b65caf63ad73a8c96936910309775bbdc1 --- /dev/null +++ b/seghist/utils/poly_utils.py @@ -0,0 +1,187 @@ +from typing import Tuple, Sequence, Union, Optional + +import numpy as np +from shapely.geometry import Polygon, JOIN_STYLE +import cv2 + +from mmocr.utils.polygon_utils import poly_make_valid, offset_polygon + +def iou(poly1, poly2): + poly1 = Polygon(poly1) + poly2 = Polygon(poly2) + return poly1.intersection(poly2).area / poly1.union(poly2).area + +def get_distance(polygon: np.ndarray, + shrink_ratio: float, + ) -> float: + """ + Compute the shrinkage distance of a polygon with respect to a given + shrink ratio. This function is in reference to the PSENet approach. + + ALERT! distance is compute by A(1-r)/L not A(1-r^2)/L + + Args: + polygon (np.ndarray): An array representing the vertices of the polygon. + The shape of the array should be (num_points, 2), where each row represents + the (x, y) coordinates of a vertex. + shrink_ratio (float): The ratio by which the polygon is to be shrunk. + It's a value less than 1, where 1 means no shrinkage. + + Returns: + distance(float): The calculated distance by which the polygon should + be shrunk. + """ + poly = polygon.reshape(-1, 2) + poly_obj = Polygon(poly) + area = poly_obj.area + peri = poly_obj.length + distance = area * (1 - shrink_ratio) / (peri + 1e-5) + return distance + +def expand_poly( + polygon: np.ndarray, + shrink_ratio: float, + stretch_ratio: float, + ) -> np.ndarray: + """Generate text instance kernels according to a shrink ratio. + + Args: + polygon (np.ndarray): array of text polygons. + + Returns: + polygon after expansion by TKS. + """ + poly = polygon.copy().reshape(-1, 2).astype(np.float32) + distance = get_distance(poly, shrink_ratio) + + # stretching on horizental + poly[:, 0] *= stretch_ratio + + # no splits happen in expansion + poly = poly_make_valid(Polygon(poly)) + expand_poly = np.array(poly.buffer(distance, + ).exterior.coords) + expand_poly = expand_poly.reshape(-1, 2).astype(np.float32) + expand_poly[:, 0] /= stretch_ratio + + return expand_poly + +def stretch_kernel( + polygon: np.ndarray, + shrink_ratio: float, + stretch_ratio: float, + ) -> np.ndarray: + poly = polygon.copy().reshape(-1, 2).astype(np.float32) + + # get shrink distance before stretching + distance = get_distance(poly, shrink_ratio) + + # stretch on x-axis + poly[:, 0] *= stretch_ratio + + # shrink poly + shrunk_poly = Polygon(poly).buffer(-distance) + + # if splits into multiple parts + if not isinstance(shrunk_poly, Polygon): + return np.array([]).reshape(0,2) + + shrunk_poly = np.array(shrunk_poly.exterior.coords) + + # shrink to NULL + if len(shrunk_poly) == 0: + return shrunk_poly + + shrunk_poly = shrunk_poly.reshape(-1, 2).astype(np.float32) + shrunk_poly[:, 0] /= stretch_ratio + return shrunk_poly + +def unstretch_kernel(poly_pts: np.ndarray, + shrink_ratio: float, + stretch_ratio: float, + refinement: bool = True, + unclip_ratio: float = 0, + refine_epoch: int = 30, + step_size: float = 1.0, + tolerance: float = 0.4) -> np.ndarray: + """Unclip a polygon either adaptively or by fixed ratio. + Only used in postprocessor. + + Args: + poly_pts (np.ndarray): The polygon points. + shrink_ratio(float): r used in module loss. + refinement(bool): whether doing refinement, if `refinement=false`, + then unclip polygons by fixed ratio `unclip_ratio`. + + Returns: + np.ndarray: The expanded polygon points. + """ + poly_pts = poly_pts.copy().reshape(-1, 2) + poly = poly_pts.astype(np.float32) + + if refinement: + # unclip adaptively + _, (_x, _y), _ = cv2.minAreaRect(poly) + poly[:, 0] *= stretch_ratio + _, (_kx, _ky), _ = cv2.minAreaRect(poly) + + # adaptive distance: distance nearly same as shrink + # b is approximate (Maintaining rotation symmetry) + a = 4 * (1 / stretch_ratio + 1) - 4 / stretch_ratio * (1 - shrink_ratio) + b = 2 * (_x + _y) - 2 / stretch_ratio * (_kx + _ky) * (1 - shrink_ratio) + c = - _x * _y * (1 - shrink_ratio) + distance = (- b + np.sqrt(b ** 2 - 4 * a * c)) / (2 * a) + assert distance >= 0, 'dilate should have d > 0' + step_size = max(distance / 2, step_size) + else: + # by fixed ratio + p = Polygon(poly) + distance = p.area * unclip_ratio / p.length + poly[:, 0] *= stretch_ratio + refine_epoch = 0 + + poly = poly_make_valid(Polygon(poly)) + expand_poly = poly.buffer(distance, ) + expand_poly = np.array(expand_poly.exterior.coords) + expand_poly[:, 0] /= stretch_ratio + + greater = None + for _ in range(refine_epoch): + # get shrink distance from newly recovered polygon + distance_0 = get_distance(expand_poly, shrink_ratio) + + if distance_0 > distance + tolerance: + if greater is not None and not greater: + # scale step + step_size /= 2 + greater = True + distance += step_size + elif distance_0 < distance - tolerance: + if greater: + # scale step + step_size /= 2 + greater = False + distance -= step_size + distance = max(distance, 0) + else: + break + expand_poly = poly.buffer(distance) + expand_poly = np.array(expand_poly.exterior.coords) + expand_poly[:, 0] /= stretch_ratio + + return expand_poly + +def align_polygon(polygon: np.ndarray, stride: int) -> np.ndarray: + return (polygon / stride) - (stride - 1) / (2 * stride) + +def fill_hole(binary_image): + floodfilled = binary_image.copy() + + h, w = binary_image.shape[:2] + mask = np.zeros((h+2, w+2), np.uint8) + + cv2.floodFill(floodfilled, mask, (0, 0), 255) + floodfilled_inv = cv2.bitwise_not(floodfilled) + out_image = binary_image | floodfilled_inv + + return out_image diff --git a/seghist/utils/toy_label_generation.py b/seghist/utils/toy_label_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..597b3027f2e0ef4df4f62b49dca9613fb272f565 --- /dev/null +++ b/seghist/utils/toy_label_generation.py @@ -0,0 +1,18 @@ +import json +import os +import random + +def main(root, label, output, sample=1): + label = os.path.join(root, label) + with open(label) as f: + ann_file = json.load(f) + datas = dict(metainfo=ann_file['metainfo']) + datas['data_list']=random.sample(ann_file['data_list'], sample) + with open(os.path.join(root, output), mode='w') as f: + json.dump(datas, f) + + +root = './data/historical_document/IACC2022_CHDAC/official_dataset' +label ='final/train/ocr_train.json' +output = 'final/train/ocr_toy.json' +main(root, label, output) \ No newline at end of file diff --git a/seghist/utils/vis_ocr_results.py b/seghist/utils/vis_ocr_results.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6f1d2a35c1f57592c9517fb9eb9863c7027674 --- /dev/null +++ b/seghist/utils/vis_ocr_results.py @@ -0,0 +1,134 @@ +import json +from tqdm import tqdm +import os +from PIL import Image, ImageDraw,ImageFont + +import urllib +import shutil + +import mmcv +import cv2 +import numpy as np + +from seghist.utils.visualize import draw_polygons, is_contain_chinese, draw_texts, gen_color + +def draw_texts_by_pil(img, + texts, + boxes=None, + draw_box=True, + on_ori_img=False, + font_size=None, + fill_color=None, + draw_pos=None, + return_text_size=False): + """Draw boxes and texts on empty image, especially for Chinese. + + Args: + img (np.ndarray): The original image. + texts (list[str]): Recognized texts. + boxes (list[list[float]]): Detected bounding boxes. + draw_box (bool): Whether draw box or not. If False, draw text only. + on_ori_img (bool): If True, draw box and text on input image, + else on a new empty image. + font_size (int, optional): Size to create a font object for a font. + fill_color (tuple(int), optional): Fill color for text. + draw_pos (list[tuple(int)], optional): Start point to draw each text. + return_text_size (bool): If True, return the list of text size. + + Returns: + (np.ndarray, list[tuple]) or np.ndarray: Return a tuple + ``(out_img, text_sizes)``, where ``out_img`` is the output image + with texts drawn on it and ``text_sizes`` are the size of drawing + texts. If ``return_text_size`` is False, only the output image will be + returned. + """ + + color_list = gen_color() + h, w = img.shape[:2] + if boxes is None: + boxes = [[0, 0, w, 0, w, h, 0, h]] + if draw_pos is None: + draw_pos = [None for _ in texts] + assert len(boxes) == len(texts) == len(draw_pos) + + if fill_color is None: + fill_color = (0, 0, 0) + + if on_ori_img: + out_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + else: + out_img = Image.new('RGB', (w, h), color=(255, 255, 255)) + out_draw = ImageDraw.Draw(out_img) + + text_sizes = [] + for idx, (box, text, ori_point) in enumerate(zip(boxes, texts, draw_pos)): + if len(text) == 0: + continue + min_x, max_x = min(box[0::2]), max(box[0::2]) + min_y, max_y = min(box[1::2]), max(box[1::2]) + color = tuple(list(color_list[idx % len(color_list)])[::-1]) + if draw_box: + out_draw.line(box, fill=color, width=1) + dirname = './utils/fonts' + font_path = os.path.join(dirname, 'font.TTF') + if not os.path.exists(font_path): + url = ('https://download.openmmlab.com/mmocr/data/font.TTF') + print(f'Downloading {url} ...') + local_filename, _ = urllib.request.urlretrieve(url) + shutil.move(local_filename, font_path) + tmp_font_size = font_size + if tmp_font_size is None: + tmp_font_size = min(int(0.9 * (max_y - min_y) / len(text)), int((max_x - min_x) * 0.6)) + fnt = ImageFont.truetype(font_path, tmp_font_size) + if ori_point is None: + ori_point = (min_x + 1, min_y + 1) + out_draw.text(ori_point, text, font=fnt, fill=fill_color, direction='ttb') + + text_sizes.append(fnt.getsize(text)) + + del out_draw + + out_img = cv2.cvtColor(np.asarray(out_img), cv2.COLOR_RGB2BGR) + + if return_text_size: + return out_img, text_sizes + + return out_img + + +def visualize_one_sample(img, boxes, texts): + img = mmcv.imread(img) + box_vis_img = draw_polygons(img, boxes) + if is_contain_chinese(''.join(texts)): + text_vis_img = draw_texts_by_pil(img, texts, boxes, draw_box=False, font_size=None) + else: + text_vis_img = draw_texts(img, texts, boxes, draw_box=False) + + h, w = img.shape[:2] + out_img = np.ones((h * 2, w, 3), dtype=np.uint8) + out_img[:h, :, :] = box_vis_img + out_img[h:, :, :] = text_vis_img + return out_img + +def visualize(result_dir, image_dir, save_dir): + image_list = [f for f in os.listdir(image_dir) if not os.path.isdir(os.path.join(image_dir, f))] + os.makedirs(save_dir, exist_ok=True) + for res_fn, img_fn in tqdm(zip(sorted(os.listdir(result_dir)), + sorted(image_list))): + img_fp = os.path.join(image_dir, img_fn) + with open(os.path.join(result_dir, res_fn)) as f: + data_list = json.load(f) + boxes, texts = [], [] + for data in data_list: + boxes.append(data['polygon']) + texts.append(data['text']) + out_img = visualize_one_sample(img_fp, boxes, texts) + save_fp = os.path.join(save_dir, img_fn) + mmcv.imwrite(out_img, save_fp) + + +def main(): + result = '/home/huxingjian/model/mmocr/projects/PFRNet/project_samples/recog_results' + image = '/home/huxingjian/model/mmocr/projects/PFRNet/project_samples' + vis = '/home/huxingjian/model/mmocr/projects/PFRNet/project_samples/vis_results' + visualize(result, image, vis) \ No newline at end of file diff --git a/seghist/utils/visualize.py b/seghist/utils/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..35ccdaf523c60f331b5541fd21e460bfb2d59870 --- /dev/null +++ b/seghist/utils/visualize.py @@ -0,0 +1,888 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import os +import shutil +import urllib +import warnings + +import cv2 +import mmcv +import numpy as np +import torch +from matplotlib import pyplot as plt +from PIL import Image, ImageDraw, ImageFont + +import mmocr.utils as utils + + +def overlay_mask_img(img, mask): + """Draw mask boundaries on image for visualization. + + Args: + img (ndarray): The input image. + mask (ndarray): The instance mask. + + Returns: + img (ndarray): The output image with instance boundaries on it. + """ + assert isinstance(img, np.ndarray) + assert isinstance(mask, np.ndarray) + + contours, _ = cv2.findContours( + mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + cv2.drawContours(img, contours, -1, (0, 255, 0), 1) + + return img + + +def show_feature(features, names, to_uint8, out_file=None): + """Visualize a list of feature maps. + + Args: + features (list(ndarray)): The feature map list. + names (list(str)): The visualized title list. + to_uint8 (list(1|0)): The list indicating whether to convent + feature maps to uint8. + out_file (str): The output file name. If set to None, + the output image will be shown without saving. + """ + assert utils.is_type_list(features, np.ndarray) + assert utils.is_type_list(names, str) + assert utils.is_type_list(to_uint8, int) + assert utils.is_none_or_type(out_file, str) + assert utils.equal_len(features, names, to_uint8) + + num = len(features) + row = col = math.ceil(math.sqrt(num)) + + for i, (f, n) in enumerate(zip(features, names)): + plt.subplot(row, col, i + 1) + plt.title(n) + if to_uint8[i]: + f = f.astype(np.uint8) + plt.imshow(f) + if out_file is None: + plt.show() + else: + plt.savefig(out_file) + + +def show_img_boundary(img, boundary): + """Show image and instance boundaires. + + Args: + img (ndarray): The input image. + boundary (list[float or int]): The input boundary. + """ + assert isinstance(img, np.ndarray) + assert utils.is_type_list(boundary, (int, float)) + + cv2.polylines( + img, [np.array(boundary).astype(np.int32).reshape(-1, 1, 2)], + True, + color=(0, 255, 0), + thickness=1) + plt.imshow(img) + plt.show() + + +def show_pred_gt(preds, + gts, + show=False, + win_name='', + wait_time=0, + out_file=None): + """Show detection and ground truth for one image. + + Args: + preds (list[list[float]]): The detection boundary list. + gts (list[list[float]]): The ground truth boundary list. + show (bool): Whether to show the image. + win_name (str): The window name. + wait_time (int): The value of waitKey param. + out_file (str): The filename of the output. + """ + assert utils.is_2dlist(preds) + assert utils.is_2dlist(gts) + assert isinstance(show, bool) + assert isinstance(win_name, str) + assert isinstance(wait_time, int) + assert utils.is_none_or_type(out_file, str) + + p_xy = [p for boundary in preds for p in boundary] + gt_xy = [g for gt in gts for g in gt] + + max_xy = np.max(np.array(p_xy + gt_xy).reshape(-1, 2), axis=0) + + width = int(max_xy[0]) + 100 + height = int(max_xy[1]) + 100 + + img = np.ones((height, width, 3), np.int8) * 255 + pred_color = mmcv.color_val('red') + gt_color = mmcv.color_val('blue') + thickness = 1 + + for boundary in preds: + cv2.polylines( + img, [np.array(boundary).astype(np.int32).reshape(-1, 1, 2)], + True, + color=pred_color, + thickness=thickness) + for gt in gts: + cv2.polylines( + img, [np.array(gt).astype(np.int32).reshape(-1, 1, 2)], + True, + color=gt_color, + thickness=thickness) + if show: + mmcv.imshow(img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(img, out_file) + + return img + + +def imshow_pred_boundary(img, + boundaries_with_scores, + labels, + score_thr=0, + boundary_color='blue', + text_color='blue', + thickness=1, + font_scale=0.5, + show=True, + win_name='', + wait_time=0, + out_file=None, + show_score=False): + """Draw boundaries and class labels (with scores) on an image. + + Args: + img (str or ndarray): The image to be displayed. + boundaries_with_scores (list[list[float]]): Boundaries with scores. + labels (list[int]): Labels of boundaries. + score_thr (float): Minimum score of boundaries to be shown. + boundary_color (str or tuple or :obj:`Color`): Color of boundaries. + text_color (str or tuple or :obj:`Color`): Color of texts. + thickness (int): Thickness of lines. + font_scale (float): Font scales of texts. + show (bool): Whether to show the image. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + out_file (str or None): The filename of the output. + show_score (bool): Whether to show text instance score. + """ + assert isinstance(img, (str, np.ndarray)) + assert utils.is_2dlist(boundaries_with_scores) + assert utils.is_type_list(labels, int) + assert utils.equal_len(boundaries_with_scores, labels) + if len(boundaries_with_scores) == 0: + warnings.warn('0 text found in ' + out_file) + return None + + utils.valid_boundary(boundaries_with_scores[0]) + img = mmcv.imread(img) + + scores = np.array([b[-1] for b in boundaries_with_scores]) + inds = scores > score_thr + boundaries = [boundaries_with_scores[i][:-1] for i in np.where(inds)[0]] + scores = [scores[i] for i in np.where(inds)[0]] + labels = [labels[i] for i in np.where(inds)[0]] + + boundary_color = mmcv.color_val(boundary_color) + text_color = mmcv.color_val(text_color) + font_scale = 0.5 + + for boundary, score in zip(boundaries, scores): + boundary_int = np.array(boundary).astype(np.int32) + + cv2.polylines( + img, [boundary_int.reshape(-1, 1, 2)], + True, + color=boundary_color, + thickness=thickness) + + if show_score: + label_text = f'{score:.02f}' + cv2.putText(img, label_text, + (boundary_int[0], boundary_int[1] - 2), + cv2.FONT_HERSHEY_COMPLEX, font_scale, text_color) + if show: + mmcv.imshow(img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(img, out_file) + + return img + + +def imshow_text_char_boundary(img, + text_quads, + boundaries, + char_quads, + chars, + show=False, + thickness=1, + font_scale=0.5, + win_name='', + wait_time=-1, + out_file=None): + """Draw text boxes and char boxes on img. + + Args: + img (str or ndarray): The img to be displayed. + text_quads (list[list[int|float]]): The text boxes. + boundaries (list[list[int|float]]): The boundary list. + char_quads (list[list[list[int|float]]]): A 2d list of char boxes. + char_quads[i] is for the ith text, and char_quads[i][j] is the jth + char of the ith text. + chars (list[list[char]]). The string for each text box. + thickness (int): Thickness of lines. + font_scale (float): Font scales of texts. + show (bool): Whether to show the image. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + out_file (str or None): The filename of the output. + """ + assert isinstance(img, (np.ndarray, str)) + assert utils.is_2dlist(text_quads) + assert utils.is_2dlist(boundaries) + assert utils.is_3dlist(char_quads) + assert utils.is_2dlist(chars) + assert utils.equal_len(text_quads, char_quads, boundaries) + + img = mmcv.imread(img) + char_color = [mmcv.color_val('blue'), mmcv.color_val('green')] + text_color = mmcv.color_val('red') + text_inx = 0 + for text_box, boundary, char_box, txt in zip(text_quads, boundaries, + char_quads, chars): + text_box = np.array(text_box) + boundary = np.array(boundary) + + text_box = text_box.reshape(-1, 2).astype(np.int32) + cv2.polylines( + img, [text_box.reshape(-1, 1, 2)], + True, + color=text_color, + thickness=thickness) + if boundary.shape[0] > 0: + cv2.polylines( + img, [boundary.reshape(-1, 1, 2)], + True, + color=text_color, + thickness=thickness) + + for b in char_box: + b = np.array(b) + c = char_color[text_inx % 2] + b = b.astype(np.int32) + cv2.polylines( + img, [b.reshape(-1, 1, 2)], True, color=c, thickness=thickness) + + label_text = ''.join(txt) + cv2.putText(img, label_text, (text_box[0, 0], text_box[0, 1] - 2), + cv2.FONT_HERSHEY_COMPLEX, font_scale, text_color) + text_inx = text_inx + 1 + + if show: + mmcv.imshow(img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(img, out_file) + + return img + + +def tile_image(images): + """Combined multiple images to one vertically. + + Args: + images (list[np.ndarray]): Images to be combined. + """ + assert isinstance(images, list) + assert len(images) > 0 + + for i, _ in enumerate(images): + if len(images[i].shape) == 2: + images[i] = cv2.cvtColor(images[i], cv2.COLOR_GRAY2BGR) + + widths = [img.shape[1] for img in images] + heights = [img.shape[0] for img in images] + h, w = sum(heights), max(widths) + vis_img = np.zeros((h, w, 3), dtype=np.uint8) + + offset_y = 0 + for image in images: + img_h, img_w = image.shape[:2] + vis_img[offset_y:(offset_y + img_h), 0:img_w, :] = image + offset_y += img_h + + return vis_img + + +def imshow_text_label(img, + pred_label, + gt_label, + show=False, + win_name='', + wait_time=-1, + out_file=None): + """Draw predicted texts and ground truth texts on images. + + Args: + img (str or np.ndarray): Image filename or loaded image. + pred_label (str): Predicted texts. + gt_label (str): Ground truth texts. + show (bool): Whether to show the image. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + out_file (str): The filename of the output. + """ + assert isinstance(img, (np.ndarray, str)) + assert isinstance(pred_label, str) + assert isinstance(gt_label, str) + assert isinstance(show, bool) + assert isinstance(win_name, str) + assert isinstance(wait_time, int) + + img = mmcv.imread(img) + + src_h, src_w = img.shape[:2] + resize_height = 64 + resize_width = int(1.0 * src_w / src_h * resize_height) + img = cv2.resize(img, (resize_width, resize_height)) + h, w = img.shape[:2] + + if is_contain_chinese(pred_label): + pred_img = draw_texts_by_pil(img, [pred_label], None) + else: + pred_img = np.ones((h, w, 3), dtype=np.uint8) * 255 + cv2.putText(pred_img, pred_label, (5, 40), cv2.FONT_HERSHEY_SIMPLEX, + 0.9, (0, 0, 255), 2) + images = [pred_img, img] + + if gt_label != '': + if is_contain_chinese(gt_label): + gt_img = draw_texts_by_pil(img, [gt_label], None) + else: + gt_img = np.ones((h, w, 3), dtype=np.uint8) * 255 + cv2.putText(gt_img, gt_label, (5, 40), cv2.FONT_HERSHEY_SIMPLEX, + 0.9, (255, 0, 0), 2) + images.append(gt_img) + + img = tile_image(images) + + if show: + mmcv.imshow(img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(img, out_file) + + return img + + +def imshow_node(img, + result, + boxes, + idx_to_cls={}, + show=False, + win_name='', + wait_time=-1, + out_file=None): + + img = mmcv.imread(img) + h, w = img.shape[:2] + + max_value, max_idx = torch.max(result['nodes'].detach().cpu(), -1) + node_pred_label = max_idx.numpy().tolist() + node_pred_score = max_value.numpy().tolist() + + texts, text_boxes = [], [] + for i, box in enumerate(boxes): + new_box = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], + [box[0], box[3]]] + Pts = np.array([new_box], np.int32) + cv2.polylines( + img, [Pts.reshape((-1, 1, 2))], + True, + color=(255, 255, 0), + thickness=1) + x_min = int(min([point[0] for point in new_box])) + y_min = int(min([point[1] for point in new_box])) + + # text + pred_label = str(node_pred_label[i]) + if pred_label in idx_to_cls: + pred_label = idx_to_cls[pred_label] + pred_score = '{:.2f}'.format(node_pred_score[i]) + text = pred_label + '(' + pred_score + ')' + texts.append(text) + + # text box + font_size = int( + min( + abs(new_box[3][1] - new_box[0][1]), + abs(new_box[1][0] - new_box[0][0]))) + char_num = len(text) + text_box = [ + x_min * 2, y_min, x_min * 2 + font_size * char_num, y_min, + x_min * 2 + font_size * char_num, y_min + font_size, x_min * 2, + y_min + font_size + ] + text_boxes.append(text_box) + + pred_img = np.ones((h, w * 2, 3), dtype=np.uint8) * 255 + pred_img = draw_texts_by_pil( + pred_img, texts, text_boxes, draw_box=False, on_ori_img=True) + + vis_img = np.ones((h, w * 3, 3), dtype=np.uint8) * 255 + vis_img[:, :w] = img + vis_img[:, w:] = pred_img + + if show: + mmcv.imshow(vis_img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(vis_img, out_file) + + return vis_img + + +def gen_color(): + """Generate BGR color schemes.""" + color_list = [(101, 67, 254), (154, 157, 252), (173, 205, 249), + (123, 151, 138), (187, 200, 178), (148, 137, 69), + (169, 200, 200), (155, 175, 131), (154, 194, 182), + (178, 190, 137), (140, 211, 222), (83, 156, 222)] + return color_list + + +def draw_polygons(img, polys): + """Draw polygons on image. + + Args: + img (np.ndarray): The original image. + polys (list[list[float]]): Detected polygons. + Return: + out_img (np.ndarray): Visualized image. + """ + dst_img = img.copy() + color_list = gen_color() + out_img = dst_img + for idx, poly in enumerate(polys): + poly = np.array(poly).reshape((-1, 1, 2)).astype(np.int32) + cv2.drawContours( + img, + np.array([poly]), + -1, + color_list[idx % len(color_list)], + thickness=cv2.FILLED) + out_img = cv2.addWeighted(dst_img, 0.5, img, 0.5, 0) + return out_img + + +def get_optimal_font_scale(text, width): + """Get optimal font scale for cv2.putText. + + Args: + text (str): Text in one box. + width (int): The box width. + """ + for scale in reversed(range(0, 60, 1)): + textSize = cv2.getTextSize( + text, + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=scale / 10, + thickness=1) + new_width = textSize[0][0] + if new_width <= width: + return scale / 10 + return 1 + + +def draw_texts(img, texts, boxes=None, draw_box=True, on_ori_img=False): + """Draw boxes and texts on empty img. + + Args: + img (np.ndarray): The original image. + texts (list[str]): Recognized texts. + boxes (list[list[float]]): Detected bounding boxes. + draw_box (bool): Whether draw box or not. If False, draw text only. + on_ori_img (bool): If True, draw box and text on input image, + else, on a new empty image. + Return: + out_img (np.ndarray): Visualized image. + """ + color_list = gen_color() + h, w = img.shape[:2] + if boxes is None: + boxes = [[0, 0, w, 0, w, h, 0, h]] + assert len(texts) == len(boxes) + + if on_ori_img: + out_img = img + else: + out_img = np.ones((h, w, 3), dtype=np.uint8) * 255 + for idx, (box, text) in enumerate(zip(boxes, texts)): + if draw_box: + new_box = [[x, y] for x, y in zip(box[0::2], box[1::2])] + Pts = np.array([new_box], np.int32) + cv2.polylines( + out_img, [Pts.reshape((-1, 1, 2))], + True, + color=color_list[idx % len(color_list)], + thickness=1) + min_x = int(min(box[0::2])) + max_y = int( + np.mean(np.array(box[1::2])) + 0.2 * + (max(box[1::2]) - min(box[1::2]))) + font_scale = get_optimal_font_scale( + text, int(max(box[0::2]) - min(box[0::2]))) + cv2.putText(out_img, text, (min_x, max_y), cv2.FONT_HERSHEY_SIMPLEX, + font_scale, (0, 0, 0), 1) + + return out_img + + +def draw_texts_by_pil(img, + texts, + boxes=None, + draw_box=True, + on_ori_img=False, + font_size=None, + fill_color=None, + draw_pos=None, + return_text_size=False): + """Draw boxes and texts on empty image, especially for Chinese. + + Args: + img (np.ndarray): The original image. + texts (list[str]): Recognized texts. + boxes (list[list[float]]): Detected bounding boxes. + draw_box (bool): Whether draw box or not. If False, draw text only. + on_ori_img (bool): If True, draw box and text on input image, + else on a new empty image. + font_size (int, optional): Size to create a font object for a font. + fill_color (tuple(int), optional): Fill color for text. + draw_pos (list[tuple(int)], optional): Start point to draw each text. + return_text_size (bool): If True, return the list of text size. + + Returns: + (np.ndarray, list[tuple]) or np.ndarray: Return a tuple + ``(out_img, text_sizes)``, where ``out_img`` is the output image + with texts drawn on it and ``text_sizes`` are the size of drawing + texts. If ``return_text_size`` is False, only the output image will be + returned. + """ + + color_list = gen_color() + h, w = img.shape[:2] + if boxes is None: + boxes = [[0, 0, w, 0, w, h, 0, h]] + if draw_pos is None: + draw_pos = [None for _ in texts] + assert len(boxes) == len(texts) == len(draw_pos) + + if fill_color is None: + fill_color = (0, 0, 0) + + if on_ori_img: + out_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + else: + out_img = Image.new('RGB', (w, h), color=(255, 255, 255)) + out_draw = ImageDraw.Draw(out_img) + + text_sizes = [] + for idx, (box, text, ori_point) in enumerate(zip(boxes, texts, draw_pos)): + if len(text) == 0: + continue + min_x, max_x = min(box[0::2]), max(box[0::2]) + min_y, max_y = min(box[1::2]), max(box[1::2]) + color = tuple(list(color_list[idx % len(color_list)])[::-1]) + if draw_box: + out_draw.line(box, fill=color, width=1) + dirname, _ = os.path.split(os.path.abspath(__file__)) + font_path = os.path.join(dirname, 'font.TTF') + if not os.path.exists(font_path): + url = ('https://download.openmmlab.com/mmocr/data/font.TTF') + print(f'Downloading {url} ...') + local_filename, _ = urllib.request.urlretrieve(url) + shutil.move(local_filename, font_path) + tmp_font_size = font_size + if tmp_font_size is None: + box_width = max(max_x - min_x, max_y - min_y) + tmp_font_size = int(0.9 * box_width / len(text)) + fnt = ImageFont.truetype(font_path, tmp_font_size) + if ori_point is None: + ori_point = (min_x + 1, min_y + 1) + out_draw.text(ori_point, text, font=fnt, fill=fill_color) + text_sizes.append(fnt.getsize(text)) + + del out_draw + + out_img = cv2.cvtColor(np.asarray(out_img), cv2.COLOR_RGB2BGR) + + if return_text_size: + return out_img, text_sizes + + return out_img + + +def is_contain_chinese(check_str): + """Check whether string contains Chinese or not. + + Args: + check_str (str): String to be checked. + + Return True if contains Chinese, else False. + """ + for ch in check_str: + if u'\u4e00' <= ch <= u'\u9fff': + return True + return False + + +def det_recog_show_result(img, end2end_res, out_file=None): + """Draw `result`(boxes and texts) on `img`. + + Args: + img (str or np.ndarray): The image to be displayed. + end2end_res (dict): Text detect and recognize results. + out_file (str): Image path where the visualized image should be saved. + Return: + out_img (np.ndarray): Visualized image. + """ + img = mmcv.imread(img) + boxes, texts = [], [] + for res in end2end_res['result']: + boxes.append(res['box']) + texts.append(res['text']) + box_vis_img = draw_polygons(img, boxes) + + if is_contain_chinese(''.join(texts)): + text_vis_img = draw_texts_by_pil(img, texts, boxes) + else: + text_vis_img = draw_texts(img, texts, boxes) + + h, w = img.shape[:2] + out_img = np.ones((h, w * 2, 3), dtype=np.uint8) + out_img[:, :w, :] = box_vis_img + out_img[:, w:, :] = text_vis_img + + if out_file: + mmcv.imwrite(out_img, out_file) + + return out_img + + +def draw_edge_result(img, result, edge_thresh=0.5, keynode_thresh=0.5): + """Draw text and their relationship on empty images. + + Args: + img (np.ndarray): The original image. + result (dict): The result of model forward_test, including: + - img_metas (list[dict]): List of meta information dictionary. + - nodes (Tensor): Node prediction with size: + number_node * node_classes. + - edges (Tensor): Edge prediction with size: number_edge * 2. + edge_thresh (float): Score threshold for edge classification. + keynode_thresh (float): Score threshold for node + (``key``) classification. + + Returns: + np.ndarray: The image with key, value and relation drawn on it. + """ + + h, w = img.shape[:2] + + vis_area_width = w // 3 * 2 + vis_area_height = h + dist_key_to_value = vis_area_width // 2 + dist_pair_to_pair = 30 + + bbox_x1 = dist_pair_to_pair + bbox_y1 = 0 + + new_w = vis_area_width + new_h = vis_area_height + pred_edge_img = np.ones((new_h, new_w, 3), dtype=np.uint8) * 255 + + nodes = result['nodes'].detach().cpu() + texts = result['img_metas'][0]['ori_texts'] + num_nodes = result['nodes'].size(0) + edges = result['edges'].detach().cpu()[:, -1].view(num_nodes, num_nodes) + + # (i, j) will be a valid pair + # either edge_score(node_i->node_j) > edge_thresh + # or edge_score(node_j->node_i) > edge_thresh + pairs = (torch.max(edges, edges.T) > edge_thresh).nonzero(as_tuple=True) + pairs = (pairs[0].numpy().tolist(), pairs[1].numpy().tolist()) + + # 1. "for n1, n2 in zip(*pairs) if n1 < n2": + # Only (n1, n2) will be included if n1 < n2 but not (n2, n1), to + # avoid duplication. + # 2. "(n1, n2) if nodes[n1, 1] > nodes[n1, 2]": + # nodes[n1, 1] is the score that this node is predicted as key, + # nodes[n1, 2] is the score that this node is predicted as value. + # If nodes[n1, 1] > nodes[n1, 2], n1 will be the index of key, + # so that n2 will be the index of value. + result_pairs = [(n1, n2) if nodes[n1, 1] > nodes[n1, 2] else (n2, n1) + for n1, n2 in zip(*pairs) if n1 < n2] + + result_pairs.sort() + result_pairs_score = [ + torch.max(edges[n1, n2], edges[n2, n1]) for n1, n2 in result_pairs + ] + + key_current_idx = -1 + pos_current = (-1, -1) + newline_flag = False + + key_font_size = 15 + value_font_size = 15 + key_font_color = (0, 0, 0) + value_font_color = (0, 0, 255) + arrow_color = (0, 0, 255) + score_color = (0, 255, 0) + for pair, pair_score in zip(result_pairs, result_pairs_score): + key_idx = pair[0] + if nodes[key_idx, 1] < keynode_thresh: + continue + if key_idx != key_current_idx: + # move y-coords down for a new key + bbox_y1 += 10 + # enlarge blank area to show key-value info + if newline_flag: + bbox_x1 += vis_area_width + tmp_img = np.ones( + (new_h, new_w + vis_area_width, 3), dtype=np.uint8) * 255 + tmp_img[:new_h, :new_w] = pred_edge_img + pred_edge_img = tmp_img + new_w += vis_area_width + newline_flag = False + bbox_y1 = 10 + key_text = texts[key_idx] + key_pos = (bbox_x1, bbox_y1) + value_idx = pair[1] + value_text = texts[value_idx] + value_pos = (bbox_x1 + dist_key_to_value, bbox_y1) + if key_idx != key_current_idx: + # draw text for a new key + key_current_idx = key_idx + pred_edge_img, text_sizes = draw_texts_by_pil( + pred_edge_img, [key_text], + draw_box=False, + on_ori_img=True, + font_size=key_font_size, + fill_color=key_font_color, + draw_pos=[key_pos], + return_text_size=True) + pos_right_bottom = (key_pos[0] + text_sizes[0][0], + key_pos[1] + text_sizes[0][1]) + pos_current = (pos_right_bottom[0] + 5, bbox_y1 + 10) + pred_edge_img = cv2.arrowedLine( + pred_edge_img, (pos_right_bottom[0] + 5, bbox_y1 + 10), + (bbox_x1 + dist_key_to_value - 5, bbox_y1 + 10), arrow_color, + 1) + score_pos_x = int( + (pos_right_bottom[0] + bbox_x1 + dist_key_to_value) / 2.) + score_pos_y = bbox_y1 + 10 - int(key_font_size * 0.3) + else: + # draw arrow from key to value + if newline_flag: + tmp_img = np.ones((new_h + dist_pair_to_pair, new_w, 3), + dtype=np.uint8) * 255 + tmp_img[:new_h, :new_w] = pred_edge_img + pred_edge_img = tmp_img + new_h += dist_pair_to_pair + pred_edge_img = cv2.arrowedLine(pred_edge_img, pos_current, + (bbox_x1 + dist_key_to_value - 5, + bbox_y1 + 10), arrow_color, 1) + score_pos_x = int( + (pos_current[0] + bbox_x1 + dist_key_to_value - 5) / 2.) + score_pos_y = int((pos_current[1] + bbox_y1 + 10) / 2.) + # draw edge score + cv2.putText(pred_edge_img, '{:.2f}'.format(pair_score), + (score_pos_x, score_pos_y), cv2.FONT_HERSHEY_COMPLEX, 0.4, + score_color) + # draw text for value + pred_edge_img = draw_texts_by_pil( + pred_edge_img, [value_text], + draw_box=False, + on_ori_img=True, + font_size=value_font_size, + fill_color=value_font_color, + draw_pos=[value_pos], + return_text_size=False) + bbox_y1 += dist_pair_to_pair + if bbox_y1 + dist_pair_to_pair >= new_h: + newline_flag = True + + return pred_edge_img + + +def imshow_edge(img, + result, + boxes, + show=False, + win_name='', + wait_time=-1, + out_file=None): + """Display the prediction results of the nodes and edges of the KIE model. + + Args: + img (np.ndarray): The original image. + result (dict): The result of model forward_test, including: + - img_metas (list[dict]): List of meta information dictionary. + - nodes (Tensor): Node prediction with size: \ + number_node * node_classes. + - edges (Tensor): Edge prediction with size: number_edge * 2. + boxes (list): The text boxes corresponding to the nodes. + show (bool): Whether to show the image. Default: False. + win_name (str): The window name. Default: '' + wait_time (float): Value of waitKey param. Default: 0. + out_file (str or None): The filename to write the image. + Default: None. + + Returns: + np.ndarray: The image with key, value and relation drawn on it. + """ + img = mmcv.imread(img) + h, w = img.shape[:2] + color_list = gen_color() + + for i, box in enumerate(boxes): + new_box = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], + [box[0], box[3]]] + Pts = np.array([new_box], np.int32) + cv2.polylines( + img, [Pts.reshape((-1, 1, 2))], + True, + color=color_list[i % len(color_list)], + thickness=1) + + pred_img_h = h + pred_img_w = w + + pred_edge_img = draw_edge_result(img, result) + pred_img_h = max(pred_img_h, pred_edge_img.shape[0]) + pred_img_w += pred_edge_img.shape[1] + + vis_img = np.zeros((pred_img_h, pred_img_w, 3), dtype=np.uint8) + vis_img[:h, :w] = img + vis_img[:, w:] = 255 + + height_t, width_t = pred_edge_img.shape[:2] + vis_img[:height_t, w:(w + width_t)] = pred_edge_img + + if show: + mmcv.imshow(vis_img, win_name, wait_time) + if out_file is not None: + mmcv.imwrite(vis_img, out_file) + res_dic = { + 'boxes': boxes, + 'nodes': result['nodes'].detach().cpu(), + 'edges': result['edges'].detach().cpu(), + 'metas': result['img_metas'][0] + } + mmcv.dump(res_dic, f'{out_file}_res.pkl') + + return vis_img diff --git a/seghist/vis/aspect_ratio_dist.py b/seghist/vis/aspect_ratio_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..a97b1c8bdd425549f9712dc685db4aafda4b6519 --- /dev/null +++ b/seghist/vis/aspect_ratio_dist.py @@ -0,0 +1,114 @@ +import json +import os +from tqdm import tqdm + +import numpy as np +from numpy.typing import * +import matplotlib.pyplot as plt + +from seghist.utils import ImageToolkits + + +def draw_fig(aspect_ratio_15, aspect_ratio_19, aspect_ratio, output='./vis/results/distribution.pdf'): + fig, axs = plt.subplots(3, 1, figsize=(12, 8)) + + axs[2].grid(color='gray', linestyle='--', linewidth=0.5, axis='y') + axs[2].hist(aspect_ratio_15, + np.arange(1, 41, 1), + color=(197/255, 224/255, 180/255), + edgecolor='black', + density=True, + label='density', + zorder=3) + axs[2].set_yticks(np.linspace(0, 0.28, 8)) + axs[2].set_xlim(right = 40) + axs[2].set_ylabel('SCUT-CTW1500', fontsize=16) + axs[2].set_xlabel('Aspect ratio of text instances', fontsize=16) + + + axs[1].grid(color='gray', linestyle='--', linewidth=0.5, axis='y') + axs[1].hist(aspect_ratio_19, + np.arange(1, 41, 1), + color=(76/255,195/255,190/255), + edgecolor='black', + density=True, + label='density', + zorder=3) + axs[1].set_yticks(np.linspace(0, 0.28, 8)) + axs[1].set_xlim(right = 40) + axs[1].set_ylabel('HDRC', fontsize=16) + + axs[0].grid(color='gray', linestyle='--', linewidth=0.5, axis='y') + axs[0].hist(aspect_ratio, + np.arange(1, 41, 1), + color=(248/255,223/255,136/255), + edgecolor='black', + density=True, + label='density', + zorder=3) + axs[0].set_yticks(np.linspace(0, 0.28, 8)) + axs[0].set_xlim(right = 40) + axs[0].set_ylabel('CHDAC', fontsize=16) + + for ax in axs: + ytick_labels = ax.get_yticklabels() + for label in ytick_labels: + label.set_fontsize(14) + xtick_labels = ax.get_xticklabels() + for label in xtick_labels: + label.set_fontsize(14) + + plt.tight_layout() + plt.savefig(output) + + +def main(): + aspect_ratio_15 = [] + for file in tqdm(os.listdir('./data/scenetext/ctw1500/train/text_label_curve')): + with open(os.path.join('./data/scenetext/ctw1500/train/text_label_curve', file)) as f: + polygons = [] + for l in f.readlines(): + l = list(map(float, l.strip().split(',')[4:])) + polygons.append(np.array(l).reshape(-1,2)) + hi = ImageToolkits(polygons, reorder=True) + aspect_ratio_15.extend(hi.aspect_ratio()) + + with open('./data/historical_document/ICDAR2019HDRC_Chinese/train_label.json') as f: + datas = json.load(f) + aspect_ratio_19 = [] + for data in tqdm(datas['data_list']): + hi = ImageToolkits([np.array(d['polygon']).reshape(-1, 2) for d in data['instances']], + (data['height'], data['width']), + data['img_path'], + [d['text'] for d in data['instances']]) + aspect_ratio_19.extend(hi.aspect_ratio()) + with open('./data/historical_document/ICDAR2019HDRC_Chinese/val_label.json') as f: + datas = json.load(f) + for data in tqdm(datas['data_list']): + hi = ImageToolkits([np.array(d['polygon']).reshape(-1, 2) for d in data['instances']], + (data['height'], data['width']), + data['img_path'], + [d['text'] for d in data['instances']]) + aspect_ratio_19.extend(hi.aspect_ratio()) + with open('./data/historical_document/ICDAR2019HDRC_Chinese/test_label.json') as f: + datas = json.load(f) + for data in tqdm(datas['data_list']): + hi = ImageToolkits([np.array(d['polygon']).reshape(-1, 2) for d in data['instances']], + (data['height'], data['width']), + data['img_path'], + [d['text'] for d in data['instances']]) + aspect_ratio_19.extend(hi.aspect_ratio()) + + data_root = './data/historical_document/IACC2022_CHDAC/official_dataset/final/train/' + ann_file = 'ocr_train.json' + with open(os.path.join(data_root, ann_file)) as f: + datas = json.load(f) + aspect_ratio = [] + for data in tqdm(datas['data_list']): + hi = ImageToolkits([np.array(d['polygon']).reshape(-1, 2) for d in data['instances']], + (data['height'], data['width']), + data['img_path'], + [d['text'] for d in data['instances']]) + aspect_ratio.extend(hi.aspect_ratio()) + + draw_fig(aspect_ratio_15, aspect_ratio_19, aspect_ratio) \ No newline at end of file diff --git a/seghist/vis/aspect_ratio_results.py b/seghist/vis/aspect_ratio_results.py new file mode 100644 index 0000000000000000000000000000000000000000..2afa04d6ded684d27c59f597cf926373d5d338d5 --- /dev/null +++ b/seghist/vis/aspect_ratio_results.py @@ -0,0 +1,116 @@ +import json +import os +from tqdm import tqdm + +import numpy as np +from numpy.typing import * +import matplotlib.pyplot as plt + +from mmocr.apis import TextDetInferencer + +from seghist.utils import ImageToolkits, iou + +def draw_fig(): + with open("./seghist/vis/results/db_as.txt") as f: + db = [] + num = [] + for l in f.readlines(): + ratio, num_, db_ = tuple(map(float, l.strip().split(','))) + db.append(db_) + num.append(num_) + + with open("./seghist/vis/results/tks_as.txt") as f: + tks = [] + for l in f.readlines(): + ratio, num_, tks_ = tuple(map(float, l.strip().split(','))) + tks.append(tks_) + + with open("./seghist/vis/results/iedp_as.txt") as f: + iedp = [] + for l in f.readlines(): + ratio, num_, iedp_ = tuple(map(float, l.strip().split(','))) + iedp.append(iedp_) + + line = [db, tks, iedp] + colors = ['purple', 'royalblue', 'orangered'] + labels = ['DB', 'DB+TKS', 'DB+TKS+IEDP'] + linestyle = ['dotted', 'dashed', 'solid'] + markers = ['o', 's', '^'] + marker_sizes = [8, 8, 8] + + plt.figure(figsize=(10, 6)) + ax1 = plt.gca() # Get current axes + ax2 = ax1.twinx() # Create another axis that shares the same x-axis + + # Plotting lines and points + for l, c, label, ls, m, ms in zip(line, colors, labels, linestyle, markers, marker_sizes): + ax1.plot(range(len(l)), l, color=c, label=label, zorder=2, linestyle=ls, marker=m, markersize=ms, linewidth=2.5) # Ensuring plots are on top + + for i, (db_, tks_, iedp_) in enumerate(zip(db, tks, iedp)): + y = max(db_, tks_, iedp_) + color = np.argmax([db_, tks_, iedp_]) + ax1.text(i, y+0.02, str(round(y*100, 2))+"%", fontsize=14, ha='center', va='bottom', color=colors[color]) + + # Setting labels for the left y-axis + ax1.set_ylabel('mean IoU', fontsize=14) + ax1.legend(loc='lower right') + + # Plotting bar chart on the second y-axis and setting it to the bottom + ax2.bar(range(len(num)), num, alpha=0.3, color='grey', zorder=1, width=0.5, + tick_label=['x<1', '1 4: + match_gt_curl.append(match_gt[igt]) + else: + match_gt_straight.append(match_gt[igt]) + + mean_iou[i].extend(match_gt.tolist()) + curl_mean_iou[i].extend(match_gt_curl) + straight_mean_iou[i].extend(match_gt_straight) + + with open(output, mode='w') as f: + for i in range(len(ratio_list[:-1])): + f.write(f"{ratio_list[i]}, {len(mean_iou[i])}, {sum(mean_iou[i])/(len(mean_iou[i])+1e-4)}\n") \ No newline at end of file diff --git a/seghist/vis/detect_results.py b/seghist/vis/detect_results.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0cd87ac0b8be830bb2a6955adf47da1cdeb008 --- /dev/null +++ b/seghist/vis/detect_results.py @@ -0,0 +1,126 @@ +import os +import json +from tqdm import tqdm + +import numpy as np +import matplotlib.pyplot as plt +import cv2 + +from mmocr.utils.polygon_utils import * +from mmocr.apis import TextDetInferencer + +from seghist.utils import iou + +def get_prediction(inferencer): + img_root = './data/historical_document/IACC2022_CHDAC/official_dataset/final/test' + with open("./data/historical_document/IACC2022_CHDAC/official_dataset/final/test/ocr_test.json") as f: + datas = json.load(f) + + with open("./results/pred.txt", mode='w') as f: + for data in tqdm(datas['data_list']): + ret_polys = inferencer(os.path.join(img_root, 'image', data['img_path']))['polygons'] + ret_polys = [np.array(p).reshape(-1, 2) for p in ret_polys] + gt_polys = [] + for instance in data['instances']: + gt_polys.append(np.array(instance['polygon']).reshape(-1,2)) + + match_gt = [False for _ in gt_polys] + match_pred = [False for _ in ret_polys] + + for igt, gt in enumerate(gt_polys): + for ip, p in enumerate(ret_polys): + if not match_pred[ip] and iou(p, gt) > 0.5: + match_pred[ip] = True + match_gt[igt] = True + break + + # compute metric + tp = np.sum(np.where(match_pred, 1, 0)) + fp = np.sum(np.where(match_pred, 0, 1)) + fn = np.sum(np.where(match_gt, 0, 1)) + precision = tp / (tp + fp) + recall = tp / (tp + fn) + f1 = 2 * precision * recall / (precision + recall) + f.write(f'{data["img_path"]}\t{precision}\t{recall}\t{f1}\n') + +def main(use_hard_example=True): + inferencer = TextDetInferencer(ckpt='./work_dirs_chdac/pse_seghist/epoch_150.pth', + config='./config/seghist/seghist_resnet50-dcnv2_fpnc.py', + device='cuda:0') + img_root = './data/historical_document/IACC2022_CHDAC/official_dataset/final/train' + with open("./data/historical_document/IACC2022_CHDAC/official_dataset/final/train/ocr_train.json") as f: + datas = json.load(f) + if use_hard_example: + if not os.path.exists("./results/pred.txt"): + get_prediction(inferencer) + hard_example = [] + with open("./results/pred.txt") as f: + for l in f.readlines(): + l = l.strip().split() + if float(l[-1]) < 0.8: + hard_example.append(l[0]) + while True: + data = np.random.choice(datas['data_list']) + if data['img_path'] in hard_example: + break + else: + data = np.random.choice(datas['data_list']) + img = cv2.imread(os.path.join(img_root,'image', data['img_path'])) + ret_polys = inferencer(os.path.join(img_root,'image', data['img_path']))['polygons'] + ret_polys = [np.array(p).reshape(-1, 2) for p in ret_polys] + print(data['img_path']) + + # missed + mask = np.zeros(img.shape[:2]) + for instance in tqdm(data['instances']): + poly = np.array(instance['polygon']).reshape(-1,2) + for p in ret_polys: + if iou(p, poly) > 0.5: + break + else: + cv2.drawContours(mask, [poly], -1, 1, 5) + + plt.figure(figsize=(20, 20)) + plt.imshow(img) + plt.imshow(mask, alpha=0.4) + plt.axis('off') + plt.savefig(f"./seghist/vis/results/{data['img_path'].split('.')[0]}_miss.jpg") + + # false positive + mask = np.zeros(img.shape[:2]) + for p in ret_polys: + for instance in data['instances']: + poly = np.array(instance['polygon']).reshape(-1,2) + if iou(p, poly) > 0.5: + break + else: + cv2.drawContours(mask, [p.astype(np.int32)], -1, 1, 5) + + plt.figure(figsize=(20, 20)) + plt.imshow(img) + plt.imshow(mask, alpha=0.4) + plt.axis('off') + plt.savefig(f"./seghist/vis/results/{data['img_path'].split('.')[0]}_fp.jpg") + + # full detect + mask = np.zeros(img.shape[:2]) + for i, p in enumerate(ret_polys): + cv2.drawContours(mask, [p.astype(np.int32)], -1, i % 5 + 1, 3) + + plt.figure(figsize=(12, 12)) + plt.imshow(img) + plt.imshow(mask, alpha=0.4, cmap='jet') + plt.axis('off') + plt.savefig(f"./seghist/vis/results/{data['img_path'].split('.')[0]}_detect.jpg") + + # ground truth + mask = np.zeros(img.shape[:2]) + for i, instance in enumerate(data['instances']): + poly = np.array(instance['polygon']).reshape(-1,2) + cv2.drawContours(mask, [poly], -1, i % 5 + 1, 3) + + plt.figure(figsize=(20, 20)) + plt.imshow(img) + plt.imshow(mask, alpha=0.4, cmap='jet') + plt.axis('off') + plt.savefig(f"./seghist/vis/results/{data['img_path'].split('.')[0]}_gt.jpg") diff --git a/seghist/vis/iedp_recovery.py b/seghist/vis/iedp_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..5a421606e38f188880a822932199e3956bcaadab --- /dev/null +++ b/seghist/vis/iedp_recovery.py @@ -0,0 +1,91 @@ +from typing import Tuple, List, Sequence, Union +import json +import os +import warnings +from tqdm import tqdm + +import numpy as np +from numpy.typing import * +import cv2 +from shapely import Polygon +from sklearn.cluster import KMeans +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1 import make_axes_locatable +from matplotlib.colors import LogNorm + +from mmocr.utils.polygon_utils import poly_make_valid +import pickle +from seghist.utils import iou, unstretch_kernel, stretch_kernel, ImageToolkits + +def draw_fig(iou_db, iou_db2, iou_iedp, output='./seghist/vis/results/iedp_recovery.pdf'): + plt.rc('font', size=14) + iou_db = np.array(iou_db) + iou_db2 = np.array(iou_db2) + iou_iedp = np.array(iou_iedp) + + xgrids = np.linspace(0, 40, 60) + ygrids = np.linspace(0.8, 1, 60) + + hist0, xedge0, yedge0 = np.histogram2d(iou_db[:, 0], iou_db[:, 1], bins=(xgrids, ygrids)) + hist1, xedge1, yedge1 = np.histogram2d(iou_db2[:, 0], iou_db2[:, 1], bins=(xgrids, ygrids)) + hist2, xedge2, yedge2 = np.histogram2d(iou_iedp[:, 0], iou_iedp[:, 1], bins=(xgrids, ygrids)) + + norm = LogNorm(vmin=1e-1, vmax=1e4, clip=True) + + X0, Y0 = np.meshgrid(xedge0[:-1], yedge0[:-1], indexing='ij') + X1, Y1 = np.meshgrid(xedge1[:-1], yedge1[:-1], indexing='ij') + X2, Y2 = np.meshgrid(xedge2[:-1], yedge2[:-1], indexing='ij') + levels = np.logspace(-1, 4, 8) + fig, axes = plt.subplots(1, 3, figsize=(13, 4), constrained_layout=True) + axes[0].contourf(X0, Y0, hist0+0.1, cmap='Blues', norm=norm, levels=levels) + axes[1].contourf(X1, Y1, hist1+0.1, cmap='Blues', norm=norm, levels=levels) + im = axes[2].contourf(X2, Y2, hist2+0.1, cmap='Blues', norm=norm, levels=levels) + + #plt.scatter(iou_iedp[:, 0], iou_iedp[:, 1], 3, color='b', alpha=0.3) + divider = make_axes_locatable(axes[2]) + cax = divider.append_axes("right", size="5%", pad=0.1) + fig.colorbar(im, cax=cax, label='density', ticks=[1, 10, 100, 1000]) + + for ax in axes: + ax.set_xlabel('vertical aspect ratio') + ax.set_ylabel('IoU') + ax.set_xticks(np.arange(0, 40, 10)) + ax.set_yticks(np.arange(0.8, 1, 0.05)) + + plt.savefig(output, bbox_inches='tight') + + +def main(): + with open("./data/historical_document/IACC2022_CHDAC/official_dataset/final/test/ocr_test.json") as f: + datas = json.load(f) + iou_db = [] + iou_db2 = [] + iou_iedp = [] + + r = 0 + s = 2 + c = [1.5, 2] + + for data in tqdm(datas['data_list']): + gt_polys = [] + for instance in data['instances']: + gt_polys.append(np.array(instance['polygon']).reshape(-1,2)) + + hi = ImageToolkits(gt_polys) + aspect_ratio = hi.vertical_aspect_ratio() + + for p, a in zip(gt_polys, aspect_ratio): + shrink = stretch_kernel(p, r, s) + if len(shrink) == 0: + continue + expand_db = unstretch_kernel(shrink, r, s, refinement=False, unclip_ratio=c[0]) + expand_db2 = unstretch_kernel(shrink, r, s, refinement=False, unclip_ratio=c[1]) + expand_iedp = unstretch_kernel(shrink, r, s, tolerance=0.01) + db = iou(p, expand_db) + db2 = iou(p, expand_db2) + iedp = iou(p, expand_iedp) + iou_db.append([a, db]) + iou_db2.append([a, db2]) + iou_iedp.append([a, iedp]) + + draw_fig(iou_db, iou_db2, iou_iedp) \ No newline at end of file diff --git a/seghist/vis/results/ar_res.pdf b/seghist/vis/results/ar_res.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e3ec46abc4142a1fe10f4190b6590902bee53fb5 --- /dev/null +++ b/seghist/vis/results/ar_res.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4f8911429426196054ed2fc831f4856086aa5aa6744641ed9d0cd0758e7a595 +size 17507 diff --git a/seghist/vis/results/db_as.txt b/seghist/vis/results/db_as.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d8acec26ffd14b24c6686a98b24fd284458c9be --- /dev/null +++ b/seghist/vis/results/db_as.txt @@ -0,0 +1,6 @@ +-1, 1935, 0.41124356879665314 +1, 17190, 0.6045297904577329 +5, 7957, 0.7128286295596237 +10, 13329, 0.8075286973821175 +15, 6157, 0.7828136671491922 +20, 4541, 0.7380234503966961 \ No newline at end of file diff --git a/seghist/vis/results/distribution.pdf b/seghist/vis/results/distribution.pdf new file mode 100644 index 0000000000000000000000000000000000000000..17dc357368af1a08833533a0d3f2d6c79ad18e3e --- /dev/null +++ b/seghist/vis/results/distribution.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e524d588d390ec16823a9966848542c75bf38403e1fc2ca7ed58311d0f6257d7 +size 20186 diff --git a/seghist/vis/results/iedp_as.txt b/seghist/vis/results/iedp_as.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9ce8e15a148b0f29d69dd3661f6f45db924a22c --- /dev/null +++ b/seghist/vis/results/iedp_as.txt @@ -0,0 +1,6 @@ +-1, 1935, 0.6884761264896987 +1, 17190, 0.7825217976025839 +5, 7957, 0.8606967549201232 +10, 13329, 0.895497121828551 +15, 6157, 0.8945829166070939 +20, 4541, 0.8644074419490465 \ No newline at end of file diff --git a/seghist/vis/results/iedp_recovery.pdf b/seghist/vis/results/iedp_recovery.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f68f7d6023a142a972c09bc1d8af3a2c0316cb4f --- /dev/null +++ b/seghist/vis/results/iedp_recovery.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24117ae5be2eb69a074b24fcc5c8ff96e79f2afc8e17448738d364f324155837 +size 59765 diff --git a/seghist/vis/results/iedp_storage.pkl b/seghist/vis/results/iedp_storage.pkl new file mode 100644 index 0000000000000000000000000000000000000000..10aba0a4e4c9f66f3d26a659901b3fa2e6a9d922 --- /dev/null +++ b/seghist/vis/results/iedp_storage.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c229dfc74e67fb3a68d6b50618fdc440e18b53f2ea52273510ee65eef1d79061 +size 3480368 diff --git a/seghist/vis/results/tks_as.txt b/seghist/vis/results/tks_as.txt new file mode 100644 index 0000000000000000000000000000000000000000..4abe09dc0dba4b8e4f47e12a41f7529ef60032f3 --- /dev/null +++ b/seghist/vis/results/tks_as.txt @@ -0,0 +1,6 @@ +-1, 1935, 0.6246592837217968 +1, 17190, 0.7601141424717563 +5, 7957, 0.8238534608179475 +10, 13329, 0.8372475504573303 +15, 6157, 0.8390749715682869 +20, 4541, 0.8121235801245915 \ No newline at end of file diff --git a/seghist/vis/results/tks_recovery.pdf b/seghist/vis/results/tks_recovery.pdf new file mode 100644 index 0000000000000000000000000000000000000000..fd1defb245efd4c7f62f909835e81879a99f493c --- /dev/null +++ b/seghist/vis/results/tks_recovery.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03824a5ad8def2655a813d923f47e2321067e04aedd450008b382a0edb5fa327 +size 137344 diff --git a/seghist/vis/separate_line_maps.py b/seghist/vis/separate_line_maps.py new file mode 100644 index 0000000000000000000000000000000000000000..8eeca6428ef67dcdc1b216b8a5bbeef5a7da2503 --- /dev/null +++ b/seghist/vis/separate_line_maps.py @@ -0,0 +1,33 @@ +import json +import os + +import numpy as np +from numpy.typing import * +import cv2 + +from seghist.utils import ImageToolkits + +def main(data_root = './data/historical_document/IACC2022_CHDAC/official_dataset/preliminary/train/', + ann_file = 'label_train.json'): + data_root = './data/historical_document/IACC2022_CHDAC/official_dataset/preliminary/train/' + ann_file = 'label_train.json' + with open(os.path.join(data_root, ann_file)) as f: + datas = json.load(f) + for img_path, instances in datas.items(): + if img_path == 'image_701.jpg': + break + image = cv2.imread(os.path.join(data_root, 'image', 'image_701.jpg')) + hi = ImageToolkits([np.array(d['points']).reshape(-1, 2) for d in instances], + image.shape[:2], + 'image_701.jpg', + texts=[d['transcription'] for d in instances]) + hi.process() + kernel_single, kernel_double = hi.generate_kernelmap() + + kernel_single = cv2.applyColorMap(kernel_single[..., np.newaxis], cv2.COLORMAP_VIRIDIS) + overlay = cv2.addWeighted(image, 0.6, kernel_single, 0.4, 0) + cv2.imwrite('./seghist/vis/results/out_single.png', overlay) + + kernel_double = cv2.applyColorMap(kernel_double[..., np.newaxis], cv2.COLORMAP_VIRIDIS) + overlay = cv2.addWeighted(image, 0.6, kernel_double, 0.4, 0) + cv2.imwrite('./seghist/vis/results/out_double.png', overlay) \ No newline at end of file diff --git a/seghist/vis/tks_recovery.py b/seghist/vis/tks_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e6098679dda7bb0956d97fd73a6d6491849038 --- /dev/null +++ b/seghist/vis/tks_recovery.py @@ -0,0 +1,56 @@ +import numpy as np +import matplotlib.pyplot as plt + +from mmocr.utils.polygon_utils import * + +from seghist.utils import stretch_kernel, iou, unstretch_kernel + +def main(): + x = np.arange(0.3, 40, 0.1) + c = np.arange(1, 10, 0.1) + xs1, cs1 = np.meshgrid(x, c) + ious1 = np.zeros_like(xs1) + r = 0.16 + s = 1 + for i, x_ in enumerate(x): + poly = np.array([[0,0],[0,x_],[1,x_],[1,0]]) + shrink = stretch_kernel(poly, r, s) + for j, c_ in enumerate(c): + expand1 = unstretch_kernel(shrink, r, s, refinement=False, unclip_ratio=c_) + ious1[j, i] = iou(poly, expand1) + + x = np.arange(0.3, 40, 0.1) + c = np.arange(1, 10, 0.1) + xs2, cs2 = np.meshgrid(x, c) + ious2 = np.zeros_like(xs2) + r = 0 + s = 2 + for i, x_ in enumerate(x): + poly = np.array([[0,0],[0,x_],[1,x_],[1,0]]) + shrink = stretch_kernel(poly, r, s) + for j, c_ in enumerate(c): + expand2 = unstretch_kernel(shrink, r, s, refinement=False, unclip_ratio=c_) + ious2[j, i] = iou(poly, expand2) + + plt.rc('font', size=14) + fig, axes = plt.subplots(1, 2, figsize=(11, 5)) + cmap='viridis' + vmin=0 + vmax=1 + axes[0].contour(cs1, xs1, ious1, levels=10, cmap=cmap, vmin=vmin, vmax=vmax) + axes[0].contourf(cs1, xs1, ious1, alpha=0.5, levels=10, cmap=cmap, vmin=vmin, vmax=vmax) + axes[1].contour(cs2, xs2, ious2, levels=10, cmap=cmap, vmin=vmin, vmax=vmax) + im = axes[1].contourf(cs2, xs2, ious2, alpha=0.5, levels=10, cmap=cmap, vmin=vmin, vmax=vmax) + + cax = fig.add_axes([0.92, 0.15, 0.02, 0.7]) + fig.colorbar(im, cax=cax, label='IoU') + + axes[0].set_xlabel('unclip ratio') + axes[0].set_ylabel('vertical aspect ratio') + axes[0].set_yticks([1, 5, 10, 15, 20, 25, 30, 35]) + axes[0].set_xticks(np.arange(1,10,1)) + axes[1].set_xlabel('unclip ratio') + axes[1].set_ylabel('vertical aspect ratio') + axes[1].set_yticks([1, 5, 10, 15, 20, 25, 30, 35]) + axes[1].set_xticks(np.arange(1,10,1)) + plt.savefig('./seghist/vis/results/tks.pdf') \ No newline at end of file diff --git a/test.py b/test.py new file mode 100644 index 0000000000000000000000000000000000000000..3699e99a9b23f97021d991bc1bce7878853aea24 --- /dev/null +++ b/test.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.registry import RUNNERS +from mmengine.runner import Runner + +from mmocr.utils import register_all_modules + + +def parse_args(): + parser = argparse.ArgumentParser(description='Test (and eval) a model') + parser.add_argument('config', help='Test config file path') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument( + '--work-dir', + help='The directory to save the file containing evaluation metrics') + parser.add_argument( + '--save-preds', + action='store_true', + help='Dump predictions to a pickle file for offline evaluation') + parser.add_argument( + '--show', action='store_true', help='Show prediction results') + parser.add_argument( + '--show-dir', + help='Directory where painted images will be saved. ' + 'If specified, it will be automatically saved ' + 'to the work_dir/timestamp/show_dir') + parser.add_argument( + '--wait-time', type=float, default=2, help='The interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='Override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='Job launcher') + parser.add_argument('--local_rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + return args + + +def trigger_visualization_hook(cfg, args): + default_hooks = cfg.default_hooks + if 'visualization' in default_hooks: + visualization_hook = default_hooks['visualization'] + # Turn on visualization + visualization_hook['enable'] = True + visualization_hook['draw_gt'] = True + visualization_hook['draw_pred'] = True + if args.show: + visualization_hook['show'] = True + visualization_hook['wait_time'] = args.wait_time + if args.show_dir: + cfg.visualizer['save_dir'] = args.show_dir + cfg.visualizer['vis_backends'] = [dict(type='LocalVisBackend')] + else: + raise RuntimeError( + 'VisualizationHook must be included in default_hooks.' + 'refer to usage ' + '"visualization=dict(type=\'VisualizationHook\')"') + + return cfg + + +def main(): + args = parse_args() + + # register all modules in mmocr into the registries + # do not init the default scope here because it will be init in the runner + register_all_modules(init_default_scope=False) + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + + cfg.load_from = args.checkpoint + + # TODO: It will be supported after refactoring the visualizer + if args.show and args.show_dir: + raise NotImplementedError('--show and --show-dir cannot be set ' + 'at the same time') + + if args.show or args.show_dir: + cfg = trigger_visualization_hook(cfg, args) + + # save predictions + if args.save_preds: + dump_metric = dict( + type='DumpResults', + out_file_path=osp.join( + cfg.work_dir, + f'{osp.basename(args.checkpoint)}_predictions.pkl')) + if isinstance(cfg.test_evaluator, (list, tuple)): + cfg.test_evaluator = list(cfg.test_evaluator) + cfg.test_evaluator.append(dump_metric) + else: + cfg.test_evaluator = [cfg.test_evaluator, dump_metric] + + # build the runner from config + if 'runner_type' not in cfg: + # build the default runner + runner = Runner.from_cfg(cfg) + else: + # build customized runner from the registry + # if 'runner_type' is set in the cfg + runner = RUNNERS.build(cfg) + + # start testing + runner.test() + + +if __name__ == '__main__': + main() diff --git a/train.py b/train.py new file mode 100644 index 0000000000000000000000000000000000000000..622041a0fc66ac622be7ff46a761ba62f37b24af --- /dev/null +++ b/train.py @@ -0,0 +1,117 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import logging +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.logging import print_log +from mmengine.registry import RUNNERS +from mmengine.runner import Runner + +from mmocr.utils import register_all_modules + + +def parse_args(): + parser = argparse.ArgumentParser(description='Train a model') + parser.add_argument('config', help='Train config file path') + parser.add_argument('--work-dir', help='The dir to save logs and models') + parser.add_argument( + '--resume', action='store_true', help='Whether to resume checkpoint.') + parser.add_argument( + '--amp', + action='store_true', + default=False, + help='Enable automatic-mixed-precision training') + parser.add_argument( + '--auto-scale-lr', + action='store_true', + help='Whether to scale the learning rate automatically. It requires ' + '`auto_scale_lr` in config, and `base_batch_size` in `auto_scale_lr`') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='Override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='Job launcher') + parser.add_argument('--local_rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + return args + + +def main(): + args = parse_args() + + # register all modules in mmdet into the registries + # do not init the default scope here because it will be init in the runner + register_all_modules(init_default_scope=False) + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + # enable automatic-mixed-precision training + if args.amp: + optim_wrapper = cfg.optim_wrapper.type + if optim_wrapper == 'AmpOptimWrapper': + print_log( + 'AMP training is already enabled in your config.', + logger='current', + level=logging.WARNING) + else: + assert optim_wrapper == 'OptimWrapper', ( + '`--amp` is only supported when the optimizer wrapper type is ' + f'`OptimWrapper` but got {optim_wrapper}.') + cfg.optim_wrapper.type = 'AmpOptimWrapper' + cfg.optim_wrapper.loss_scale = 'dynamic' + + if args.resume: + cfg.resume = True + + # enable automatically scaling LR + if args.auto_scale_lr: + if 'auto_scale_lr' in cfg and \ + 'base_batch_size' in cfg.auto_scale_lr: + cfg.auto_scale_lr.enable = True + else: + raise RuntimeError('Can not find "auto_scale_lr" or ' + '"auto_scale_lr.base_batch_size" in your' + ' configuration file.') + + # build the runner from config + if 'runner_type' not in cfg: + # build the default runner + runner = Runner.from_cfg(cfg) + else: + # build customized runner from the registry + # if 'runner_type' is set in the cfg + runner = RUNNERS.build(cfg) + + # start training + runner.train() + + +if __name__ == '__main__': + main()