【发布时间】:2021-05-30 02:00:57
【问题描述】:
我必须部署一个机器学习模型,该模型将处理来自用户相机的视频,并且我们必须处理模型的预测。 我想让用户能够控制模型从摄像头输入/获取视频源的时间长短,就像某种可以提供该服务的按钮一样。
目前,我可以对视频源进行预测,但它对于每一帧都是连续的,我正在使用 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' %}">
【问题讨论】:
-
您想要的视频处理 FPS 是多少?
-
我想不到这样的限制,但现在我思考你的问题我意识到动机,如果fps太低,视频会出现滞后,对吧?所以在这种情况下需要 30 FPS(我想 30 就可以了)。
-
知道了,你用的是什么版本的 Django?
-
我正在使用 Django==3.1.6
-
好,也尝试对WebRTC核心概念有更好的理解,你可以看看这个网站WebRTC For The Curious 祝你旅途愉快
标签: python django opencv computer-vision webrtc