简体   繁体   中英

How to draw a circle when the face is detected in OpenCV - python

So I wrote this code that can detect my face using the webcam and make a rectangle around the face. But how can I draw a circle around the face instead?

import cv2


face_cascade = cv2.CascadeClassifier("face.xml")


cap = cv2.VideoCapture(0)

while True:
    _, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.1, 4)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 100), 3)

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break


cap.release()
for (x, y, w, h) in faces:
    center_coordinates = x + w // 2, y + h // 2
    radius = w // 2 # or can be h / 2 or can be anything based on your requirements
    cv2.circle(img, center_coordinates, radius, (0, 0, 100), 3)

Use the coordinates to find the center of the face and from that point draw a rectangle of radius w/2 or h/2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM