openocr-python 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. openocr/__init__.py +11 -0
  2. openocr/configs/det/dbnet/repvit_db.yml +173 -0
  3. openocr/configs/rec/abinet/resnet45_trans_abinet_lang.yml +94 -0
  4. openocr/configs/rec/abinet/resnet45_trans_abinet_wo_lang.yml +93 -0
  5. openocr/configs/rec/abinet/svtrv2_abinet_lang.yml +130 -0
  6. openocr/configs/rec/abinet/svtrv2_abinet_wo_lang.yml +128 -0
  7. openocr/configs/rec/aster/resnet31_lstm_aster_tps_on.yml +93 -0
  8. openocr/configs/rec/aster/svtrv2_aster.yml +127 -0
  9. openocr/configs/rec/aster/svtrv2_aster_tps_on.yml +102 -0
  10. openocr/configs/rec/autostr/autostr_lstm_aster_tps_on.yml +95 -0
  11. openocr/configs/rec/busnet/svtrv2_busnet.yml +135 -0
  12. openocr/configs/rec/busnet/svtrv2_busnet_pretraining.yml +134 -0
  13. openocr/configs/rec/busnet/vit_busnet.yml +104 -0
  14. openocr/configs/rec/busnet/vit_busnet_pretraining.yml +104 -0
  15. openocr/configs/rec/cam/convnextv2_cam_tps_on.yml +118 -0
  16. openocr/configs/rec/cam/convnextv2_tiny_cam_tps_on.yml +118 -0
  17. openocr/configs/rec/cam/svtrv2_cam_tps_on.yml +123 -0
  18. openocr/configs/rec/cdistnet/resnet45_trans_cdistnet.yml +93 -0
  19. openocr/configs/rec/cdistnet/svtrv2_cdistnet.yml +139 -0
  20. openocr/configs/rec/cppd/svtr_base_cppd.yml +123 -0
  21. openocr/configs/rec/cppd/svtr_base_cppd_ch.yml +126 -0
  22. openocr/configs/rec/cppd/svtr_base_cppd_h8.yml +123 -0
  23. openocr/configs/rec/cppd/svtr_base_cppd_syn.yml +124 -0
  24. openocr/configs/rec/cppd/svtrv2_cppd.yml +150 -0
  25. openocr/configs/rec/dan/resnet45_fpn_dan.yml +98 -0
  26. openocr/configs/rec/dan/svtrv2_dan.yml +130 -0
  27. openocr/configs/rec/focalsvtr/focalsvtr_ctc.yml +137 -0
  28. openocr/configs/rec/gtc/svtrv2_lnconv_nrtr_gtc.yml +168 -0
  29. openocr/configs/rec/gtc/svtrv2_lnconv_smtr_gtc_long_infer.yml +151 -0
  30. openocr/configs/rec/gtc/svtrv2_lnconv_smtr_gtc_smtr_long.yml +150 -0
  31. openocr/configs/rec/gtc/svtrv2_lnconv_smtr_gtc_stream.yml +152 -0
  32. openocr/configs/rec/igtr/svtr_base_ds_igtr.yml +157 -0
  33. openocr/configs/rec/lister/focalsvtr_lister_wo_fem_maxratio12.yml +133 -0
  34. openocr/configs/rec/lister/svtrv2_lister_wo_fem_maxratio12.yml +138 -0
  35. openocr/configs/rec/lpv/svtr_base_lpv.yml +124 -0
  36. openocr/configs/rec/lpv/svtr_base_lpv_wo_glrm.yml +123 -0
  37. openocr/configs/rec/lpv/svtrv2_lpv.yml +147 -0
  38. openocr/configs/rec/lpv/svtrv2_lpv_wo_glrm.yml +146 -0
  39. openocr/configs/rec/maerec/vit_nrtr.yml +116 -0
  40. openocr/configs/rec/matrn/resnet45_trans_matrn.yml +95 -0
  41. openocr/configs/rec/matrn/svtrv2_matrn.yml +130 -0
  42. openocr/configs/rec/mgpstr/svtrv2_mgpstr_only_char.yml +140 -0
  43. openocr/configs/rec/mgpstr/vit_base_mgpstr_only_char.yml +111 -0
  44. openocr/configs/rec/mgpstr/vit_large_mgpstr_only_char.yml +110 -0
  45. openocr/configs/rec/mgpstr/vit_mgpstr.yml +110 -0
  46. openocr/configs/rec/mgpstr/vit_mgpstr_only_char.yml +110 -0
  47. openocr/configs/rec/moran/resnet31_lstm_moran.yml +92 -0
  48. openocr/configs/rec/nrtr/focalsvtr_nrtr_maxraio12.yml +145 -0
  49. openocr/configs/rec/nrtr/nrtr.yml +107 -0
  50. openocr/configs/rec/nrtr/svtr_base_nrtr.yml +118 -0
  51. openocr/configs/rec/nrtr/svtr_base_nrtr_syn.yml +119 -0
  52. openocr/configs/rec/nrtr/svtrv2_nrtr.yml +146 -0
  53. openocr/configs/rec/ote/svtr_base_h8_ote.yml +117 -0
  54. openocr/configs/rec/ote/svtr_base_ote.yml +116 -0
  55. openocr/configs/rec/parseq/focalsvtr_parseq_maxratio12.yml +140 -0
  56. openocr/configs/rec/parseq/svrtv2_parseq.yml +136 -0
  57. openocr/configs/rec/parseq/vit_parseq.yml +100 -0
  58. openocr/configs/rec/robustscanner/resnet31_robustscanner.yml +102 -0
  59. openocr/configs/rec/robustscanner/svtrv2_robustscanner.yml +134 -0
  60. openocr/configs/rec/sar/resnet31_lstm_sar.yml +94 -0
  61. openocr/configs/rec/sar/svtrv2_sar.yml +128 -0
  62. openocr/configs/rec/seed/resnet31_lstm_seed_tps_on.yml +96 -0
  63. openocr/configs/rec/smtr/focalsvtr_smtr.yml +150 -0
  64. openocr/configs/rec/smtr/focalsvtr_smtr_long.yml +133 -0
  65. openocr/configs/rec/smtr/svtrv2_smtr.yml +150 -0
  66. openocr/configs/rec/smtr/svtrv2_smtr_bi.yml +136 -0
  67. openocr/configs/rec/srn/resnet50_fpn_srn.yml +97 -0
  68. openocr/configs/rec/srn/svtrv2_srn.yml +131 -0
  69. openocr/configs/rec/svtrs/convnextv2_ctc.yml +105 -0
  70. openocr/configs/rec/svtrs/convnextv2_h8_ctc.yml +105 -0
  71. openocr/configs/rec/svtrs/convnextv2_h8_rctc.yml +106 -0
  72. openocr/configs/rec/svtrs/convnextv2_rctc.yml +106 -0
  73. openocr/configs/rec/svtrs/convnextv2_tiny_h8_ctc.yml +105 -0
  74. openocr/configs/rec/svtrs/convnextv2_tiny_h8_rctc.yml +106 -0
  75. openocr/configs/rec/svtrs/crnn_ctc.yml +99 -0
  76. openocr/configs/rec/svtrs/crnn_ctc_long.yml +116 -0
  77. openocr/configs/rec/svtrs/focalnet_base_ctc.yml +108 -0
  78. openocr/configs/rec/svtrs/focalnet_base_rctc.yml +109 -0
  79. openocr/configs/rec/svtrs/focalsvtr_ctc.yml +106 -0
  80. openocr/configs/rec/svtrs/focalsvtr_rctc.yml +107 -0
  81. openocr/configs/rec/svtrs/resnet45_trans_ctc.yml +103 -0
  82. openocr/configs/rec/svtrs/resnet45_trans_rctc.yml +104 -0
  83. openocr/configs/rec/svtrs/svtr_base_ctc.yml +110 -0
  84. openocr/configs/rec/svtrs/svtr_base_rctc.yml +111 -0
  85. openocr/configs/rec/svtrs/svtrnet_ctc_syn.yml +111 -0
  86. openocr/configs/rec/svtrs/vit_ctc.yml +103 -0
  87. openocr/configs/rec/svtrs/vit_rctc.yml +103 -0
  88. openocr/configs/rec/svtrv2/repsvtr_ch.yml +121 -0
  89. openocr/configs/rec/svtrv2/svtrv2_ch.yml +133 -0
  90. openocr/configs/rec/svtrv2/svtrv2_ctc.yml +136 -0
  91. openocr/configs/rec/svtrv2/svtrv2_rctc.yml +135 -0
  92. openocr/configs/rec/svtrv2/svtrv2_small_rctc.yml +135 -0
  93. openocr/configs/rec/svtrv2/svtrv2_smtr_gtc_rctc.yml +162 -0
  94. openocr/configs/rec/svtrv2/svtrv2_smtr_gtc_rctc_ch.yml +153 -0
  95. openocr/configs/rec/svtrv2/svtrv2_tiny_rctc.yml +135 -0
  96. openocr/configs/rec/visionlan/resnet45_trans_visionlan_LA.yml +103 -0
  97. openocr/configs/rec/visionlan/resnet45_trans_visionlan_LF_1.yml +102 -0
  98. openocr/configs/rec/visionlan/resnet45_trans_visionlan_LF_2.yml +103 -0
  99. openocr/configs/rec/visionlan/svtrv2_visionlan_LA.yml +112 -0
  100. openocr/configs/rec/visionlan/svtrv2_visionlan_LF_1.yml +111 -0
  101. openocr/configs/rec/visionlan/svtrv2_visionlan_LF_2.yml +112 -0
  102. openocr/demo_gradio.py +128 -0
  103. openocr/opendet/modeling/__init__.py +11 -0
  104. openocr/opendet/modeling/backbones/__init__.py +14 -0
  105. openocr/opendet/modeling/backbones/repvit.py +340 -0
  106. openocr/opendet/modeling/base_detector.py +69 -0
  107. openocr/opendet/modeling/heads/__init__.py +14 -0
  108. openocr/opendet/modeling/heads/db_head.py +73 -0
  109. openocr/opendet/modeling/necks/__init__.py +14 -0
  110. openocr/opendet/modeling/necks/db_fpn.py +609 -0
  111. openocr/opendet/postprocess/__init__.py +18 -0
  112. openocr/opendet/postprocess/db_postprocess.py +273 -0
  113. openocr/opendet/preprocess/__init__.py +154 -0
  114. openocr/opendet/preprocess/crop_resize.py +121 -0
  115. openocr/opendet/preprocess/db_resize_for_test.py +135 -0
  116. openocr/openrec/losses/__init__.py +62 -0
  117. openocr/openrec/losses/abinet_loss.py +42 -0
  118. openocr/openrec/losses/ar_loss.py +23 -0
  119. openocr/openrec/losses/cam_loss.py +48 -0
  120. openocr/openrec/losses/cdistnet_loss.py +34 -0
  121. openocr/openrec/losses/ce_loss.py +68 -0
  122. openocr/openrec/losses/cppd_loss.py +77 -0
  123. openocr/openrec/losses/ctc_loss.py +33 -0
  124. openocr/openrec/losses/igtr_loss.py +12 -0
  125. openocr/openrec/losses/lister_loss.py +14 -0
  126. openocr/openrec/losses/lpv_loss.py +30 -0
  127. openocr/openrec/losses/mgp_loss.py +34 -0
  128. openocr/openrec/losses/parseq_loss.py +12 -0
  129. openocr/openrec/losses/robustscanner_loss.py +20 -0
  130. openocr/openrec/losses/seed_loss.py +46 -0
  131. openocr/openrec/losses/smtr_loss.py +12 -0
  132. openocr/openrec/losses/srn_loss.py +40 -0
  133. openocr/openrec/losses/visionlan_loss.py +58 -0
  134. openocr/openrec/metrics/__init__.py +19 -0
  135. openocr/openrec/metrics/rec_metric.py +270 -0
  136. openocr/openrec/metrics/rec_metric_gtc.py +58 -0
  137. openocr/openrec/metrics/rec_metric_long.py +142 -0
  138. openocr/openrec/metrics/rec_metric_mgp.py +93 -0
  139. openocr/openrec/modeling/__init__.py +11 -0
  140. openocr/openrec/modeling/base_recognizer.py +69 -0
  141. openocr/openrec/modeling/common.py +238 -0
  142. openocr/openrec/modeling/decoders/__init__.py +109 -0
  143. openocr/openrec/modeling/decoders/abinet_decoder.py +283 -0
  144. openocr/openrec/modeling/decoders/aster_decoder.py +170 -0
  145. openocr/openrec/modeling/decoders/bus_decoder.py +133 -0
  146. openocr/openrec/modeling/decoders/cam_decoder.py +43 -0
  147. openocr/openrec/modeling/decoders/cdistnet_decoder.py +334 -0
  148. openocr/openrec/modeling/decoders/cppd_decoder.py +393 -0
  149. openocr/openrec/modeling/decoders/ctc_decoder.py +203 -0
  150. openocr/openrec/modeling/decoders/dan_decoder.py +203 -0
  151. openocr/openrec/modeling/decoders/igtr_decoder.py +815 -0
  152. openocr/openrec/modeling/decoders/lister_decoder.py +535 -0
  153. openocr/openrec/modeling/decoders/lpv_decoder.py +119 -0
  154. openocr/openrec/modeling/decoders/matrn_decoder.py +236 -0
  155. openocr/openrec/modeling/decoders/mgp_decoder.py +99 -0
  156. openocr/openrec/modeling/decoders/nrtr_decoder.py +439 -0
  157. openocr/openrec/modeling/decoders/ote_decoder.py +205 -0
  158. openocr/openrec/modeling/decoders/parseq_decoder.py +504 -0
  159. openocr/openrec/modeling/decoders/rctc_decoder.py +70 -0
  160. openocr/openrec/modeling/decoders/robustscanner_decoder.py +749 -0
  161. openocr/openrec/modeling/decoders/sar_decoder.py +236 -0
  162. openocr/openrec/modeling/decoders/smtr_decoder.py +621 -0
  163. openocr/openrec/modeling/decoders/smtr_decoder_nattn.py +521 -0
  164. openocr/openrec/modeling/decoders/srn_decoder.py +283 -0
  165. openocr/openrec/modeling/decoders/visionlan_decoder.py +321 -0
  166. openocr/openrec/modeling/encoders/__init__.py +39 -0
  167. openocr/openrec/modeling/encoders/autostr_encoder.py +327 -0
  168. openocr/openrec/modeling/encoders/cam_encoder.py +760 -0
  169. openocr/openrec/modeling/encoders/convnextv2.py +213 -0
  170. openocr/openrec/modeling/encoders/focalsvtr.py +631 -0
  171. openocr/openrec/modeling/encoders/nrtr_encoder.py +28 -0
  172. openocr/openrec/modeling/encoders/rec_hgnet.py +346 -0
  173. openocr/openrec/modeling/encoders/rec_lcnetv3.py +488 -0
  174. openocr/openrec/modeling/encoders/rec_mobilenet_v3.py +132 -0
  175. openocr/openrec/modeling/encoders/rec_mv1_enhance.py +254 -0
  176. openocr/openrec/modeling/encoders/rec_nrtr_mtb.py +37 -0
  177. openocr/openrec/modeling/encoders/rec_resnet_31.py +213 -0
  178. openocr/openrec/modeling/encoders/rec_resnet_45.py +183 -0
  179. openocr/openrec/modeling/encoders/rec_resnet_fpn.py +216 -0
  180. openocr/openrec/modeling/encoders/rec_resnet_vd.py +252 -0
  181. openocr/openrec/modeling/encoders/repvit.py +338 -0
  182. openocr/openrec/modeling/encoders/resnet31_rnn.py +123 -0
  183. openocr/openrec/modeling/encoders/svtrnet.py +574 -0
  184. openocr/openrec/modeling/encoders/svtrnet2dpos.py +616 -0
  185. openocr/openrec/modeling/encoders/svtrv2.py +470 -0
  186. openocr/openrec/modeling/encoders/svtrv2_lnconv.py +503 -0
  187. openocr/openrec/modeling/encoders/svtrv2_lnconv_two33.py +517 -0
  188. openocr/openrec/modeling/encoders/vit.py +120 -0
  189. openocr/openrec/modeling/transforms/__init__.py +15 -0
  190. openocr/openrec/modeling/transforms/aster_tps.py +262 -0
  191. openocr/openrec/modeling/transforms/moran.py +136 -0
  192. openocr/openrec/modeling/transforms/tps.py +246 -0
  193. openocr/openrec/optimizer/__init__.py +73 -0
  194. openocr/openrec/optimizer/lr.py +227 -0
  195. openocr/openrec/postprocess/__init__.py +72 -0
  196. openocr/openrec/postprocess/abinet_postprocess.py +37 -0
  197. openocr/openrec/postprocess/ar_postprocess.py +63 -0
  198. openocr/openrec/postprocess/ce_postprocess.py +43 -0
  199. openocr/openrec/postprocess/char_postprocess.py +108 -0
  200. openocr/openrec/postprocess/cppd_postprocess.py +42 -0
  201. openocr/openrec/postprocess/ctc_postprocess.py +119 -0
  202. openocr/openrec/postprocess/igtr_postprocess.py +100 -0
  203. openocr/openrec/postprocess/lister_postprocess.py +59 -0
  204. openocr/openrec/postprocess/mgp_postprocess.py +143 -0
  205. openocr/openrec/postprocess/nrtr_postprocess.py +75 -0
  206. openocr/openrec/postprocess/smtr_postprocess.py +73 -0
  207. openocr/openrec/postprocess/srn_postprocess.py +80 -0
  208. openocr/openrec/postprocess/visionlan_postprocess.py +81 -0
  209. openocr/openrec/preprocess/__init__.py +173 -0
  210. openocr/openrec/preprocess/abinet_aug.py +473 -0
  211. openocr/openrec/preprocess/abinet_label_encode.py +36 -0
  212. openocr/openrec/preprocess/ar_label_encode.py +36 -0
  213. openocr/openrec/preprocess/auto_augment.py +1012 -0
  214. openocr/openrec/preprocess/cam_label_encode.py +141 -0
  215. openocr/openrec/preprocess/ce_label_encode.py +116 -0
  216. openocr/openrec/preprocess/char_label_encode.py +36 -0
  217. openocr/openrec/preprocess/cppd_label_encode.py +173 -0
  218. openocr/openrec/preprocess/ctc_label_encode.py +124 -0
  219. openocr/openrec/preprocess/ep_label_encode.py +38 -0
  220. openocr/openrec/preprocess/igtr_label_encode.py +360 -0
  221. openocr/openrec/preprocess/mgp_label_encode.py +95 -0
  222. openocr/openrec/preprocess/parseq_aug.py +150 -0
  223. openocr/openrec/preprocess/rec_aug.py +211 -0
  224. openocr/openrec/preprocess/resize.py +534 -0
  225. openocr/openrec/preprocess/smtr_label_encode.py +125 -0
  226. openocr/openrec/preprocess/srn_label_encode.py +37 -0
  227. openocr/openrec/preprocess/visionlan_label_encode.py +67 -0
  228. openocr/tools/create_lmdb_dataset.py +118 -0
  229. openocr/tools/data/__init__.py +94 -0
  230. openocr/tools/data/collate_fn.py +100 -0
  231. openocr/tools/data/lmdb_dataset.py +142 -0
  232. openocr/tools/data/lmdb_dataset_test.py +166 -0
  233. openocr/tools/data/multi_scale_sampler.py +177 -0
  234. openocr/tools/data/ratio_dataset.py +217 -0
  235. openocr/tools/data/ratio_dataset_test.py +273 -0
  236. openocr/tools/data/ratio_dataset_tvresize.py +213 -0
  237. openocr/tools/data/ratio_dataset_tvresize_test.py +276 -0
  238. openocr/tools/data/ratio_sampler.py +190 -0
  239. openocr/tools/data/simple_dataset.py +263 -0
  240. openocr/tools/data/strlmdb_dataset.py +143 -0
  241. openocr/tools/engine/__init__.py +5 -0
  242. openocr/tools/engine/config.py +158 -0
  243. openocr/tools/engine/trainer.py +621 -0
  244. openocr/tools/eval_rec.py +41 -0
  245. openocr/tools/eval_rec_all_ch.py +184 -0
  246. openocr/tools/eval_rec_all_en.py +206 -0
  247. openocr/tools/eval_rec_all_long.py +119 -0
  248. openocr/tools/eval_rec_all_long_simple.py +122 -0
  249. openocr/tools/export_rec.py +118 -0
  250. openocr/tools/infer/onnx_engine.py +65 -0
  251. openocr/tools/infer/predict_rec.py +140 -0
  252. openocr/tools/infer/utility.py +234 -0
  253. openocr/tools/infer_det.py +449 -0
  254. openocr/tools/infer_e2e.py +462 -0
  255. openocr/tools/infer_e2e_parallel.py +184 -0
  256. openocr/tools/infer_rec.py +371 -0
  257. openocr/tools/train_rec.py +37 -0
  258. openocr/tools/utility.py +45 -0
  259. openocr/tools/utils/EN_symbol_dict.txt +94 -0
  260. openocr/tools/utils/__init__.py +0 -0
  261. openocr/tools/utils/ckpt.py +87 -0
  262. openocr/tools/utils/dict/ar_dict.txt +117 -0
  263. openocr/tools/utils/dict/arabic_dict.txt +161 -0
  264. openocr/tools/utils/dict/be_dict.txt +145 -0
  265. openocr/tools/utils/dict/bg_dict.txt +140 -0
  266. openocr/tools/utils/dict/chinese_cht_dict.txt +8421 -0
  267. openocr/tools/utils/dict/cyrillic_dict.txt +163 -0
  268. openocr/tools/utils/dict/devanagari_dict.txt +167 -0
  269. openocr/tools/utils/dict/en_dict.txt +63 -0
  270. openocr/tools/utils/dict/fa_dict.txt +136 -0
  271. openocr/tools/utils/dict/french_dict.txt +136 -0
  272. openocr/tools/utils/dict/german_dict.txt +143 -0
  273. openocr/tools/utils/dict/hi_dict.txt +162 -0
  274. openocr/tools/utils/dict/it_dict.txt +118 -0
  275. openocr/tools/utils/dict/japan_dict.txt +4399 -0
  276. openocr/tools/utils/dict/ka_dict.txt +153 -0
  277. openocr/tools/utils/dict/kie_dict/xfund_class_list.txt +4 -0
  278. openocr/tools/utils/dict/korean_dict.txt +3688 -0
  279. openocr/tools/utils/dict/latex_symbol_dict.txt +111 -0
  280. openocr/tools/utils/dict/latin_dict.txt +185 -0
  281. openocr/tools/utils/dict/layout_dict/layout_cdla_dict.txt +10 -0
  282. openocr/tools/utils/dict/layout_dict/layout_publaynet_dict.txt +5 -0
  283. openocr/tools/utils/dict/layout_dict/layout_table_dict.txt +1 -0
  284. openocr/tools/utils/dict/mr_dict.txt +153 -0
  285. openocr/tools/utils/dict/ne_dict.txt +153 -0
  286. openocr/tools/utils/dict/oc_dict.txt +96 -0
  287. openocr/tools/utils/dict/pu_dict.txt +130 -0
  288. openocr/tools/utils/dict/rs_dict.txt +91 -0
  289. openocr/tools/utils/dict/rsc_dict.txt +134 -0
  290. openocr/tools/utils/dict/ru_dict.txt +125 -0
  291. openocr/tools/utils/dict/spin_dict.txt +68 -0
  292. openocr/tools/utils/dict/ta_dict.txt +128 -0
  293. openocr/tools/utils/dict/table_dict.txt +277 -0
  294. openocr/tools/utils/dict/table_master_structure_dict.txt +39 -0
  295. openocr/tools/utils/dict/table_structure_dict.txt +28 -0
  296. openocr/tools/utils/dict/table_structure_dict_ch.txt +48 -0
  297. openocr/tools/utils/dict/te_dict.txt +151 -0
  298. openocr/tools/utils/dict/ug_dict.txt +114 -0
  299. openocr/tools/utils/dict/uk_dict.txt +142 -0
  300. openocr/tools/utils/dict/ur_dict.txt +137 -0
  301. openocr/tools/utils/dict/xi_dict.txt +110 -0
  302. openocr/tools/utils/dict90.txt +90 -0
  303. openocr/tools/utils/e2e_metric/Deteval.py +802 -0
  304. openocr/tools/utils/e2e_metric/polygon_fast.py +70 -0
  305. openocr/tools/utils/e2e_utils/extract_batchsize.py +86 -0
  306. openocr/tools/utils/e2e_utils/extract_textpoint_fast.py +479 -0
  307. openocr/tools/utils/e2e_utils/extract_textpoint_slow.py +582 -0
  308. openocr/tools/utils/e2e_utils/pgnet_pp_utils.py +159 -0
  309. openocr/tools/utils/e2e_utils/visual.py +152 -0
  310. openocr/tools/utils/en_dict.txt +95 -0
  311. openocr/tools/utils/gen_label.py +68 -0
  312. openocr/tools/utils/ic15_dict.txt +36 -0
  313. openocr/tools/utils/logging.py +56 -0
  314. openocr/tools/utils/poly_nms.py +132 -0
  315. openocr/tools/utils/ppocr_keys_v1.txt +6623 -0
  316. openocr/tools/utils/stats.py +58 -0
  317. openocr/tools/utils/utility.py +165 -0
  318. openocr/tools/utils/visual.py +117 -0
  319. openocr_python-0.0.2.dist-info/LICENCE +201 -0
  320. openocr_python-0.0.2.dist-info/METADATA +98 -0
  321. openocr_python-0.0.2.dist-info/RECORD +323 -0
  322. openocr_python-0.0.2.dist-info/WHEEL +5 -0
  323. openocr_python-0.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,262 @@
1
+ import itertools
2
+ import math
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+
10
+ def conv3x3_block(in_planes, out_planes, stride=1):
11
+ """3x3 convolution with padding."""
12
+ conv_layer = nn.Conv2d(in_planes,
13
+ out_planes,
14
+ kernel_size=3,
15
+ stride=1,
16
+ padding=1)
17
+
18
+ block = nn.Sequential(
19
+ conv_layer,
20
+ nn.BatchNorm2d(out_planes),
21
+ nn.ReLU(inplace=True),
22
+ )
23
+ return block
24
+
25
+
26
+ class STNHead(nn.Module):
27
+
28
+ def __init__(self, in_planes, num_ctrlpoints, activation='none'):
29
+ super(STNHead, self).__init__()
30
+
31
+ self.in_planes = in_planes
32
+ self.num_ctrlpoints = num_ctrlpoints
33
+ self.activation = activation
34
+ self.stn_convnet = nn.Sequential(
35
+ conv3x3_block(in_planes, 32), # 32*64
36
+ nn.MaxPool2d(kernel_size=2, stride=2),
37
+ conv3x3_block(32, 64), # 16*32
38
+ nn.MaxPool2d(kernel_size=2, stride=2),
39
+ conv3x3_block(64, 128), # 8*16
40
+ nn.MaxPool2d(kernel_size=2, stride=2),
41
+ conv3x3_block(128, 256), # 4*8
42
+ nn.MaxPool2d(kernel_size=2, stride=2),
43
+ conv3x3_block(256, 256), # 2*4,
44
+ nn.MaxPool2d(kernel_size=2, stride=2),
45
+ conv3x3_block(256, 256)) # 1*2
46
+
47
+ self.stn_fc1 = nn.Sequential(nn.Linear(2 * 256, 512),
48
+ nn.BatchNorm1d(512),
49
+ nn.ReLU(inplace=True))
50
+ self.stn_fc2 = nn.Linear(512, num_ctrlpoints * 2)
51
+
52
+ self.init_weights(self.stn_convnet)
53
+ self.init_weights(self.stn_fc1)
54
+ self.init_stn(self.stn_fc2)
55
+
56
+ def init_weights(self, module):
57
+ for m in module.modules():
58
+ if isinstance(m, nn.Conv2d):
59
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
60
+ m.weight.data.normal_(0, math.sqrt(2. / n))
61
+ if m.bias is not None:
62
+ m.bias.data.zero_()
63
+ elif isinstance(m, nn.BatchNorm2d):
64
+ m.weight.data.fill_(1)
65
+ m.bias.data.zero_()
66
+ elif isinstance(m, nn.Linear):
67
+ m.weight.data.normal_(0, 0.001)
68
+ m.bias.data.zero_()
69
+
70
+ def init_stn(self, stn_fc2):
71
+ margin = 0.01
72
+ sampling_num_per_side = int(self.num_ctrlpoints / 2)
73
+ ctrl_pts_x = np.linspace(margin, 1. - margin, sampling_num_per_side)
74
+ ctrl_pts_y_top = np.ones(sampling_num_per_side) * margin
75
+ ctrl_pts_y_bottom = np.ones(sampling_num_per_side) * (1 - margin)
76
+ ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
77
+ ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
78
+ ctrl_points = np.concatenate([ctrl_pts_top, ctrl_pts_bottom],
79
+ axis=0).astype(np.float32)
80
+ if self.activation == 'none':
81
+ pass
82
+ elif self.activation == 'sigmoid':
83
+ ctrl_points = -np.log(1. / ctrl_points - 1.)
84
+ stn_fc2.weight.data.zero_()
85
+ stn_fc2.bias.data = torch.Tensor(ctrl_points).view(-1)
86
+
87
+ def forward(self, x):
88
+ x = self.stn_convnet(x)
89
+ batch_size, _, h, w = x.size()
90
+ x = x.view(batch_size, -1)
91
+ img_feat = self.stn_fc1(x)
92
+ x = self.stn_fc2(0.1 * img_feat)
93
+ if self.activation == 'sigmoid':
94
+ x = F.sigmoid(x)
95
+ x = x.view(-1, self.num_ctrlpoints, 2)
96
+ return x
97
+
98
+
99
+ def grid_sample(input, grid, canvas=None):
100
+ output = F.grid_sample(input, grid)
101
+ if canvas is None:
102
+ return output
103
+ else:
104
+ input_mask = input.data.new(input.size()).fill_(1)
105
+ output_mask = F.grid_sample(input_mask, grid)
106
+ padded_output = output * output_mask + canvas * (1 - output_mask)
107
+ return padded_output
108
+
109
+
110
+ # phi(x1, x2) = r^2 * log(r), where r = ||x1 - x2||_2
111
+ def compute_partial_repr(input_points, control_points):
112
+ N = input_points.size(0)
113
+ M = control_points.size(0)
114
+ pairwise_diff = input_points.view(N, 1, 2) - control_points.view(1, M, 2)
115
+ # original implementation, very slow
116
+ # pairwise_dist = torch.sum(pairwise_diff ** 2, dim = 2) # square of distance
117
+ pairwise_diff_square = pairwise_diff * pairwise_diff
118
+ pairwise_dist = pairwise_diff_square[:, :, 0] + pairwise_diff_square[:, :,
119
+ 1]
120
+ repr_matrix = 0.5 * pairwise_dist * torch.log(pairwise_dist)
121
+ # fix numerical error for 0 * log(0), substitute all nan with 0
122
+ mask = repr_matrix != repr_matrix
123
+ repr_matrix.masked_fill_(mask, 0)
124
+ return repr_matrix
125
+
126
+
127
+ # output_ctrl_pts are specified, according to our task.
128
+ def build_output_control_points(num_control_points, margins):
129
+ margin_x, margin_y = margins
130
+ num_ctrl_pts_per_side = num_control_points // 2
131
+ ctrl_pts_x = np.linspace(margin_x, 1.0 - margin_x, num_ctrl_pts_per_side)
132
+ ctrl_pts_y_top = np.ones(num_ctrl_pts_per_side) * margin_y
133
+ ctrl_pts_y_bottom = np.ones(num_ctrl_pts_per_side) * (1.0 - margin_y)
134
+ ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
135
+ ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
136
+ # ctrl_pts_top = ctrl_pts_top[1:-1,:]
137
+ # ctrl_pts_bottom = ctrl_pts_bottom[1:-1,:]
138
+ output_ctrl_pts_arr = np.concatenate([ctrl_pts_top, ctrl_pts_bottom],
139
+ axis=0)
140
+ output_ctrl_pts = torch.Tensor(output_ctrl_pts_arr)
141
+ return output_ctrl_pts
142
+
143
+
144
+ class TPSSpatialTransformer(nn.Module):
145
+
146
+ def __init__(
147
+ self,
148
+ output_image_size,
149
+ num_control_points,
150
+ margins,
151
+ ):
152
+ super(TPSSpatialTransformer, self).__init__()
153
+ self.output_image_size = output_image_size
154
+ self.num_control_points = num_control_points
155
+ self.margins = margins
156
+
157
+ self.target_height, self.target_width = output_image_size
158
+ target_control_points = build_output_control_points(
159
+ num_control_points, margins)
160
+ N = num_control_points
161
+ # N = N - 4
162
+
163
+ # create padded kernel matrix
164
+ forward_kernel = torch.zeros(N + 3, N + 3)
165
+ target_control_partial_repr = compute_partial_repr(
166
+ target_control_points, target_control_points)
167
+ forward_kernel[:N, :N].copy_(target_control_partial_repr)
168
+ forward_kernel[:N, -3].fill_(1)
169
+ forward_kernel[-3, :N].fill_(1)
170
+ forward_kernel[:N, -2:].copy_(target_control_points)
171
+ forward_kernel[-2:, :N].copy_(target_control_points.transpose(0, 1))
172
+ # compute inverse matrix
173
+ inverse_kernel = torch.inverse(forward_kernel)
174
+
175
+ # create target cordinate matrix
176
+ HW = self.target_height * self.target_width
177
+ target_coordinate = list(
178
+ itertools.product(range(self.target_height),
179
+ range(self.target_width)))
180
+ target_coordinate = torch.Tensor(target_coordinate) # HW x 2
181
+ Y, X = target_coordinate.split(1, dim=1)
182
+ Y = Y / (self.target_height - 1)
183
+ X = X / (self.target_width - 1)
184
+ target_coordinate = torch.cat([X, Y],
185
+ dim=1) # convert from (y, x) to (x, y)
186
+ target_coordinate_partial_repr = compute_partial_repr(
187
+ target_coordinate, target_control_points)
188
+ target_coordinate_repr = torch.cat([
189
+ target_coordinate_partial_repr,
190
+ torch.ones(HW, 1), target_coordinate
191
+ ],
192
+ dim=1)
193
+
194
+ # register precomputed matrices
195
+ self.register_buffer('inverse_kernel', inverse_kernel)
196
+ self.register_buffer('padding_matrix', torch.zeros(3, 2))
197
+ self.register_buffer('target_coordinate_repr', target_coordinate_repr)
198
+ self.register_buffer('target_control_points', target_control_points)
199
+
200
+ def forward(self, input, source_control_points):
201
+ assert source_control_points.ndimension() == 3
202
+ assert source_control_points.size(1) == self.num_control_points
203
+ assert source_control_points.size(2) == 2
204
+ batch_size = source_control_points.size(0)
205
+
206
+ Y = torch.cat([
207
+ source_control_points,
208
+ self.padding_matrix.expand(batch_size, 3, 2)
209
+ ], 1)
210
+ mapping_matrix = torch.matmul(self.inverse_kernel, Y)
211
+ source_coordinate = torch.matmul(self.target_coordinate_repr,
212
+ mapping_matrix)
213
+
214
+ grid = source_coordinate.view(-1, self.target_height,
215
+ self.target_width, 2)
216
+ grid = torch.clamp(
217
+ grid, 0, 1) # the source_control_points may be out of [0, 1].
218
+ # the input to grid_sample is normalized [-1, 1], but what we get is [0, 1]
219
+ grid = 2.0 * grid - 1.0
220
+ output_maps = grid_sample(input, grid, canvas=None)
221
+ return output_maps
222
+
223
+
224
+ class Aster_TPS(nn.Module):
225
+
226
+ def __init__(
227
+ self,
228
+ in_channels,
229
+ tps_inputsize=[32, 64],
230
+ tps_outputsize=[32, 100],
231
+ num_control_points=20,
232
+ tps_margins=[0.05, 0.05],
233
+ ) -> None:
234
+ super().__init__()
235
+ self.in_channels = in_channels
236
+ #TODO
237
+ self.out_channels = in_channels
238
+ self.tps_inputsize = tps_inputsize
239
+ self.num_control_points = num_control_points
240
+
241
+ self.stn_head = STNHead(
242
+ in_planes=3,
243
+ num_ctrlpoints=num_control_points,
244
+ )
245
+
246
+ self.tps = TPSSpatialTransformer(
247
+ output_image_size=tps_outputsize,
248
+ num_control_points=num_control_points,
249
+ margins=tps_margins,
250
+ )
251
+
252
+ def forward(self, img):
253
+ stn_input = F.interpolate(img,
254
+ self.tps_inputsize,
255
+ mode='bilinear',
256
+ align_corners=True)
257
+
258
+ ctrl_points = self.stn_head(stn_input)
259
+
260
+ img = self.tps(img, ctrl_points)
261
+
262
+ return img
@@ -0,0 +1,136 @@
1
+ """This code is refer from:
2
+ https://github.com/Canjie-Luo/MORAN_v2
3
+ """
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.nn import functional as F
9
+
10
+
11
+ class MORN(nn.Module):
12
+
13
+ def __init__(self, in_channels, target_shape=[32, 100], enhance=1):
14
+ super(MORN, self).__init__()
15
+ self.targetH = target_shape[0]
16
+ self.targetW = target_shape[1]
17
+ self.enhance = enhance
18
+ self.out_channels = in_channels
19
+ self.cnn = nn.Sequential(nn.MaxPool2d(2, 2),
20
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
21
+ nn.BatchNorm2d(64), nn.ReLU(True),
22
+ nn.MaxPool2d(2,
23
+ 2), nn.Conv2d(64, 128, 3, 1, 1),
24
+ nn.BatchNorm2d(128), nn.ReLU(True),
25
+ nn.MaxPool2d(2,
26
+ 2), nn.Conv2d(128, 64, 3, 1, 1),
27
+ nn.BatchNorm2d(64), nn.ReLU(True),
28
+ nn.Conv2d(64, 16, 3, 1, 1),
29
+ nn.BatchNorm2d(16), nn.ReLU(True),
30
+ nn.Conv2d(16, 1, 3, 1, 1), nn.BatchNorm2d(1))
31
+ self.pool = nn.MaxPool2d(2, 1)
32
+ h_list = np.arange(self.targetH) * 2. / (self.targetH - 1) - 1
33
+ w_list = np.arange(self.targetW) * 2. / (self.targetW - 1) - 1
34
+ grid = np.meshgrid(w_list, h_list, indexing='ij')
35
+ grid = np.stack(grid, axis=-1)
36
+ grid = np.transpose(grid, (1, 0, 2))
37
+ grid = np.expand_dims(grid, 0)
38
+ self.grid = nn.Parameter(
39
+ torch.from_numpy(grid).float(),
40
+ requires_grad=False,
41
+ )
42
+
43
+ def forward(self, x):
44
+
45
+ bs = x.shape[0]
46
+ grid = self.grid.tile([bs, 1, 1, 1])
47
+ grid_x = self.grid[:, :, :, 0].unsqueeze(3).tile([bs, 1, 1, 1])
48
+ grid_y = self.grid[:, :, :, 1].unsqueeze(3).tile([bs, 1, 1, 1])
49
+ x_small = F.upsample(x,
50
+ size=(self.targetH, self.targetW),
51
+ mode='bilinear')
52
+
53
+ offsets = self.cnn(x_small)
54
+ offsets_posi = F.relu(offsets, inplace=False)
55
+ offsets_nega = F.relu(-offsets, inplace=False)
56
+ offsets_pool = self.pool(offsets_posi) - self.pool(offsets_nega)
57
+
58
+ offsets_grid = F.grid_sample(offsets_pool, grid)
59
+ offsets_grid = offsets_grid.permute(0, 2, 3, 1).contiguous()
60
+ offsets_x = torch.cat([grid_x, grid_y + offsets_grid], 3)
61
+ x_rectified = F.grid_sample(x, offsets_x)
62
+
63
+ for iteration in range(self.enhance):
64
+ offsets = self.cnn(x_rectified)
65
+
66
+ offsets_posi = F.relu(offsets, inplace=False)
67
+ offsets_nega = F.relu(-offsets, inplace=False)
68
+ offsets_pool = self.pool(offsets_posi) - self.pool(offsets_nega)
69
+
70
+ offsets_grid += F.grid_sample(offsets_pool,
71
+ grid).permute(0, 2, 3,
72
+ 1).contiguous()
73
+ offsets_x = torch.cat([grid_x, grid_y + offsets_grid], 3)
74
+ x_rectified = F.grid_sample(x, offsets_x)
75
+
76
+ # if debug:
77
+
78
+ # offsets_mean = torch.mean(offsets_grid.view(x.size(0), -1), 1)
79
+ # offsets_max, _ = torch.max(offsets_grid.view(x.size(0), -1), 1)
80
+ # offsets_min, _ = torch.min(offsets_grid.view(x.size(0), -1), 1)
81
+
82
+ # import matplotlib.pyplot as plt
83
+ # from colour import Color
84
+ # from torchvision import transforms
85
+ # import cv2
86
+
87
+ # alpha = 0.7
88
+ # density_range = 256
89
+ # color_map = np.empty([self.targetH, self.targetW, 3], dtype=int)
90
+ # cmap = plt.get_cmap("rainbow")
91
+ # blue = Color("blue")
92
+ # hex_colors = list(blue.range_to(Color("red"), density_range))
93
+ # rgb_colors = [[rgb * 255 for rgb in color.rgb] for color in hex_colors][::-1]
94
+ # to_pil_image = transforms.ToPILImage()
95
+
96
+ # for i in range(x.size(0)):
97
+
98
+ # img_small = x_small[i].data.cpu().mul_(0.5).add_(0.5)
99
+ # img = to_pil_image(img_small)
100
+ # img = np.array(img)
101
+ # if len(img.shape) == 2:
102
+ # img = cv2.merge([img.copy()]*3)
103
+ # img_copy = img.copy()
104
+
105
+ # v_max = offsets_max.data[i]
106
+ # v_min = offsets_min.data[i]
107
+ # if self.cuda:
108
+ # img_offsets = (offsets_grid[i]).view(1, self.targetH, self.targetW).data.cuda().add_(-v_min).mul_(1./(v_max-v_min))
109
+ # else:
110
+ # img_offsets = (offsets_grid[i]).view(1, self.targetH, self.targetW).data.cpu().add_(-v_min).mul_(1./(v_max-v_min))
111
+ # img_offsets = to_pil_image(img_offsets)
112
+ # img_offsets = np.array(img_offsets)
113
+ # color_map = np.empty([self.targetH, self.targetW, 3], dtype=int)
114
+ # for h_i in range(self.targetH):
115
+ # for w_i in range(self.targetW):
116
+ # color_map[h_i][w_i] = rgb_colors[int(img_offsets[h_i, w_i]/256.*density_range)]
117
+ # color_map = color_map.astype(np.uint8)
118
+ # cv2.addWeighted(color_map, alpha, img_copy, 1-alpha, 0, img_copy)
119
+
120
+ # img_processed = x_rectified[i].data.cpu().mul_(0.5).add_(0.5)
121
+ # img_processed = to_pil_image(img_processed)
122
+ # img_processed = np.array(img_processed)
123
+ # if len(img_processed.shape) == 2:
124
+ # img_processed = cv2.merge([img_processed.copy()]*3)
125
+
126
+ # total_img = np.ones([self.targetH, self.targetW*3+10, 3], dtype=int)*255
127
+ # total_img[0:self.targetH, 0:self.targetW] = img
128
+ # total_img[0:self.targetH, self.targetW+5:2*self.targetW+5] = img_copy
129
+ # total_img[0:self.targetH, self.targetW*2+10:3*self.targetW+10] = img_processed
130
+ # total_img = cv2.resize(total_img.astype(np.uint8), (300, 50))
131
+ # # cv2.imshow("Input_Offsets_Output", total_img)
132
+ # # cv2.waitKey()
133
+
134
+ # return x_rectified, total_img
135
+
136
+ return x_rectified
@@ -0,0 +1,246 @@
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from openrec.modeling.common import Activation
7
+
8
+
9
+ class ConvBNLayer(nn.Module):
10
+
11
+ def __init__(self,
12
+ in_channels,
13
+ out_channels,
14
+ kernel_size,
15
+ stride=1,
16
+ groups=1,
17
+ act=None):
18
+ super(ConvBNLayer, self).__init__()
19
+ self.conv = nn.Conv2d(
20
+ in_channels=in_channels,
21
+ out_channels=out_channels,
22
+ kernel_size=kernel_size,
23
+ stride=stride,
24
+ padding=(kernel_size - 1) // 2,
25
+ groups=groups,
26
+ bias=False,
27
+ )
28
+ self.bn = nn.BatchNorm2d(out_channels)
29
+ self.act = Activation(act) if act else None
30
+
31
+ def forward(self, x):
32
+ x = self.conv(x)
33
+ x = self.bn(x)
34
+ if self.act is not None:
35
+ x = self.act(x)
36
+ return x
37
+
38
+
39
+ class LocalizationNetwork(nn.Module):
40
+
41
+ def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
42
+ super(LocalizationNetwork, self).__init__()
43
+ self.F = num_fiducial
44
+ F = num_fiducial
45
+ if model_name == 'large':
46
+ num_filters_list = [64, 128, 256, 512]
47
+ fc_dim = 256
48
+ else:
49
+ num_filters_list = [16, 32, 64, 128]
50
+ fc_dim = 64
51
+
52
+ self.block_list = nn.ModuleList()
53
+ for fno in range(0, len(num_filters_list)):
54
+ num_filters = num_filters_list[fno]
55
+ conv = ConvBNLayer(
56
+ in_channels=in_channels,
57
+ out_channels=num_filters,
58
+ kernel_size=3,
59
+ act='relu',
60
+ )
61
+ self.block_list.append(conv)
62
+ if fno == len(num_filters_list) - 1:
63
+ pool = nn.AdaptiveAvgPool2d(1)
64
+ else:
65
+ pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
66
+ in_channels = num_filters
67
+ self.block_list.append(pool)
68
+ self.fc1 = nn.Linear(in_channels, fc_dim)
69
+
70
+ # Init fc2 in LocalizationNetwork
71
+ self.fc2 = nn.Linear(fc_dim, F * 2)
72
+
73
+ initial_bias = self.get_initial_fiducials()
74
+ initial_bias = initial_bias.reshape(-1)
75
+ self.fc2.bias.data = torch.tensor(initial_bias, dtype=torch.float32)
76
+ nn.init.zeros_(self.fc2.weight.data)
77
+ self.out_channels = F * 2
78
+
79
+ def forward(self, x):
80
+ """
81
+ Estimating parameters of geometric transformation
82
+ Args:
83
+ image: input
84
+ Return:
85
+ batch_C_prime: the matrix of the geometric transformation
86
+ """
87
+ for block in self.block_list:
88
+ x = block(x)
89
+ x = x.squeeze(dim=2).squeeze(dim=2)
90
+ x = self.fc1(x)
91
+
92
+ x = F.relu(x)
93
+ x = self.fc2(x)
94
+ x = x.reshape(shape=[-1, self.F, 2])
95
+ return x
96
+
97
+ def get_initial_fiducials(self):
98
+ """see RARE paper Fig.
99
+
100
+ 6 (a)
101
+ """
102
+ F = self.F
103
+ ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
104
+ ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))
105
+ ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))
106
+ ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
107
+ ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
108
+ initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
109
+ return initial_bias
110
+
111
+
112
+ class GridGenerator(nn.Module):
113
+
114
+ def __init__(self, in_channels, num_fiducial):
115
+ super(GridGenerator, self).__init__()
116
+ self.eps = 1e-6
117
+ self.F = num_fiducial
118
+
119
+ self.fc = nn.Linear(in_channels, 6)
120
+ nn.init.constant_(self.fc.weight, 0)
121
+ nn.init.constant_(self.fc.bias, 0)
122
+ self.fc.weight.requires_grad = False
123
+ self.fc.bias.requires_grad = False
124
+
125
+ def forward(self, batch_C_prime, I_r_size):
126
+ """Generate the grid for the grid_sampler.
127
+
128
+ Args:
129
+ batch_C_prime: the matrix of the geometric transformation
130
+ I_r_size: the shape of the input image
131
+ Return:
132
+ batch_P_prime: the grid for the grid_sampler
133
+ """
134
+ C = self.build_C_paddle()
135
+ P = self.build_P_paddle(I_r_size)
136
+
137
+ inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).float()
138
+ P_hat_tensor = self.build_P_hat_paddle(C, torch.tensor(P)).float()
139
+
140
+ batch_C_ex_part_tensor = self.get_expand_tensor(batch_C_prime)
141
+
142
+ batch_C_prime_with_zeros = torch.cat(
143
+ [batch_C_prime, batch_C_ex_part_tensor], dim=1)
144
+ batch_T = torch.matmul(
145
+ inv_delta_C_tensor.to(batch_C_prime_with_zeros.device),
146
+ batch_C_prime_with_zeros,
147
+ )
148
+ batch_P_prime = torch.matmul(P_hat_tensor.to(batch_T.device), batch_T)
149
+ return batch_P_prime
150
+
151
+ def build_C_paddle(self):
152
+ """Return coordinates of fiducial points in I_r; C."""
153
+ F = self.F
154
+ ctrl_pts_x = torch.linspace(-1.0, 1.0, int(F / 2), dtype=torch.float64)
155
+ ctrl_pts_y_top = -1 * torch.ones([int(F / 2)], dtype=torch.float64)
156
+ ctrl_pts_y_bottom = torch.ones([int(F / 2)], dtype=torch.float64)
157
+ ctrl_pts_top = torch.stack([ctrl_pts_x, ctrl_pts_y_top], dim=1)
158
+ ctrl_pts_bottom = torch.stack([ctrl_pts_x, ctrl_pts_y_bottom], dim=1)
159
+ C = torch.cat([ctrl_pts_top, ctrl_pts_bottom], dim=0)
160
+ return C # F x 2
161
+
162
+ def build_P_paddle(self, I_r_size):
163
+ I_r_height, I_r_width = I_r_size
164
+ I_r_grid_x = (torch.arange(-I_r_width, I_r_width, 2) +
165
+ 1.0) / torch.tensor(np.array([I_r_width]))
166
+
167
+ I_r_grid_y = (torch.arange(-I_r_height, I_r_height, 2) +
168
+ 1.0) / torch.tensor(np.array([I_r_height]))
169
+
170
+ # P: self.I_r_width x self.I_r_height x 2
171
+ P = torch.stack(torch.meshgrid(I_r_grid_x, I_r_grid_y), dim=2)
172
+ P = torch.permute(P, [1, 0, 2])
173
+ # n (= self.I_r_width x self.I_r_height) x 2
174
+ return P.reshape([-1, 2])
175
+
176
+ def build_inv_delta_C_paddle(self, C):
177
+ """Return inv_delta_C which is needed to calculate T."""
178
+ F = self.F
179
+ hat_eye = torch.eye(F) # F x F
180
+ hat_C = torch.norm(C.reshape([1, F, 2]) - C.reshape([F, 1, 2]),
181
+ dim=2) + hat_eye
182
+ hat_C = (hat_C**2) * torch.log(hat_C)
183
+ delta_C = torch.cat( # F+3 x F+3
184
+ [
185
+ torch.cat([torch.ones((F, 1)), C, hat_C], dim=1), # F x F+3
186
+ torch.concat([torch.zeros(
187
+ (2, 3)), C.transpose(0, 1)], dim=1), # 2 x F+3
188
+ torch.concat([torch.zeros(
189
+ (1, 3)), torch.ones((1, F))], dim=1), # 1 x F+3
190
+ ],
191
+ axis=0,
192
+ )
193
+ inv_delta_C = torch.inverse(delta_C)
194
+ return inv_delta_C # F+3 x F+3
195
+
196
+ def build_P_hat_paddle(self, C, P):
197
+ F = self.F
198
+ eps = self.eps
199
+ n = P.shape[0] # n (= self.I_r_width x self.I_r_height)
200
+ # P_tile: n x 2 -> n x 1 x 2 -> n x F x 2
201
+ P_tile = torch.tile(torch.unsqueeze(P, dim=1), (1, F, 1))
202
+ C_tile = torch.unsqueeze(C, dim=0) # 1 x F x 2
203
+ P_diff = P_tile - C_tile # n x F x 2
204
+ # rbf_norm: n x F
205
+ rbf_norm = torch.norm(P_diff, p=2, dim=2, keepdim=False)
206
+
207
+ # rbf: n x F
208
+ rbf = torch.multiply(torch.square(rbf_norm), torch.log(rbf_norm + eps))
209
+ P_hat = torch.cat([torch.ones((n, 1)), P, rbf], dim=1)
210
+ return P_hat # n x F+3
211
+
212
+ def get_expand_tensor(self, batch_C_prime):
213
+ B, H, C = batch_C_prime.shape
214
+ batch_C_prime = batch_C_prime.reshape([B, H * C])
215
+ batch_C_ex_part_tensor = self.fc(batch_C_prime)
216
+ batch_C_ex_part_tensor = batch_C_ex_part_tensor.reshape([-1, 3, 2])
217
+ return batch_C_ex_part_tensor
218
+
219
+
220
+ class TPS(nn.Module):
221
+
222
+ def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
223
+ super(TPS, self).__init__()
224
+ self.loc_net = LocalizationNetwork(in_channels, num_fiducial, loc_lr,
225
+ model_name)
226
+ self.grid_generator = GridGenerator(self.loc_net.out_channels,
227
+ num_fiducial)
228
+ self.out_channels = in_channels
229
+
230
+ def forward(self, image):
231
+ image.stop_gradient = False
232
+ batch_C_prime = self.loc_net(image)
233
+ batch_P_prime = self.grid_generator(batch_C_prime, image.shape[2:])
234
+ batch_P_prime = batch_P_prime.reshape(
235
+ [-1, image.shape[2], image.shape[3], 2])
236
+ is_fp16 = False
237
+ if batch_P_prime.dtype != torch.float32:
238
+ data_type = batch_P_prime.dtype
239
+ image = image.float()
240
+ batch_P_prime = batch_P_prime.float()
241
+ is_fp16 = True
242
+ batch_I_r = F.grid_sample(image, grid=batch_P_prime)
243
+ if is_fp16:
244
+ batch_I_r = batch_I_r.astype(data_type)
245
+
246
+ return batch_I_r