78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
"""OCR helper with preprocessing for WeChat bubbles (Windows.Media.Ocr, zh-Hans)."""
|
|
import asyncio
|
|
import sys
|
|
|
|
from PIL import Image, ImageOps
|
|
from winsdk.windows.graphics.imaging import BitmapDecoder
|
|
from winsdk.windows.media.ocr import OcrEngine
|
|
from winsdk.windows.globalization import Language
|
|
from winsdk.windows.storage import StorageFile, FileAccessMode
|
|
|
|
ENGINE = None
|
|
|
|
|
|
def engine():
|
|
global ENGINE
|
|
if ENGINE is None:
|
|
ENGINE = OcrEngine.try_create_from_language(Language('zh-Hans-CN'))
|
|
return ENGINE
|
|
|
|
|
|
async def ocr_png(path):
|
|
file = await StorageFile.get_file_from_path_async(path)
|
|
stream = await file.open_async(FileAccessMode.READ)
|
|
decoder = await BitmapDecoder.create_async(stream)
|
|
bitmap = await decoder.get_software_bitmap_async()
|
|
result = await engine().recognize_async(bitmap)
|
|
out = []
|
|
for line in result.lines:
|
|
words = list(line.words)
|
|
if not words:
|
|
continue
|
|
x0 = min(w.bounding_rect.x for w in words)
|
|
y0 = min(w.bounding_rect.y for w in words)
|
|
x1 = max(w.bounding_rect.x + w.bounding_rect.width for w in words)
|
|
y1 = max(w.bounding_rect.y + w.bounding_rect.height for w in words)
|
|
out.append({'text': line.text, 'x': int(x0), 'y': int(y0), 'w': int(x1 - x0), 'h': int(y1 - y0)})
|
|
return out
|
|
|
|
|
|
def preprocess(img, scale=2.5, invert=False):
|
|
img = img.convert('L')
|
|
img = ImageOps.autocontrast(img, cutoff=1)
|
|
# push mid-tones apart so bubble background becomes white and glyphs black
|
|
lut = []
|
|
for i in range(256):
|
|
if i < 110:
|
|
lut.append(0)
|
|
elif i > 175:
|
|
lut.append(255)
|
|
else:
|
|
lut.append(int((i - 110) * 255 / 65))
|
|
img = img.point(lut)
|
|
if invert:
|
|
img = ImageOps.invert(img)
|
|
if scale != 1.0:
|
|
img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
|
|
return img.convert('RGB')
|
|
|
|
|
|
def main():
|
|
path = sys.argv[1]
|
|
scale = float(sys.argv[2]) if len(sys.argv) > 2 else 2.5
|
|
crop = tuple(int(v) for v in sys.argv[3:7]) if len(sys.argv) > 6 else None
|
|
img = Image.open(path).convert('RGB')
|
|
if crop:
|
|
img = img.crop(crop)
|
|
for invert in (False, True):
|
|
out = path + f'.{scale}.{"inv" if invert else "std"}.png'
|
|
preprocess(img, scale, invert).save(out)
|
|
lines = asyncio.run(ocr_png(out))
|
|
print(f'--- invert={invert}')
|
|
for item in lines:
|
|
print(f"[{item['x']},{item['y']} {item['w']}x{item['h']}] {item['text']}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|