You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何终止条码识别代码中的for循环并停止打印重复值?

条码/二维码识别代码修改方案

针对原代码需要实现的两个需求:

  • 识别到条码后终止遍历条码的for循环
  • 不再重复打印已识别过的条码值

修改后的完整代码

import cv2
from pyzbar import pyzbar

# 存储已识别过的条码,避免重复输出
recognized_barcodes = set()

def read_barcodes(frame):
    global recognized_barcodes
    barcodes = pyzbar.decode(frame)
    for barcode in barcodes:
        x, y, w, h = barcode.rect
        barcode_info = barcode.data.decode('utf-8')
        
        # 只处理未识别过的条码
        if barcode_info not in recognized_barcodes:
            recognized_barcodes.add(barcode_info)
            # 绘制识别框和条码内容
            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.8, (255, 255, 255), 1)
            # 打印并写入文件
            print(barcode_info)
            with open("barcode_result.txt", mode='w') as file:
                file.write("Recognized Barcode:" + barcode_info)
        # 终止for循环,只处理第一个条码
        break
    return frame

def main():
    camera = cv2.VideoCapture(0)
    ret, frame = camera.read()
    
    while ret:
        ret, frame = camera.read()
        frame = read_barcodes(frame)
        cv2.imshow('Barcode/QR code reader', frame)
        # 按ESC键退出
        if cv2.waitKey(1) & 0xFF == 27:
            break
    
    camera.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

关键修改说明

  • 新增recognized_barcodes集合,利用集合的去重特性记录已识别的条码,避免重复输出
  • 在for循环内部处理完第一个条码后立即执行break,终止循环,不再处理同帧内的其他条码
  • 调整了cv2.putText的字体大小(从2.0改为0.8),避免条码内容显示超出画面(可根据实际需求调整)
  • 移除了未使用的time模块导入

内容的提问来源于stack exchange,提问作者Ashwin Guna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:15:36