Detect a QR code in a webcam feed

Oct 20, 2023

Pieced together from a few tutorials on the web. Note that the webcam I was targeting is the second device on my system; you may need to change the argument to VideoCapture to get the proper feed on your computer.

import cv2 as cv

cap = cv.VideoCapture(1)
if not cap.isOpened():
    print("Cannot open camera")

detector = cv.QRCodeDetector()

while True:
    ret, frame =
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")

    data, bbox, _ = detector.detectAndDecode(frame)
    if data:
        frame = cv.polylines(frame, bbox.astype(int), True, (0, 255, 0), 3)

    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):


prerequisite: pip install opencv-python

↑ up