我有使用 MediaPipe 和深度学习模型进行实时动作检测的代码。我想创建一个 Django 视频流 Web 应用程序并集成此代码来检测帧中的操作。我尝试将整个代码(以及代码中调用的每个函数的函数定义)放在一个单独的 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.py
、views.py
、urls.py
和 html 模板中会包含什么内容。非常感谢!
您的camera.py 不适用于 Django 网站。在当前的代码中,您直接从运行脚本的设备获取视频。因此,如果您在客户端-服务器环境中运行camera.py,它将在服务器上搜索摄像头,但您想要捕获来自用户的流。
因此,要实现您想要的目的,您需要与用户建立套接字连接,并不断捕获数据并将其发送到您的服务器,或者仅使用 WebRTC 进行视频捕获。
这是一个有点复杂的过程,我无法在代码中完全演示,请搜索这些主题,它应该会给您一些见解。