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

如何用Python检测人脸所在的像素坐标?

获取人脸像素坐标的实现方案

你的代码里,faceCascade.detectMultiScale()返回的faces变量已经存储了所有人脸的像素坐标信息,每一项都是一个包含四个值的元组(x, y, w, h):

  • x:人脸区域左上角的横坐标
  • y:人脸区域左上角的纵坐标
  • w:人脸区域的像素宽度
  • h:人脸区域的像素高度

如果需要提取并使用这些坐标,只需要遍历faces集合即可,以下是修改后的完整代码:

import cv2
import pandas as pd
import win32api, win32con
import time

from PIL import ImageGrab

ImageBox = None
im = ImageGrab.grab(ImageBox)
im.save('screenshot.png')
im.close()
image = cv2.imread("screenshot.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.3,
        minNeighbors=3,
        minSize=(30, 30)
)

print("Found {0} Faces!".format(len(faces)))
# 遍历并输出每个人脸的坐标信息
for idx, (x, y, w, h) in enumerate(faces):
    print(f"第{idx+1}张人脸:左上角坐标({x}, {y}),宽度{w},高度{h}")
    # 可选:计算人脸中心坐标
    center_x = x + w // 2
    center_y = y + h // 2
    print(f"  人脸中心坐标:({center_x}, {center_y})")

如果需要将坐标保存到文件(比如CSV),可以用pandas快速实现:

# 将人脸坐标转为DataFrame并保存
face_coords = pd.DataFrame(faces, columns=['x', 'y', 'width', 'height'])
face_coords.to_csv('face_coordinates.csv', index=False)
print("人脸坐标已保存到face_coordinates.csv")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:55:29