draw_green_boxes_on_original_image.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 在遮罩图上绘制绿色文字区域边框
  5. """
  6. import cv2
  7. import json
  8. import sys
  9. from pathlib import Path
  10. import numpy as np
  11. def draw_green_boxes_on_original_image(image_path, regions_json_path, output_path):
  12. """
  13. 在原图片上绘制绿色边框(支持中文路径)
  14. """
  15. # 读取原图片(支持中文路径)
  16. image_data = np.fromfile(str(image_path), dtype=np.uint8)
  17. image = cv2.imdecode(image_data, cv2.IMREAD_COLOR)
  18. if image is None:
  19. raise ValueError(f"无法读取图片: {image_path}")
  20. print(f"[INFO] 图片尺寸: {image.shape[1]}x{image.shape[0]}")
  21. # 读取文字区域JSON
  22. with open(regions_json_path, 'r', encoding='utf-8') as f:
  23. text_regions = json.load(f)
  24. print(f"[INFO] 需要绘制 {len(text_regions)} 个绿色边框")
  25. # 绘制每个文字区域的绿色边框
  26. for i, region in enumerate(text_regions):
  27. bbox = region['bbox']
  28. # bbox格式: [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
  29. x1, y1 = int(bbox[0][0]), int(bbox[0][1])
  30. x2, y2 = int(bbox[2][0]), int(bbox[2][1])
  31. # 绘制绿色矩形框
  32. cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 3) # 绿色,线宽3
  33. # 移除了编号相关逻辑
  34. print(f"[INFO] 绘制区域 {i+1}: ({x1},{y1}) -> ({x2},{y2})")
  35. # 保存结果(支持中文路径)
  36. success, encoded_img = cv2.imencode('.png', image)
  37. if success:
  38. encoded_img.tofile(str(output_path))
  39. print(f"[SUCCESS] 已保存带绿色边框的图片: {output_path}")
  40. else:
  41. raise RuntimeError(f"保存图片失败: {output_path}")
  42. def main():
  43. if len(sys.argv) != 4:
  44. print("用法: python draw_green_boxes_on_original_image.py <原图片路径> <区域JSON路径> <输出图片路径>")
  45. sys.exit(1)
  46. image_path = Path(sys.argv[1])
  47. regions_json_path = Path(sys.argv[2])
  48. output_path = Path(sys.argv[3])
  49. try:
  50. draw_green_boxes_on_original_image(image_path, regions_json_path, output_path)
  51. except Exception as e:
  52. print(f"[ERROR] 绘制失败: {e}")
  53. sys.exit(1)
  54. if __name__ == "__main__":
  55. main()