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

如何调整集体照人脸检测矩形框,使其仅框选人脸而非全身?

解决人脸检测矩形框过大的问题

你当前使用face_recognition库检测集体照人脸时,出现了矩形框框选人物全身的情况,这是因为face_locations()返回的检测框范围偏宽。可以通过收缩检测框坐标的方式,让矩形框精准框选人脸区域,具体修改如下:

修改后的代码

import cv2
import face_recognition as fc

image = fc.load_image_file('classA.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

face_locations = fc.face_locations(image)

# 设置收缩比例,可根据实际图片调整(建议0.1~0.2之间)
scale = 0.15

for (top, right, bottom, left) in face_locations:
    # 计算收缩后的坐标:向内收缩对应比例的距离
    shrink_top = int(top + (bottom - top) * scale)
    shrink_bottom = int(bottom - (bottom - top) * scale)
    shrink_left = int(left + (right - left) * scale)
    shrink_right = int(right - (right - left) * scale)
    
    # 绘制收缩后的矩形框
    image = cv2.rectangle(image, (shrink_left, shrink_top), (shrink_right, shrink_bottom), (0,255,0), 2)

cv2.imshow('Students present in class detected', image)
cv2.waitKey(0)
cv2.destroyAllWindows()  # 避免窗口残留

核心说明

  1. face_locations()返回的每个检测框格式为(top, right, bottom, left),对应人脸区域的上、右、下、左边界坐标
  2. 通过scale比例控制收缩幅度:
    • 上下方向:从顶部向下、底部向上各收缩对应比例的人脸高度
    • 左右方向:从左向右、右向左各收缩对应比例的人脸宽度
  3. 如果图片中人脸大小差异较大,也可以改用固定像素值收缩(比如shrink_top = top + 20),根据实际效果调整即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:10:20