Thursday, May 26, 2022

[SOLVED] Running Python Script from Terminal on Raspberry fails but running in IDE is fine

Issue

I've written a Python Script on my Raspberry Pi and its working really fine when running over Thonny IDE. But when i want to start it from Terminal it has a lot of import errors. Ive already added the environment comment on the start of the script. This is my following Code:


    #!/usr/bin/env python
    import cv2
    import time
    import os
    import numpy
    import imutils
    from threading import Thread
    import threading
    
    class WebcamVideoStream:
        def __init__(self, src ='/dev/video0', cap = cv2.CAP_V4L2):
            self.stream = cv2.VideoCapture(src,cap)
            self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))
            self.stream.set(cv2.CAP_PROP_FPS,30.0)
            self.stream.set(cv2.CAP_PROP_FRAME_WIDTH,1280)
            self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT,720)
            (self.grabbed, self.frame) = self.stream.read()
            self.stopped = False
        def start(self):
            Thread(target = self.update, args=()).start()
            return self
        def update(self):
            while(True):
                if self.stopped:
                    return
                (self.grabbed, self.frame) = self.stream.read()
        def read(self):
            return self.frame
        def stop(self):
            self.stopped = True
    if __name__ == "__main__":
        vs = WebcamVideoStream()
        vs.start()
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')
        timeStart = False
        timeStartReal = time.time()
        faceRecNeeded = True
        count = 0
        countFrames = 0
        face_cascade = cv2.CascadeClassifier('/home/pi/Downloads/haarcascade_frontalface_default.xml')
        while True:
            frame = vs.read()
            if faceRecNeeded:
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                # Detect the faces
                faces = face_cascade.detectMultiScale(gray, 1.1, 4)
                    # Draw the rectangle around each face
                for (x, y, w, h) in faces:
                    cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
                    count += 1
            
            if count>0 and timeStart == False:
                faceRecNeeded = False
                timeStart = True
                timeStartReal = time.time()
                out = cv2.VideoWriter('output' + str(time.time()) + '.avi', fourcc, 15.0, (1280, 720))
            count = 0
        
            if timeStart == True and time.time()-timeStartReal < 5:
                out.write(frame)
                countFrames+=1
        
            if timeStart == True and time.time()-timeStartReal >= 5:
                timeStart = False
                faceRecNeeded = True
                out.release()
                print(countFrames)
        
            # Display
            #cv2.imshow('img', frame)
            # Stop if escape key is pressed
            if cv2.waitKey(1) & 0xFF == ord('q'):
                if timeStart == True:
                    out.release()
                break
        cv2.destroyAllWindows()
        vs.stop()

This is my output of my Terminal after running cmd = python3 /home/pi/Desktop/DATANAME.py

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/numpy/__init__.py", line 140, in <module>
    from . import core
  File "/usr/lib/python3/dist-packages/numpy/core/__init__.py", line 101, in <module>
    from . import _internal
  File "/usr/lib/python3/dist-packages/numpy/core/_internal.py", line 10, in <module>
    import platform
  File "/usr/lib/python3.9/platform.py", line 119, in <module>
    import subprocess
  File "/usr/lib/python3.9/subprocess.py", line 51, in <module>
    import threading
  File "/home/pi/Desktop/threading.py", line 3, in <module>
    from imutils.video import FPS
  File "/usr/local/lib/python3.9/dist-packages/imutils/video/__init__.py", line 4, in <module>
    from .videostream import VideoStream
  File "/usr/local/lib/python3.9/dist-packages/imutils/video/videostream.py", line 2, in <module>
    from .webcamvideostream import WebcamVideoStream
  File "/usr/local/lib/python3.9/dist-packages/imutils/video/webcamvideostream.py", line 2, in <module>
    from threading import Thread
ImportError: cannot import name 'Thread' from partially initialized module 'threading' (most likely due to a circular import) (/home/pi/Desktop/threading.py)
Traceback (most recent call last):
  File "/home/pi/Desktop/faceDetectionThreading.py", line 2, in <module>
    import cv2
ImportError: numpy.core.multiarray failed to import

Can you help me fix this error, so i can run also over Terminal


Solution

I guess, that your "threading.py" file which is located in the desktop directory. That very likely causes the circular import error since subprocess wrongly imports your own module instead of the python native threading module.

Your problem should be solved, when you rename your threading.py file to not interfer with other modules.



Answered By - Felix Kleine Bösing
Answer Checked By - Marie Seifert (WPSolving Admin)