gpt4 book ai didi

python - Raspi 相机模块无法在单独的进程中工作

转载 作者:太空宇宙 更新时间:2023-11-03 21:40:55 25 4
gpt4 key购买 nike

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

基本上,如果我尝试在 Process 中运行 rpi 相机模块, 它卡住在 for frame in self.camera.capture_continuous行。

下面是一些示例代码:

主要.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")

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

有什么见解吗?

最佳答案

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

The camera firmware is designed to be used by a single process at a time. Attempting to use the camera from multiple processes simultaneously will fail in a variety of ways (from simple errors to the process locking up).

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

关于python - Raspi 相机模块无法在单独的进程中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com