read_qr_img.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import os
  2. import cv2
  3. def read_bounding_boxes(txt_file_path, image_dir:str = None):
  4. """
  5. 读取包含bounding box信息的txt文件。
  6. 参数:
  7. txt_file_path (str): txt文件路径。
  8. image_dir (str): 图片保存位置,默认为None,如果txt文件保存的是图像绝对路径,则此处为空
  9. 返回:
  10. list: 包含图片路径和bounding box的列表。
  11. """
  12. bounding_boxes = []
  13. image_dir = os.path.normpath(image_dir)
  14. with open(txt_file_path, 'r') as file:
  15. for line in file:
  16. parts = line.strip().split()
  17. image_path = f"{image_dir}/{parts[0]}" if image_dir is not None else parts[0]
  18. bbox = list(map(float, parts[1:]))
  19. bounding_boxes.append((image_path, bbox))
  20. return bounding_boxes
  21. def detect_qrcode_in_bbox(image_path, bbox):
  22. """
  23. 在指定的bounding box中检测和解码QR码。
  24. 参数:
  25. image_path (str): 图片路径。
  26. bbox (list): bounding box,格式为[x_min, y_min, x_max, y_max]。
  27. 返回:
  28. str: QR码解码后的信息,如果未找到QR码则返回 None。
  29. """
  30. # 读取图片
  31. img = cv2.imread(image_path)
  32. if img is None:
  33. raise FileNotFoundError(f"Image not found or unable to load: {image_path}")
  34. # 将浮点数的bounding box坐标转换为整数
  35. x_min, y_min, x_max, y_max = map(int, bbox)
  36. # 裁剪出bounding box中的区域
  37. qr_region = img[y_min:y_max, x_min:x_max]
  38. # 初始化QRCodeDetector
  39. qr_decoder = cv2.QRCodeDetector()
  40. # 检测并解码QR码
  41. data, _, _ = qr_decoder.detectAndDecode(qr_region)
  42. return data if data else None
  43. def process_images_with_bboxes(txt_file_path, output_file_path):
  44. """
  45. 根据bounding box文件处理图片并识别QR码,输出结果到txt文件。
  46. 参数:
  47. txt_file_path (str): 包含bounding box信息的txt文件路径。
  48. output_file_path (str): 结果输出的txt文件路径。
  49. """
  50. bounding_boxes = read_bounding_boxes(txt_file_path)
  51. with open(output_file_path, 'w') as output_file:
  52. for image_path, bbox in bounding_boxes:
  53. qr_data = detect_qrcode_in_bbox(image_path, bbox)
  54. output_line = f"{image_path} {bbox} {qr_data}\n"
  55. output_file.write(output_line)
  56. print(output_line.strip())
  57. # Example usage
  58. txt_file_path = "./qrcode_positions.txt"
  59. output_file_path = "./test.txt"
  60. process_images_with_bboxes(txt_file_path, output_file_path)