PythonでOCR
Netflixの字幕がダウンロードできると知ったので実行してみたが、 日本語字幕が画像だった※ため、PythonでOCRにかけて文字列に変換した。結果は微妙。
※ 後でエピソード単位だと日本語字幕を文字列で取得できることに気付いた。。。作品単位だと画像になる模様。
Install
OSはWindows10。ORCには以下の2つが必要。
- pyorc-0.5.3
- tesseract-ocr-setup-3.05.02-20180621
1はpip。
2は、Tesseract at UB Mannheimから、
tesseract-ocr-setup-3.05.02-20180621.exe
をダウンロードして実行。
最初3.02を使っていたが、精度が低かったため、3.05を選択。
4.00が出てるので、そちらの方がいいかも。
exe実行時、OCRにかける言語を選択するオプションでは日本語を選択すること。
Code
以下のコードを実行すると、字幕画像を文字列にしてファイルに出力してくれる。 OCRで解析したい画像字幕のフォルダはimg_dirに指定する。 文字列にした字幕ファイルもここに保存される。 なお、コードはgithubにも上げてます。
# coding: utf-8 from PIL import Image import sys import pyocr import pyocr.builders import os from tqdm import trange # Set Netflix subtitle image directory. img_dir = '../data/planetes/PLANETES.S01E02.WEBRip.Netflix/' # Get a tool. tools = pyocr.get_available_tools() if len(tools) == 0: print("No OCR tool found") sys.exit(1) tool = tools[0] print("Will use tool '%s'" % (tool.get_name())) langs = tool.get_available_languages() print("Available languages: %s" % ", ".join(langs)) # Image to string. txts = [] img_names = [f for f in os.listdir(img_dir) if f.split('.')[-1].lower() in ('png')] img_names = sorted(img_names) print(img_names) for i in trange(len(img_names), desc='img 2 str'): txt = tool.image_to_string( Image.open(img_dir+img_names[i]), lang='jpn', builder=pyocr.builders.TextBuilder() ) print(txt) txts.append(txt) # Save the subtitle. subs = open(img_dir+'subs.txt', 'w') subs.write('\n'.join(txts)) subs.close()
Result
複雑な漢字が苦手らしい。縁取りがあるからな気もする。 また、他の画像でも試したが、画像の大きさとも精度が相関している模様。
画像
文字列
ステ一 ンヨノ建L ロ時に出た廃某 武物画像
文字列
これなんか
かなり当たるようですよ