机器视觉开发-摄像头扫描二维码

以下是使用Python和OpenCV实现摄像头扫描二维码的最简单示例:

import cv2
from pyzbar import pyzbar

# 打开摄像头
cap = cv2.VideoCapture(0)

print("正在扫描二维码... (按 'q' 键退出)")

while True:
    # 读取摄像头帧
    ret, frame = cap.read()
    
    if not ret:
        print("无法获取摄像头画面")
        break
    
    # 查找并解码二维码
    barcodes = pyzbar.decode(frame)
    
    # 处理检测到的二维码
    for barcode in barcodes:
        # 提取二维码数据
        barcode_data = barcode.data.decode("utf-8")
        barcode_type = barcode.type
        
        # 在图像上绘制二维码边框和内容
        (x, y, w, h) = barcode.rect
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        # 显示二维码内容
        text = f"{barcode_type}: {barcode_data}"
        cv2.putText(frame, text, (x, y - 10), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        
        # 打印到控制台
        print(f"检测到二维码: {text}")
    
    # 显示画面
    cv2.imshow("二维码扫描器", frame)
    
    # 按'q'键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()

代码说明:

  1. ​依赖库​​:

    • opencv-python:用于摄像头捕获和图像显示
    • pyzbar:用于二维码/条形码识别
  2. ​安装依赖​​:

    pip install opencv-python pyzbar
  3. ​主要功能​​:

    • 打开默认摄像头
    • 实时检测画面中的二维码
    • 在画面中标记二维码位置
    • 显示二维码内容和类型
    • 在控制台输出检测结果
  4. ​支持的二维码类型​​:

    • QR Code
    • Code 128
    • EAN-13
    • UPC-A
    • 等多种常见条码/二维码格式

效果: 

你可能感兴趣的:(opencv,python,人工智能)