draw_green_boxes_on_mask.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_mask(mask_path, regions_json_path, output_path):
  12. """
  13. 在遮罩图上绘制绿色边框(支持中文路径)
  14. """
  15. # 读取遮罩图(支持中文路径)
  16. mask_data = np.fromfile(str(mask_path), dtype=np.uint8)
  17. mask = cv2.imdecode(mask_data, cv2.IMREAD_COLOR)
  18. if mask is None:
  19. raise ValueError(f"无法读取遮罩图: {mask_path}")
  20. print(f"[INFO] 遮罩图尺寸: {mask.shape[1]}x{mask.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(mask, (x1, y1), (x2, y2), (0, 255, 0), 2) # 绿色,线宽2
  33. print(f"[INFO] 绘制区域 {i+1}: ({x1},{y1}) -> ({x2},{y2})")
  34. # 保存结果(支持中文路径)
  35. success, encoded_img = cv2.imencode('.png', mask)
  36. if success:
  37. encoded_img.tofile(str(output_path))
  38. print(f"[SUCCESS] 已保存带绿色边框的遮罩图: {output_path}")
  39. else:
  40. raise RuntimeError(f"保存图片失败: {output_path}")
  41. def main():
  42. if len(sys.argv) != 4:
  43. print("用法: python draw_green_boxes_on_mask.py <遮罩图路径> <区域JSON路径> <输出图片路径>")
  44. sys.exit(1)
  45. mask_path = Path(sys.argv[1])
  46. regions_json_path = Path(sys.argv[2])
  47. output_path = Path(sys.argv[3])
  48. try:
  49. draw_green_boxes_on_mask(mask_path, regions_json_path, output_path)
  50. except Exception as e:
  51. print(f"[ERROR] 绘制失败: {e}")
  52. sys.exit(1)
  53. if __name__ == "__main__":
  54. main()