Raspi相机模块无法在单独的过程中工作

时间:2018-11-30 16:12:05

标签: python python-3.x opencv raspberry-pi

我正在尝试构建一个将在Raspberry Pi上运行的多进程应用程序。其中一个进程应该从rpi摄像机获取一帧并将其保存到磁盘上,以供其他进程之一使用。但是,python multiprocessing.Process类如何处理rpi摄像头模块有些奇怪。

基本上,如果我尝试在Process内运行rpi摄像机模块,它将冻结在for frame in self.camera.capture_continuous行。

下面是一些示例代码:

main.py

from multiprocessing import Process
import camera as c
import time, atexit, sh


def cleanUp():
    print("Killed the following processes:\n{}".format(
        sh.grep(sh.ps("aux", _piped=True), "python3")))
    sh.pkill("python3")


# Used to keep any of the processes from being orphaned
atexit.register(cleanUp)

proc = Process(target=c.run)
proc.start()

while True:
    time.sleep(1)
    print("main")

camera.py

from picamera.array import PiRGBArray
from picamera import PiCamera
import cv2

camera = PiCamera()
camera.resolution = (1280, 720)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=(1280, 720))


def run():
    print("run function started")
    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
        print("this never runs")
        cv2.imwrite('frame.jpg', frame.array)
        rawCapture.truncate(0)

有什么见解吗?

1 个答案:

答案 0 :(得分:1)

问题似乎是您有两个不同的进程访问 PiCamera 模块,并且文档中Section 5.16的FAQ中明确禁止使用该进程:

  

相机固件设计为一次只能由一个进程使用。尝试同时使用多个过程中的摄像机会以多种方式失败(从简单的错误到锁定过程)。

我将您的代码减少到最低程度以显示问题,这是在第一个过程中导入camera.py模块时执行相机初始化,但在生成的子过程中执行图像读取-因此有两个进程正在访问摄像机。

#!/usr/bin/env python3

from multiprocessing import Process
import camera as c
import time

proc = Process(target=c.run)
proc.start()

while True:
    time.sleep(1)
    print("main")

还有camera.py模块:

#!/usr/bin/env python3

import os

print('Running in process: {}'.format(os.getpid()))
print('camera = PiCamera()')
print('camera.resolution = (1280, 720)')
print('camera.framerate = 30')
print('rawCapture = PiRGBArray(camera, size=(1280, 720))')


def run():
    print("run function started")
    print('Running in process: {}'.format(os.getpid()))

运行它时,您会看到报告了两个不同的进程ID:

示例输出

Running in process: 51513
camera = PiCamera()
camera.resolution = (1280, 720)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=(1280, 720))
run function started
Running in process: 51514
main
main
main

一种解决方案是在run()函数中初始化相机。