Skip to main content
 首页 » 编程设计

python之Pygame 的图像捕获实际上是如何工作的

2024年12月31日9qq78292959

我的目标是使用 Raspberry Pi 设置一个网络摄像头,使其在特定时间(比如 2 分钟)处于事件状态。在此期间,我应该能够随时捕捉静态图像并将该图像保存到文件夹中。我选择使用 pygame。我的项目是在传感器被触发后立即捕捉图像,因此它需要非常灵敏。

根据 Pygame 相机文档 here它说:

open()

Opens the camera device, attempts to initialize it, and begins recording images to a buffer. The camera must be started before any of the below functions can be used.

get_image()

Pulls an image off of the buffer as an RGB Surface. It can optionally reuse an existing Surface to save time. The bit-depth of the surface is either 24 bits or the same as the optionally supplied Surface.

因此对于我的情况,get_image() 似乎只是提取调用 start() 后捕获的第一张图像。我的问题是,我怎样才能到达包含所有捕获图像的缓冲区,或者捕获实际上是如何工作的?在我调用 pygame 相机上的 start() 和 stop() 之后,我找不到捕获和保存静止图像(随时)的解决方案。由于 start() 函数在几秒钟内启动,因此仅调用 start()、get_image() 和 stop() 一个接一个。任何帮助或建议将不胜感激。

请参阅下面的 python 代码:

def activateCapturing: 
    pygame.init() 
    pygame.camera.init() 
    cam = pygame.camera.Camera("/dev/video0",(320,180)) 
    cam.start() 
 
    pngdata = None 
    imageAsbytes = [] 
    activated = True 
 
    while activated: 
        if readSensor(): 
            img = cam.get_image() 
            pygame.image.save(img, "/tmp/image.png") 
            activated = False 
 
     with open("/tmp/image.png", 'rb') as f: 
            pngdata = f.read() 
            imageAsbytes = bytearray(pngdata) 
 
    cam.stop() 
    return imageAsbytes 

提前致谢!

请您参考如下方法:

您只需在拍摄一张图像后不要停止相机。

参见 https://www.pygame.org/docs/tut/CameraIntro.html .

get_image() 从缓冲区获取相机当前看到的图像 - 缓冲区不是“自 start() 以来的所有图片”,而只是当前查看的图像。

您在“捕获窗口”3 秒后使用 stop() 停止获取更多图像。

如果您追求性能,您可能需要向下滚动该页面并查看有关捕获实时流的部分 - 如果您执行相同操作(不显示流)并且刚刚保存需要时将 1 个图像存入磁盘,您应该会获得不错的帧率。

API:get_image()