如何在 reading/deciding 带有 pyzbar 的二维码后关闭我的相机框架?

How do I close my camera frame after reading/deciding a qr code with pyzbar?

我一直在研究这个 QR 码扫描器,到目前为止我已经完成了所有工作;

问题 是我实际上希望在检测到、解码和所有上述过程时 单个 QR 码关闭框架已完成。

实际发生的事情 是框架不断打开后,在检测到二维码后,它实际上记录了多个(大约 15 个)二维码实例2秒。而且框架还在,我仍然可以检测图像。

框架关闭,只有按下等待键27或'Esc'

我试过添加这个:

for obj in decodedObjects:
            id = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data))
            cv2.putText(frame, str(id[0]), (50, 50), font, 3, (255, 255, 255), 2)

            attendee = get_object_or_404(Attendee, pk=str(id[0]))
            attendee.present = True
            attendee.timestamp = timezone.now()
            attendee.time_log.append(attendee.timestamp)
            attendee.save()

            if id is not None:
                cv2.destroyAllWindows()
                break 

但显然这行不通,因为它在 for 循环中...

Here's the code:

from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from .models import Attendee

import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar

def qrscanner(request):
    cap = cv2.VideoCapture(0)

    context = {
        'scan': 'QR Successfully Scanned'
    }

    while True:
        _, frame = cap.read()

        decodedObjects = pyzbar.decode(frame)

        for obj in decodedObjects:
            id = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data))
            cv2.putText(frame, str(id[0]), (50, 50), font, 3, (255, 255, 255), 2)

            attendee = get_object_or_404(Attendee, pk=str(id[0]))
            attendee.present = True
            attendee.timestamp = timezone.now()
            attendee.time_log.append(attendee.timestamp)
            attendee.save()

        cv2.imshow("QR Reader", frame)

        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            cv2.destroyAllWindows()
            break


    return render(request, 'attendees/qrscanner.html', context)

所以我实际上是在寻找2件事:

好的,经过一些测试后,我发现这些小的修改是可行的:

first we add:

while id is None:
        _, frame = cap.read()

        decodedObjects = pyzbar.decode(frame)
...
...

then below we turn the while end function to:

if id is not None:
            cv2.destroyAllWindows()

就是这样!