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

如何在视频画面中显示截取的人脸?附现有实现代码

How to Display Cropped Faces on Your Video Feed

Hey there! I see you've got a solid face detection setup going—saving cropped faces and showing the total count is already working great. To add the feature of displaying each cropped face directly on the video frame, here's a step-by-step adjustment to your code:

Key Idea

We'll store each cropped face as a resized thumbnail, then draw these thumbnails in a neat grid (row-by-row) on a designated area of your video feed. This keeps the main detection area clear while letting you see all captured faces at a glance.

Modified Code

import numpy as np
import cv2
import time
from time import strftime

# Initialize variables for face storage and display
num = 0
total = 0
cropped_faces = []  # List to hold resized cropped faces for on-screen display
thumb_width, thumb_height = 100, 100  # Size of face thumbnails
start_x, start_y = 10, 80  # Starting position for the first thumbnail
spacing = 10  # Space between each thumbnail
max_per_row = 5  # Max number of thumbnails per row

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
previous_millis = 0

while True:
    ret, img = cap.read()
    if not ret:
        break  # Exit loop if video capture fails
    
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    font = cv2.FONT_HERSHEY_SIMPLEX

    # Draw header text
    cv2.putText(img, 'Person Count Algorithm', (10, 50), font, 1, (255, 0, 0), 2, cv2.LINE_AA)

    millis = int(round(time.time() * 1000))  # Fixed to standard millisecond calculation
    interval = 2000

    if (millis - previous_millis) >= interval:
        previous_millis = millis
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        
        print("FOUND", len(faces), 'PERSON')
        total += len(faces)
        print('Total Count:', total)

        for (x, y, w, h) in faces:
            # Draw rectangle around detected face
            cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
            roi_color = img[y:y+h, x:x+w]
            
            # Label the detected face
            cv2.putText(img, 'person', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 0), 2)
            
            # Save the cropped face to folder
            cv2.imwrite(f'crop_faces/crop{num}.jpg', roi_color)
            num += 1
            
            # Resize and store the face for on-screen display
            resized_face = cv2.resize(roi_color, (thumb_width, thumb_height))
            cropped_faces.append(resized_face)

    # Display total count (cleaned up from your original code)
    cv2.circle(img, (470, 63), 63, (255, 0, 0), 3)
    cv2.putText(img, 'Total Count:', (420, 40), font, 0.5, (255, 0, 0), 1, cv2.LINE_AA)
    cv2.putText(img, str(total), (436, 100), font, 2, (255, 0, 0), 2, cv2.LINE_AA)

    # Draw all cropped face thumbnails on the frame
    for idx, face in enumerate(cropped_faces):
        # Calculate position for each thumbnail
        row = idx // max_per_row
        col = idx % max_per_row
        pos_x = start_x + col * (thumb_width + spacing)
        pos_y = start_y + row * (thumb_height + spacing)
        
        # Ensure we don't draw outside the video frame bounds
        if pos_y + thumb_height < img.shape[0] and pos_x + thumb_width < img.shape[1]:
            img[pos_y:pos_y+thumb_height, pos_x:pos_x+thumb_width] = face

    # Show the final frame with all elements
    cv2.imshow('image', img)
    k = cv2.waitKey(1) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

What Changed?

  • Added thumbnail storage: The cropped_faces list keeps track of every resized face we capture, so we can display them consistently on every frame.
  • Smart positioning logic: We calculate each thumbnail's position using rows and columns, ensuring they arrange neatly without overlapping.
  • Fixed millisecond calculation: Changed time.time() * 5000 to time.time() * 1000 to get standard milliseconds, so your 2-second detection interval works as expected.
  • Added error handling: The if not ret: break line prevents crashes if the video capture fails unexpectedly.

Customization Tips

  • Adjust thumb_width/thumb_height to make face previews bigger or smaller.
  • Change start_x/start_y to move the preview area to another part of the screen (like the right side).
  • Modify max_per_row to change how many faces fit in each row.
  • If you don't want to keep all historical faces, limit the cropped_faces list length (e.g., if len(cropped_faces) > 20: cropped_faces.pop(0) to keep only the last 20 faces).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:37:34