如何将实时摄像头MediaPipe代码集成到Django中

-1 投票
1 回答
96 浏览
提问于 2025-04-14 17:32

我有一段代码,用于实时动作检测,使用的是MediaPipe和一个深度学习模型。我想创建一个Django的视频流网页应用,并把这段代码整合进去,以便从视频帧中检测动作。我尝试把整个代码放到一个类里(包括代码中调用的每个函数的定义),并放在一个单独的Python脚本中(叫做camera.py)。然后我把这个类导入到我的views.py里,但当我运行服务器时,视频帧没有显示出来。这是我想整合到Django应用中的代码:

sequence = []
sentence = []
predictions = []
threshold = 0.5

cap = cv2.VideoCapture(0)
# Set mediapipe model 
with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:
    while cap.isOpened():

        # Read feed
        ret, frame = cap.read()

        # Make detections
        image, results = mediapipe_detection(frame, holistic)
        print(results)
        
        # Draw landmarks
        draw_styled_landmarks(image, results)
        
        # 2. Prediction logic
        keypoints = extract_keypoints(results)
        sequence.append(keypoints)
        sequence = sequence[-30:]
        
        if len(sequence) == 30:
            res = model.predict(np.expand_dims(sequence, axis=0))[0]
            print(actions[np.argmax(res)])
            predictions.append(np.argmax(res))
            
            
        #3. Viz logic
            if np.unique(predictions[-10:])[0]==np.argmax(res): 
                if res[np.argmax(res)] > threshold: 
                    
                    if len(sentence) > 0: 
                        if actions[np.argmax(res)] != sentence[-1]:
                            sentence.append(actions[np.argmax(res)])
                    else:
                        sentence.append(actions[np.argmax(res)])

            if len(sentence) > 5: 
                sentence = sentence[-5:]

            # Viz probabilities
            image = prob_viz(res, actions, image, colors)
            
        cv2.rectangle(image, (0,0), (640, 40), (245, 117, 16), -1)
        cv2.putText(image, ' '.join(sentence), (3,30), 
                       cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
        
        # Show to screen
        cv2.imshow('OpenCV Feed', image)

        # Break gracefully
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()

我想知道camera.pyviews.pyurls.py和HTML模板里应该写些什么。非常感谢!

1 个回答

0

你的camera.py在Django网站上是无法工作的。因为在你现在的代码中,你是直接从运行脚本的设备上获取视频的。所以如果你在客户端-服务器环境中运行camera.py,它会在服务器上寻找摄像头,但你其实是想从用户那里捕捉视频流。

为了实现你的目标,你需要和用户建立一个socket连接,持续捕捉数据并将其发送到你的服务器,或者直接使用WebRTC来进行视频捕捉。

这个过程有点复杂,我无法在代码中完全演示,请你搜索一下这些主题,应该能给你一些启发。

撰写回答