Skip to main content
 首页 » 编程设计

python之如何实时处理图像并输出结果的实时视频

2024年10月01日9Renyi-Fan

我有一个带摄像头的 Rasberry Pi,我正在使用 RPi Cam Web 界面将视频流式传输到我的浏览器。我运行一个脚本来读取图像并像下面这样处理它们。运行代码会打开一个窗口,其中包含当前已处理的图像。当我关闭窗口时,我会得到更新后的处理图像。

然而,我想做的是输出经过处理的图像的连续视频。我应该采取什么方法来做到这一点?

while True:  
    image = io.imread('http://[ip-address]/cam_pic.php') 
    image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) 
    faces = detect(image_gray) 
    image_with_detected_faces = faces_draw(image, faces) 
    plt.imshow(image_with_detected_faces) 
    plt.show() 

请您参考如下方法:

你可能想看看这个问题:update frame in matplotlib with live camera preview直接使用VideoCapture。相反,如果您想从 http 读取图像,您可以将其更改为以下之一。

交互模式

import cv2 
import matplotlib.pyplot as plt 
 
def grab_frame(): 
    image = io.imread('http://[ip-address]/cam_pic.php') 
    image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) 
    faces = detect(image_gray) 
    return faces_draw(image, faces) 
 
#create axes 
ax1 = plt.subplot(111) 
 
#create image plot 
im1 = ax1.imshow(grab_frame()) 
 
plt.ion() 
 
while True: 
    im1.set_data(grab_frame()) 
    plt.pause(0.2) 
 
plt.ioff() # due to infinite loop, this gets never called. 
plt.show() 

函数动画

import cv2 
import matplotlib.pyplot as plt 
from matplotlib.animation import FuncAnimation 
 
def grab_frame(): 
    image = io.imread('http://[ip-address]/cam_pic.php') 
    image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) 
    faces = detect(image_gray) 
    return faces_draw(image, faces) 
 
#create axes 
ax1 = plt.subplot(111) 
 
#create axes 
im1 = ax1.imshow(grab_frame()) 
 
def update(i): 
    im1.set_data(grab_frame()) 
 
ani = FuncAnimation(plt.gcf(), update, interval=200) 
plt.show()