首页 > 解决方案 > Raspi 相机模块不在单独的进程中工作

问题描述

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

基本上,如果我尝试在 a 内运行 rpi 摄像头模块Process,它会在线路上冻结for frame in self.camera.capture_continuous

这是一些示例代码:

主文件

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")

相机.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)

有什么见解吗?

标签: pythonpython-3.xopencvraspberry-pi

解决方案


问题似乎是您有两个不同的进程访问PiCamera模块,这在文档第 5.16 节的常见问题解答中明确禁止:

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

我将您的代码减少到最低限度以显示问题,即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()函数中初始化相机。


推荐阅读