python - 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)
有什么见解吗?
解决方案
问题似乎是您有两个不同的进程访问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()
函数中初始化相机。
推荐阅读
- ios - 尽管宽度相等,但集合视图网格最后一行的显示方式不同 - swift iOS
- mysql - 简单删除查询上的 mysql/innodb 死锁
- android - XML 文件中的单行最大长度限制是多少?
- asp.net-core - 在 .Net Core 应用程序中使用 LinqToSql 作为 ORM 的参考存储库类
- angular - 如何使用不同下拉菜单中的选项显示-隐藏下拉元素
- css - IE11 中的 CSS 浏览器特定问题
- kubernetes - 如何安全地更改 Kubernetes 集群上 glusterfs 存储类的 resturl?
- linux - 用于 Linux 进程监控的 Python Zabbix API
- php - 调用未定义的方法 Illuminate\Database\Query\Builder::passengers()
- javascript - setTimeout 似乎越来越短