LayoutParserとは
LayoutParserは、レイアウト検出、文字認識、その他多くの文書処理タスクに応用が可能なDLベースのレイアウト解析ツールです。(ライセンスはApache 2.0)大まかなレイアウトに対する物体検出結果を合成し、意味のあるまとまりを持ったテキストで抽出することが可能です。また、事前に画像とそれに対して座標情報と文字列をアノテーションした複数のXMLファイルを用意して、学習済みモデルをfine tuningすることができ、個別の用途にカスタマイズすることが可能です。
pre-trained modelの紹介
LayoutParserにはすでに多くの学習済みモデルが存在します。それぞれのモデルは既に個別の用途に最適なモデルとなっており、自分達がこれから処理するドキュメントのレイアウトにある程度似ていれば学習済みモデルをそのまま使用しても一定の精度が見込めます。以下の表1では学習済みモデルの学習データとその概要についてのまとめです。
サンプルコード
import layoutparser as lp
model = lp.Detectron2LayoutModel(
config_path ='lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config',
# In model catalog
label_map ={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"}, # In model`label_map`
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8]
# Optional
)
model.detect(image)
実行コード
OCRツールとしてはtesseractを使用しています。
import layoutparser as lp
import cv2
def layoutparser(image):
model = lp.Detectron2LayoutModel('lp://PubLayNet/faster_rcnn_R_50_FPN_3x/config',
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.9],
label_map={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"})
layout = model.detect(image)
text_blocks = lp.Layout([b for b in layout if b.type=='Figure'])
return text_blocks
def tesseract(text_blocks):
ocr_agent = lp.TesseractAgent(languages='jpn')
for block in text_blocks:
segment_image = (block
.pad(left=5, right=5, top=5, bottom=5)
.crop_image(img))
text = ocr_agent.detect(segment_image)
block.set(text=text, inplace=True)
for txt in text_blocks.get_texts():
print(txt, end='\n---\n')
def main():
img = cv2.imread("sample.png")
text_blocks = layoutparser(img)
txt = tesseract(text_blocks)
if __name__ == '__main__':
main()
出力結果
元画像

出力画像

fine-tuningの仕方
fine-tuningに必要なものは、画像データとアノテーションがなされたXMLファイルです。
以下のGithubに詳しいfine-tuning方法が記載されています。
GitHub - Layout-Parser/layout-model-training: The scripts for training Detectron2-based Layout Models on popular layout analysis datasets
The scripts for training Detectron2-based Layout Models on popular layout analysis datasets - GitHub - Layout-Parser/layout-model-training: The scripts for training Detectron2-based Layout Models ...
参考文献
https://layoutparser.readthedocs.io/en/latest/example/deep_layout_parsing/index.html