import os import cv2 def read_bounding_boxes(txt_file_path, image_dir:str = None): """ 读取包含bounding box信息的txt文件。 参数: txt_file_path (str): txt文件路径。 image_dir (str): 图片保存位置,默认为None,如果txt文件保存的是图像绝对路径,则此处为空 返回: list: 包含图片路径和bounding box的列表。 """ bounding_boxes = [] image_dir = os.path.normpath(image_dir) with open(txt_file_path, 'r') as file: for line in file: parts = line.strip().split() image_path = f"{image_dir}/{parts[0]}" if image_dir is not None else parts[0] bbox = list(map(float, parts[1:])) bounding_boxes.append((image_path, bbox)) return bounding_boxes def detect_qrcode_in_bbox(image_path, bbox): """ 在指定的bounding box中检测和解码QR码。 参数: image_path (str): 图片路径。 bbox (list): bounding box,格式为[x_min, y_min, x_max, y_max]。 返回: str: QR码解码后的信息,如果未找到QR码则返回 None。 """ # 读取图片 img = cv2.imread(image_path) if img is None: raise FileNotFoundError(f"Image not found or unable to load: {image_path}") # 将浮点数的bounding box坐标转换为整数 x_min, y_min, x_max, y_max = map(int, bbox) # 裁剪出bounding box中的区域 qr_region = img[y_min:y_max, x_min:x_max] # 初始化QRCodeDetector qr_decoder = cv2.QRCodeDetector() # 检测并解码QR码 data, _, _ = qr_decoder.detectAndDecode(qr_region) return data if data else None def process_images_with_bboxes(txt_file_path, output_file_path): """ 根据bounding box文件处理图片并识别QR码,输出结果到txt文件。 参数: txt_file_path (str): 包含bounding box信息的txt文件路径。 output_file_path (str): 结果输出的txt文件路径。 """ bounding_boxes = read_bounding_boxes(txt_file_path) with open(output_file_path, 'w') as output_file: for image_path, bbox in bounding_boxes: qr_data = detect_qrcode_in_bbox(image_path, bbox) output_line = f"{image_path} {bbox} {qr_data}\n" output_file.write(output_line) print(output_line.strip()) # Example usage txt_file_path = "./qrcode_positions.txt" output_file_path = "./test.txt" process_images_with_bboxes(txt_file_path, output_file_path)