OpenCV 模块不在 Raspberry Pi 中重复循环 4. 在 windows 上工作正常

OpenCV module not repeating loop in Raspberry Pi 4. Working fine on windows

首先让我说我对 Python 和 Raspberry Pi 很陌生。

我已经在 windows 上“制作”(更像是从许多差异源复制并编译)一个模块,用于在按键时从网络摄像头捕获图像并将其保存在文件夹中(附上代码)。它在 windows 上工作正常并重复循环,但在第一个循环后 Raspberry Pi 上抛出错误。

windows的代码:-

# Import Modules #######################################################################################################

from datetime import datetime
import cv2
import time
import queue
import threading


# Module Level Variables ###############################################################################################


inpath = "D:\Python Projects\OCR Trial2\Input\Training Data\"
outpath = "D:\Python Projects\OCR Trial2\Output\"
intpath = "D:\Python Projects\OCR Trial2\Intermediate\"
file_Prefix = 'IMG100'
file_Extension = '.png'


# Class Definitions ####################################################################################################

class VideoCapture:

    def __init__(self, name):
        self.cap = cv2.VideoCapture(name)
        self.q = queue.Queue()
        t = threading.Thread(target=self._reader)
        t.daemon = True
        t.start()

    def _reader(self):
        while True:
            ret, frame = self.cap.read()
            if not ret:
                break
            if not self.q.empty():
                try:
                    self.q.get_nowait()
                except queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        return self.q.get()

# Functions ############################################################################################################

def main():
    while True:
        try:
            windowName = "Live Video Feed"
            cv2.namedWindow(windowName)

            if cv2.waitKey(1) == ord("c"):

                time.sleep(1)
                now = datetime.now()
                formatted_time = now.strftime('%Y-%m-%d %H-%M-%S.%f')[:-3]
                cam = VideoCapture(0 + cv2.CAP_DSHOW)
                frame1 = cam.read()
                cv2.imshow(windowName,frame1)
                cv2.imwrite(intpath + file_Prefix + formatted_time + file_Extension, frame1)
                print(formatted_time)
            else:
                continue
        except:
            pass

# Execute Code #########################################################################################################

if __name__ == "__main__":
    main()

Windows 的输出:-

2021-01-06 17-20-05.255
2021-01-06 17-20-07.404
2021-01-06 17-20-08.601
2021-01-06 17-20-10.766
2021-01-06 17-20-12.408

Process finished with exit code -1

Raspberry Pi的代码:-

# Import Modules #######################################################################################################

from datetime import datetime
import cv2
import time
import queue
import threading

# Module Level Variables ###############################################################################################



intpath = "/home/pi/Python Images/"
file_Prefix = 'IMG100'
file_Extension = '.png'


# Class Definitions ####################################################################################################

class VideoCapture:

    def __init__(self, name):
        self.cap = cv2.VideoCapture(name)
        self.q = queue.Queue()
        t = threading.Thread(target=self._reader)
        t.daemon = True
        t.start()

    def _reader(self):
        while True:
            ret, frame = self.cap.read()
            if not ret:
                break
            if not self.q.empty():
                try:
                    self.q.get_nowait()
                except queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        return self.q.get()

# Functions ############################################################################################################


def main():
    while True:
        try:
            windowName = "Live Video Feed"
            cv2.namedWindow(windowName)

            if cv2.waitKey(1) == ord("c"):

                time.sleep(1)
                now = datetime.now()
                formatted_time = now.strftime('%Y-%m-%d %H-%M-%S.%f')[:-3]
                cam = VideoCapture(0)
                frame1 = cam.read()
                cv2.imshow(windowName,frame1)
                cv2.imwrite(intpath + file_Prefix + formatted_time + file_Extension, frame1)
                print(formatted_time)
            else:
                continue
        except:
            pass

# Execute Code #########################################################################################################


if __name__ == "__main__":
    main()

Raspberry Pi 的输出:-

2021-01-06 17-07-59.501
[ WARN:4] global /tmp/pip-wheel-qd18ncao/opencv-python/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index

Process finished with exit code 137 (interrupted by signal 9: SIGKILL)

Raspberry Pi 上的 Open CV 模块是通过 PIP 安装的,不是手动编译的。一般的 OpenCV 功能,如视频捕获和 imshow 在 Raspberry Pi 上工作正常,它成功捕获了第一张照片但无法捕获第二张照片。 请指出可能是什么问题,我接下来可以尝试什么。

编辑 1 - 添加了这是打印异常后的整个错误:-

/home/pi/PycharmProjects/pythonProject/venv/bin/python "/home/pi/PycharmProjects/pythonProject/Image Capture.py"
2021-01-07 15-07-36.555
[ WARN:4] global /tmp/pip-wheel-qd18ncao/opencv-python/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
Traceback (most recent call last):
  File "/home/pi/PycharmProjects/pythonProject/Image Capture.py", line 72, in <module>
    main()
  File "/home/pi/PycharmProjects/pythonProject/Image Capture.py", line 59, in main
    frame1 = cam.read()
  File "/home/pi/PycharmProjects/pythonProject/Image Capture.py", line 42, in read
    return self.q.get()
  File "/usr/lib/python3.7/queue.py", line 170, in get
    self.not_empty.wait()
  File "/usr/lib/python3.7/threading.py", line 296, in wait
    waiter.acquire()
KeyboardInterrupt

Process finished with exit code 1

你的错误可能是 cam = VideoCapture(0) 内部循环。

您应该只创建一次 - 在循环之前。

如果您尝试第二次使用它(例如在循环中),那么在它仍然使用以前的 cam = VideoCapture(0).

之前系统无法访问它