Peter  Lunk
Published © GPL3+

QR-code generator and scanner Python script / OpenCV

A simple app to scan or Generate QR-codes from text or URL's ( (ChatGPT helped me create this code.)

IntermediateProtip1 hour9
QR-code generator and scanner Python script / OpenCV

Story

Read more

Code

Simple QR-code generator and scanner in Python.

Python
QR-code generator and scanner.
1. Scan QR-codes with webcam and get the contents returned to console.
2. Create QR-codes from Text or URL
# Script to offer choice between generating a QR code or scanning a QR code

import qrcode
import cv2
import pyzbar.pyzbar as pyzbar
import webbrowser

def generate_qr_code(input_text, file_name):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(input_text)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    img = img.resize((500, 500))
    img.save(file_name + ".jpg", "JPEG")

def scan_qr_code():

    print("Please wait for the camera to open!")
    print("After scanning press ESC to return to the menu.")

    # start video capture
    cap = cv2.VideoCapture(0)

    while True:
        # read a frame from the webcam
        _, frame = cap.read()

        # decode the QR code
        decoded_objects = pyzbar.decode(frame)

        # loop over all decoded objects
        for obj in decoded_objects:
            # extract the QR code data
            data = obj.data.decode("utf-8")
            print(data)
            if data.startswith("http"):
                webbrowser.open(data, new=2)
                print("URL detected, scanner stopped.")
                cap.release()
                cv2.destroyAllWindows()
                return
        cv2.imshow("QR Code Scanner", frame)

        key = cv2.waitKey(1)
        if key == 27:
            break

    cap.release()
    cv2.destroyAllWindows()

def start():
    print("Please select an option:")
    print("1. Generate QR code")
    print("2. Scan QR code")

    choice = input()

    if choice == "1":
        user_input = input("Enter a URL or text: ")
        file_name = input("Enter the file name for the QR code (without extension): ")
        generate_qr_code(user_input, file_name)
    elif choice == "2":
        scan_qr_code()
    else:
        print("Invalid choice. Please select either 1 or 2.")
    after_choice()

def after_choice():
    print("Do you want to run again? (yes or no)")
    again = input()
    if again.lower() == "yes":
        start()
    elif again.lower() == "no":
        print("Goodbye!")
    else:
        print("Invalid choice. Please select either 'yes' or 'no'.")
        after_choice()

start()

Credits

Peter  Lunk
5 projects • 31 followers
Contact

Comments

Please log in or sign up to comment.