Skip to content

Instantly share code, notes, and snippets.

@cs-mshah
Created March 17, 2023 05:45
Show Gist options
  • Save cs-mshah/fb56e4c9cb1d29d64af034dcbd536bf8 to your computer and use it in GitHub Desktop.
Save cs-mshah/fb56e4c9cb1d29d64af034dcbd536bf8 to your computer and use it in GitHub Desktop.
Scan QR codes from your screen and store them in a file
import cv2
from pyzbar.pyzbar import decode
import pyautogui
import numpy as np
import time
SLEEP = 5
QR_FILE_PATH = 'qr_codes.txt'
if __name__ == '__main__':
qr_codes = set() # set storing scanned qr codes
with open(QR_FILE_PATH, 'r') as file:
line = file.readline()
qr_codes.add(line)
print(f'Detecting QR codes at an interval of {SLEEP} seconds..\nPress ctrl+C to exit.\n')
with open(QR_FILE_PATH, 'a') as file:
while True:
# Take a screenshot
screenshot = pyautogui.screenshot()
# Convert the screenshot to an OpenCV compatible format
img_np = np.array(screenshot)
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
# Convert frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Decode QR codes in the frame
qr_codes_detected = decode(gray)
# Loop over all detected QR codes
for qr_code in qr_codes_detected:
# Extract the QR code's data
data = qr_code.data.decode("utf-8")
if data not in qr_codes:
qr_codes.add(data)
file.write('\n')
file.write(data)
time.sleep(SLEEP)
@cs-mshah
Copy link
Author

Additional requirements:
pyzbar: pip install pyzbar
pyautogui: pip install PyAutoGUI

Just create a file qr_codes.txt and run this code: python screenQR.py in the background. This will scan unique QR codes that appear on your screen and write them to a file. You can re-run this code when you want to resume. I used this to collect QR codes for a treasure hunt prize in wandb's fully-connected-conference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment