opencv 如果检测到人脸,我如何添加“发现人脸”?

ssm49v7z  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(193)

这是我写的代码,我希望能够在终端上显示找到了多少张脸,我尝试了一些方法(如果face_coordinates:cv2.imshow(“找到了一个人”,网络摄像头)和其他方法,但没有任何效果

import cv2

# load some pre-trained data on front faces (haarcascade algorithm)
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# to capture video from webcam
webcam = cv2.VideoCapture(1)

# iterate forever over frames
while True:
    successful_frame_read, frame = webcam.read()
    #flip the video (mirror)
    flipped_frame = cv2.flip(frame, 1)
    # convert to grayscale
    grayscaled_img = cv2.cvtColor(flipped_frame, cv2.COLOR_BGR2GRAY)
    # detect faces
    face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
    # show rectangles around the face
    for (x, y, w, h) in face_coordinates:
        cv2.rectangle(flipped_frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    # show the webcam
    cv2.imshow("Fadi's face detector system", flipped_frame)
    key = cv2.waitKey(1)
    # exit app if Q or q are pressed
    if key==81 or key==113:
        break
    if face_coordinates:  # python types can be coerced to boolean
    cv2.imshow("Human was found!", webcam)
    continue
    else:
        cv2.imshow("no human was found...", webcam)
        continue

webcam.release()
l0oc07j2

l0oc07j21#

为了打印在终端中检测到的人脸数量,我尝试计数检测到的不同人脸,并在此基础上,您可以在检测时打印在终端中发现的人类数量。我在您的代码中做了一些小的更改,如下所示。

import cv2

# load some pre-trained data on front faces (haarcascade algorithm)
trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')

# to capture video from webcam
webcam = cv2.VideoCapture(0)

# iterate forever over frames
while True:
    successful_frame_read, frame = webcam.read()
    #flip the video (mirror)
    flipped_frame = cv2.flip(frame, 1)
    # convert to grayscale
    grayscaled_img = cv2.cvtColor(flipped_frame, cv2.COLOR_BGR2GRAY)
    # detect faces
    face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
    count=0
    # show rectangles around the face
    for (x, y, w, h) in face_coordinates:
        count=count+1
        cv2.rectangle(flipped_frame, (x, y), (x+w, y+h), (0, 255, 0), 3)

    # show the webcam
    cv2.imshow("Fadi's face detector system", flipped_frame)
    key = cv2.waitKey(1)
    # exit app if Q or q are pressed
    if key==81 or key==113:
        break
    # python types can be coerced to boolean
    if count==1:
        print(count," human found")
    elif count>0:
        print(count," humans found")
    else:
        print("No human was found")
webcam.release()

相关问题