mark_ocr_loca.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. """测试ocr的位置,与预期是否一致"""
  3. from PIL import Image, ImageDraw
  4. import json
  5. from pathlib import Path
  6. def draw_rectangles_on_image(image_path, rectangles, output_path):
  7. image = Image.open(image_path)
  8. draw = ImageDraw.Draw(image)
  9. for rectangle in rectangles:
  10. top_left = (rectangle['left'], rectangle['top'])
  11. bottom_right = (rectangle['left'] + rectangle['width'], rectangle['top'] + rectangle['height'])
  12. draw.rectangle([top_left, bottom_right], outline='red', width=2)
  13. image.save(output_path)
  14. rectangles = [
  15. ]
  16. with open("log.txt", "r", encoding="utf-8") as f:
  17. try:
  18. ocr_data = json.loads(f.read())
  19. except json.decoder.JSONDecodeError:
  20. print("json格式化错误")
  21. for i in ocr_data['words_result']:
  22. for char_loca in i['chars']:
  23. rectangles.append(char_loca['location'])
  24. script_path = Path(__file__).resolve()
  25. script_directory = script_path.parent
  26. transformed_image_path = str(Path(script_directory, r"transformed_image.jpg"))
  27. draw_rectangles_on_image(transformed_image_path, rectangles, 'output_with_rectangles.jpg')