通过 django 将视频流式传输到网页时获取默认图像

问题描述 投票:0回答:1

My moto:-* 创建一个接受视频文件的网页,一旦通过提交按钮提交,视频(以帧的形式)将显示在同一页面的另一个 div 部分中。显示为帧的原因是我需要处理每个帧。 (将帧渲染到网页上)。*

我的django代码

    if request.method == 'POST':
        try:
            video_file = request.FILES["video"]
            if video_file:
                video_filename = "temp_video.mp4"
                video_filepath = os.path.join(settings.STATIC_ROOT, video_filename)
                with open(video_filepath, 'wb') as destination:
                    for chunk in video_file.chunks():
                        destination.write(chunk)
                video_cap = cv2.VideoCapture(video_filepath)
                if not video_cap.isOpened():
                    print("Error: Could not open video file")
                    return "Error in processing video."
                while True:
                    ret, frame = video_cap.read()
                    if not ret:
                        break
                    else:
                        #cv2.imshow("output",frame) tried this too but not working.
                        frame_bytes = frame.tobytes()
                        yield (b'--frame\r\n'
                            b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n\r\n')
            else:
                print("no video file")
        except Exception as e:
            print("An error occurred:", e)
            return "An error occurred while processing the video."
def process_video(request):
    return StreamingHttpResponse(gen(request),content_type='multipart/x-mixed-replace; boundary=frame')

我的javascript(在html文件中):-

<script src="https://code.jquery.com/jquery-3.5.1.js"
        integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script>
        document.getElementById('uploadForm').addEventListener('submit', function (event) {
            event.preventDefault(); // Prevent default form submission behavior
            const formData = new FormData(this);
            fetch(this.action, {
                method: this.method,
                body: formData})
                .then(response => {
                    // Handle response
                    // Define a function to handle each frame received
                    function handleFrame(frameUrl) {
                        // Create a new image element
                        var img = $('<img>')
                            .attr('src', frameUrl)
                            .attr('height', '100px')
                            .attr('width', '100px');
                        $('#video-display').empty().append(img);}
                    // Create a function to process the streaming response
                    function processResponse(response) {
                        var contentType = response.headers.get('content-type');                        
                        if (contentType && contentType.indexOf('multipart/x-mixed-replace') !== -1) {const reader = response.body.getReader();
                            async function read() {
                                while (true) {
                                    // Read the next chunk
                                    const { done, value } = await reader.read();
                                    // If the chunk is done, break the loop
                                    if (done) {
                                        break;}
                                    // Convert the chunk to a blob and create a URL for it
                                    const blob = new Blob([value], { type: 'image/jpeg' });                                    const imageUrl = URL.createObjectURL(blob);
                                    // Handle the frame
                                    handleFrame(imageUrl);}}
                            // Start reading chunks
                            read();}}
                    // Process the streaming response
                    processResponse(response);})
                .catch(error => {
                    console.error('Error:', error);});});
    </script>

我的html:-

{% load static %}
<!DOCTYPE html>
<form class="home-form" id="uploadForm" action="{% url 'process_video' %}" method="post"
                        enctype="multipart/form-data">
                        {% csrf_token %}
                        <input type="file" accept="video" id="video-file" name="video"
                            placeholder="Enter your video here" class="home-input input" />
                        <div class="home-container08">
                            <button type="reset" class="home-button button">
                                <span>
                                    <span>Reset</span>
                                    <br />
                                </span>
                            </button>
                            <button type="submit" class="home-button1 button">Submit</button>
                        </div>
                    </form> <div id="video-display" class="home-container16">
                </div>

我的终端:-

February 19, 2024 - 16:04:33
Django version 5.0.2, using settings 'final.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

[19/Feb/2024 16:04:50] "GET / HTTP/1.1" 200 9358
[19/Feb/2024 16:05:07] "POST /process-video/ HTTP/1.1" 200 846041346

我的应用程序中的

urls.py:-

from django.urls import path
from . import views
urlpatterns= [
    path("",views.home,name="home"),
     path('process-video/', views.process_video, name='process_video'),]
django项目中的

urls.py:-

from django.contrib import admin
from django.urls import path,include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("myapp.urls"))
]
# Add staticfiles_urlpatterns to urlpatterns
urlpatterns += staticfiles_urlpatterns()

输出是这样的enter image description here 这是我的文件结构enter image description here

图标图像也在更新,但图像没有显示,视频也按预期存储在静态文件中。

请帮帮我。预先感谢。

javascript html django forms video-streaming
1个回答
0
投票

这对我不起作用。所以,我使用了套接字编程而不是 StreamingResponse。它比仅仅将框架生成到网页上效果更好。 使用相关库访问socket编程并通过emit函数返回帧。

© www.soinside.com 2019 - 2024. All rights reserved.