python - 有没有办法在 Django 中控制来自网络摄像头的视频?
问题描述
我必须部署一个机器学习模型来处理来自用户相机的视频,我们必须处理模型的预测。我想让用户能够控制模型输入/从相机获取视频的时间,就像某种可以提供该服务的按钮一样。
目前,我能够对视频源进行预测,但它像每一帧一样是连续的,我正在使用 StreamingHttpResponse 将该帧返回到前端,但 StreamingHttpResponse 中的问题是我不知道如何包含应用程序中的任何控件(停止、继续预测)。
如果除了 StreamingHttpResponse 之外还有其他方法可以实现这一点,或者 StreamingHttpResponse 是否可行,我愿意接受建议 - 请指导我正确的方向
查看允许流式传输功能的函数
def gen(camera):
while True:
frame = cam.get_frame()
# print(frame)
m_image, lab =predict_video(frame, "result")
print(lab)
# m_image = cv2.cvtColor(m_image, cv2.COLOR_RGB2BGR)
ret, m_image = cv2.imencode('.jpg', m_image)
m_image = m_image.tobytes()
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + m_image + b'\r\n\r\n')
def livefeed(request):
try:
return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame")
except Exception as e: # This is bad! replace it with proper handling
print(e)
predict_video 是我在views.py 中编写的另一个函数,它返回修改后的图像(带有边界框的图像)和预测的标签。
cam 是我在另一个 .py 文件中定义的 VideoCamera 类的一个对象,它的定义是这样的:
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
(self.grabbed, self.frame) = self.video.read()
threading.Thread(target=self.update, args=()).start()
def __del__(self):
self.video.release()
def get_frame(self):
image = self.frame
# ret, jpeg = cv2.imencode('.jpg', image)
return image
def update(self):
while True:
(self.grabbed, self.frame) = self.video.read()
视频部分的 urls.py:
path('live/', views.livefeed, name="showlive"),
我在 html 的 img 标记中包含了指向“live/”网址的链接,如下所示:
<h3> This is the live feed </h3>
<img src="{% url 'live' %}">
解决方案
正如您在评论中提到的,您需要每秒 30 帧的视频处理,您需要WebRTC从浏览器/移动设备获取用户相机视频帧并将它们发送到您的后端。
那里有各种 WebRTC 实现,但对于 Python,您可以使用aiortc。
aiortc 是 Python 中用于 Web 实时通信 (WebRTC) 和对象实时通信 (ORTC) 的库。它建立在 Python 的标准异步 I/O 框架 asyncio 之上。
对于您想要实时处理视频的用opencv
例,项目存储库中有一个确切的示例,请查看 aiortc 服务器示例
此示例说明使用浏览器建立音频、视频和数据通道。它还使用 OpenCV 对视频帧执行一些图像处理。
最后,如果您使用的是同步 Django(3 之前的任何内容),则将 Django 用于此服务是不可行的,您应该考虑使用异步框架,如,Django3
或...FastAPI
Starlette
推荐阅读
- sql-server - 系统表 sys.dm_db_xtp_table_memory_stats 导致的数据库属性响应缓慢
- python - Joblib 不在多核上运行
- coq - 作者在 cpdt book 练习中的数据类型是什么意思?
- java - HttpServletRequest 参数映射始终为空
- agm-map - 当我更新在 agm 地图中不起作用的任何多边形 polyPathsChange 方法时
- python-3.x - 将熊猫数据框保存为 csv - python
- angular - 建议和安全规则的分布式计数器/喜欢或投票
- sql - 使用 JOIN 和 GROUP BY 返回结果平均值的 SQL 查询
- python - 为什么这行得通??元类,模型 = 用户
- html - Angular 1.4:进度条无法正常工作