Search code examples
pythontkinterpython-imaging-library

My program decodes a QR code standalone but when I integrate it into Tkinter GUI, it does not


using a web camera and the pyzbar library, I am trying to recognize the contents of the QR code, the web camera sees the QR code, but recognition does not occur, please help me figure it out, below is the code

def qr_webcam_reader():
ret, frame = capture.read()
if ret:
    frame = cv2.resize(frame, (400, 280))
    img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(img)
    imgtk = ImageTk.PhotoImage(image=img)
    LabelCamera.imgtk = imgtk
    LabelCamera.configure(image=imgtk)
for code in decode(frame):
    decoded_data = code.data.decode("utf-8")
    rect_pts = code.rect

    if decoded_data:
        pts = np.array([code.polygon], np.int32)
        cv2.polylines(frame, [pts], True, (255, 0, 0), 3)
        cv2.putText(frame, str(decoded_data), (rect_pts[0], rect_pts[1]), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2)
win.after(10, qr_webcam_reader)

the code below works, but it is important for me to do it with tkinter and read the code in the label after putting it in the database

cap = cv2.VideoCapture(0)

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

    if not success:
        break

    for code in decode(frame):
        decoded_data = code.data.decode("utf-8")
        rect_pts = code.rect

        if decoded_data:
            pts = np.array([code.polygon], np.int32)
            cv2.polylines(frame, [pts], True, (255, 0, 0), 3)
            cv2.putText(frame, str(decoded_data), (rect_pts[0], rect_pts[1]), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2)


    cv2.imshow("camera", frame)

    cv2.waitKey(1)
cap.release()

Solution

  • You need to do the tasks in this order:

    • resize the captured frame
    • decode the resized frame
    • convert the frame to PIL image
    • show the image
    def qr_webcam_reader():
        ret, frame = capture.read()
        if ret:
            # resize frame
            frame = cv2.resize(frame, (400, 280))
            # decode frame
            for code in decode(frame):
                decoded_data = code.data.decode("utf-8")
                if decoded_data:
                    rect_pts = code.rect
                    pts = np.array([code.polygon], np.int32)
                    cv2.polylines(frame, [pts], True, (255, 0, 0), 3)
                    cv2.putText(frame, str(decoded_data), (rect_pts[0], rect_pts[1]), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2)
            # convert the frame to PILL image
            img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(img)
            # show the image
            imgtk = ImageTk.PhotoImage(image=img)
            LabelCamera.imgtk = imgtk
            LabelCamera.configure(image=imgtk)
    
        win.after(10, qr_webcam_reader)