You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于OpenCV调用摄像头结合MTCNN实现人脸检测的代码问题

Fixing MTCNN Camera Face Detection Issues

Let's walk through the problems in your code and fix them step by step — it looks like you're mixing up OpenCV and Matplotlib workflows, plus a few other small bugs that are breaking the execution.

Key Issues in Your Original Code:

  • Incorrect image loading: face = pyplot.imread(frame) is wrong because frame is a numpy array from the camera, not a file path. This line is totally unnecessary and causes errors.
  • Blocking display: pyplot.show() halts the loop until you close the Matplotlib window, which makes real-time camera feed impossible.
  • No check for detected faces: You directly access face[0]['box'] without verifying if any faces were found — this will throw an index error when no face is detected.
  • Color space mismatch: MTCNN expects RGB images, but OpenCV captures frames in BGR format.
  • Redundant plotting setup: Creating ax = pyplot.gca() and calling pyplot.imshow(frame) every loop is inefficient and causes display conflicts with OpenCV's cv.imshow().

Corrected Code

We'll stick with OpenCV for display to keep things smooth for real-time feed, and handle MTCNN properly:

from mtcnn.mtcnn import MTCNN
import cv2 as cv

# Initialize camera and detector
cap = cv.VideoCapture(0)
detector = MTCNN()

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to capture frame")
        break

    # Convert BGR (OpenCV) to RGB (MTCNN requirement)
    rgb_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
    
    # Detect faces
    faces = detector.detect_faces(rgb_frame)
    
    # Draw bounding boxes on the original frame
    for face in faces:
        x, y, width, height = face['box']
        # Draw rectangle using OpenCV (BGR color: red)
        cv.rectangle(frame, (x, y), (x + width, y + height), (0, 0, 255), 2)
    
    # Display the frame with detections
    cv.imshow('MTCNN Face Detection', frame)
    
    # Exit on 'q' press
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

# Cleanup
cap.release()
cv.destroyAllWindows()

What We Changed:

  1. Removed Matplotlib dependencies: We use OpenCV's native drawing and display functions for real-time performance, which is far better suited for camera feeds.
  2. Color space conversion: Added rgb_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB) since MTCNN processes RGB images.
  3. Face detection check: We loop over all detected faces (instead of assuming there's at least one) to avoid index errors.
  4. Proper drawing: Used cv.rectangle() to draw red boxes directly on the frame, no need for Matplotlib patches.
  5. Removed blocking calls: No more pyplot.show() — the loop runs smoothly until you press 'q'.

If you still want to use Matplotlib for display (though it's not ideal for real-time), you'd need to use pyplot.ion() for interactive mode and avoid show() in the loop. But the OpenCV approach is the standard for camera-based computer vision tasks.

内容的提问来源于stack exchange,提问作者Jerome Ariola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:48:20