pythondetectionface-detectionroi

Create Mask Inside ROI selection


Hi I am trying to make the eyes that is circled to be white. I know we cant delete the eyes so i wanted to mask it, but i couldnt figure out a way. Below is my code.

import cv2
import os
cascPathface = os.path.dirname(
cv2.__file__) + "/data/haarcascade_frontalface_alt2.xml"
cascPatheyes = os.path.dirname(
cv2.__file__) + "/data/haarcascade_eye_tree_eyeglasses.xml"

faceCascade = cv2.CascadeClassifier(cascPathface)
eyeCascade = cv2.CascadeClassifier(cascPatheyes)

while True:
img = cv2.imread('man1.png')
newImg = cv2.resize(img, (600,600))
gray = cv2.cvtColor(newImg, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
                                     scaleFactor=1.1,
                                     minNeighbors=5,
                                     minSize=(60, 60),
                                     flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
    cv2.rectangle(newImg, (x, y), (x + w, y + h),(0,255,0), 2)
    faceROI = newImg[y:y+h,x:x+w]
    eyes = eyeCascade.detectMultiScale(faceROI)

    
    for (x2, y2, w2, h2) in eyes:
        eye_center = (x + x2 + w2 // 2, y + y2 + h2 // 2)
        radius = int(round((w2 + h2) * 0.25))
        frame = cv2.circle(newImg, eye_center, radius, (255, 0, 0), 4)

    # Display the resulting frame
cv2.imshow('Image', newImg)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

last = cv2.imwrite('faces_detected.png', faceROI)
cv2.destroyAllWindows()

This is the image where i want the eyes to be white:

enter image description here


Solution

  • In order to mask the eyes, change the thickness parameter in the cv2.circle method to -1. That will fill the circle with the specified color.

    Change the code from frame = cv2.circle(newImg, eye_center, radius, (255, 0, 0), 4) to frame = cv2.circle(newImg, eye_center, radius, (255, 0, 0), -1).

    Refer: https://www.geeksforgeeks.org/python-opencv-cv2-circle-method/

    Kindly do upvote the solution, if you find it helpful.