-1

This is my first stack overflow question. Basically, I'm creating a QR code reader that will read a URL on a QR code and automatically open a chrome browser to that link.

The easiest way I've found to do this and allow it to keep running is for the app to keep looping and restarting itself.

Here's my code

#!/usr/bin/env python

import cv2
import urllib.request
import webbrowser
import time
import os

# open a connection to a URL using urllib
webUrl = urllib.request.urlopen

# set up camera object
cap = cv2.VideoCapture(0)

# QR code detection object
detector = cv2.QRCodeDetector()
data=""
triggerTime=0
while True:
    # get the image
    _, img = cap.read()  
    # get bounding box coords and data
    data, bbox, _ = detector.detectAndDecode(img)
   
    # if there is a bounding box, draw one, along with the data
    if(bbox is not None):
        for i in range(len(bbox)):
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
                     0, 255), thickness=2)
        cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    0.5, (0, 255, 0), 2)
        if data:
            url = data
            chrome_path = '/usr/bin/chromium-browser'
            webbrowser.get(chrome_path).open(url)
            print("data found: ", data)
           
            while 1:
                os.system("/home/pi/Desktop/cameratest.py")
                print("Restarting Script")
                exit()
           
           
       
                           
    # display the image preview
    cv2.imshow("QR Parser", img)
    if(cv2.waitKey(1) == ord("q")):
        break
# free camera object and exit
cap.release()
cv2.destroyAllWindows()

So my code runs fine, it reads the QR code, recognizes it and then goes to the URL using Chromium. Once the code loops and attempts to restart itself, it opens the script and then gives "ImportError: No module named cv2"

Any help would be greatly appreciated. I have no clue why this isn't working.

I have opencv2-python installed and I'm running raspbian.

  • What do you mean by the loop in this sentence? "Once the code loops and attempts to restart itself" The while loop in the code? – pullidea-dev Jun 28 '21 at 18:38
  • this while loop while 1: os.system("/home/pi/Desktop/cameratest.py") print("Restarting Script") exit() this runs successfully, it's just once it actually calls the .py script, the import for cv2 fails. This keeps happening Sorry if I'm not being clear, I'm learning how to write software and this is my first project – Josh Brannan Jun 28 '21 at 18:40
  • Why did you exit after print("Restarting Script")? You can continue or break instead of exit because exit will terminate the entire script. – pullidea-dev Jun 28 '21 at 18:42
  • because if I leave this script running, the QR parser will attempt to read more frames in the frame buffer and open multiple tabs. It's an issue that cv2 has, I've not found a way to clear the frame buffer for cv2 so this is my hacky way of completely killing it and restarting it. – Josh Brannan Jun 28 '21 at 18:44
  • Is the filename cameratest.py? So, you are calling the file again in itself? If so, you should use other method to do that. – pullidea-dev Jun 28 '21 at 18:49
  • Like this one. https://stackoverflow.com/questions/36018401/how-to-make-a-python-program-automatically-restart-itself – pullidea-dev Jun 28 '21 at 18:49
  • Yes, cameratest.py is my filename. Yes to both questions. I know how the def method can be used. I just don't know how it would apply here. Ideally, it would work based off if data had been found in a QR code. If data was found, we could call the while loop and restart. Just.... not sure how I'd do that. Like I said, I'm a really new python dev. – Josh Brannan Jun 28 '21 at 19:06
  • 1
    solve this without `system()`. that "solution" solves nothing and it only causes more problems. to prevent the same detection from triggering actions repeatedly, you MUST detect that situation, i.e. keep that `data` in another variable, and compare new detections to that. – Christoph Rackwitz Jun 28 '21 at 20:13

2 Answers2

0

The possibility that there are two versions in raspbian.

When the code starts, a standard version can be obtained so that your code runs without errors, but you have installed cv2 in another version.

the python version that received the cv2 installation is not being used, but what should be used is the default version that is not installed cv2

cardosource
  • 165
  • 1
  • 7
0
 if data:
    url = data
    chrome_path = '/usr/bin/chromium-browser'
    webbrowser.get(chrome_path).open(url)
    print("data found: ", data)
   
    while 1:
        os.system("/home/pi/Desktop/cameratest.py")
        print("Restarting Script")
        exit()

You can change this part to this:

 if data:
    url = data
    chrome_path = '/usr/bin/chromium-browser'
    webbrowser.get(chrome_path).open(url)
    print("data found: ", data)
    if __name__ == '__main__':
        os.execv(__file__, sys.argv)

You might have to import sys

pullidea-dev
  • 1,768
  • 1
  • 7
  • 23