如何修改条码识别代码,停止输出重复值并中断重复循环
解决条码/二维码识别重复输出并中断循环的方案
修改思路
- 维护一个已识别条码的集合,用于判断当前条码是否已处理过
- 仅在首次识别到新条码时执行输出和文件写入操作
- 添加逻辑,在成功识别到目标条码后中断视频捕获循环
修改后的完整代码
import numpy as np import cv2 from pyzbar import pyzbar def read_barcodes(frame): barcodes = pyzbar.decode(frame) detected_code = None for barcode in barcodes: x, y, w, h = barcode.rect barcode_info = barcode.data.decode('utf-8') # 绘制识别框与文本 cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, barcode_info, (x + 6, y - 6), font, 0.5, (255, 255, 255), 1) detected_code = barcode_info break # 单帧仅处理第一个识别到的条码 return frame, detected_code def main(): camera = cv2.VideoCapture(0) ret, frame = camera.read() recognized_codes = set() # 存储已识别条码,避免重复处理 stop_flag = False while ret and not stop_flag: ret, frame = camera.read() frame, detected_code = read_barcodes(frame) cv2.imshow('Barcode/QR code reader', frame) if detected_code and detected_code not in recognized_codes: # 首次识别新条码,执行输出与写入 print(f"识别到条码: {detected_code}") recognized_codes.add(detected_code) with open("barcode_result.txt", mode='w') as file: file.write(f"Recognized Barcode: {detected_code}") # 识别后中断循环,若需继续识别其他条码可注释此行 stop_flag = True # 按ESC键手动终止程序 if cv2.waitKey(1) & 0xFF == 27: break camera.release() cv2.destroyAllWindows() if __name__ == '__main__': main()
关键修改说明
- 已识别集合:
recognized_codes集合用于记录已处理的条码,确保同一条码不会被重复输出。 - 函数返回值调整:
read_barcodes返回处理后的帧和识别到的条码信息,让主逻辑能直接判断是否需要处理。 - 重复判断与执行逻辑:仅当条码不在已识别集合中时,才执行打印和文件写入,避免重复操作。
- 循环中断控制:
stop_flag变量控制循环终止,识别到新条码后自动中断;同时保留ESC键手动终止的功能。 - UI优化:将原代码中过大的字体大小(2.0)调整为0.5,避免文本溢出识别框。
- 单帧单条码处理:添加
break确保一帧内只处理第一个识别到的条码,避免同一帧多条码导致的重复输出。
内容的提问来源于stack exchange,提问作者Ashwin Guna
相关产品推荐
相关产品推荐

