0

I'm trying to write a program that detects my eyes and then just keeps them and blackens the rest of the video.

so I just have the coordinates of eyes and I want to keep these sub-matrices and make the rest of the matrix to zero.

example

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)
while(True):
    ret, img = cap.read()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]


        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:

            # how to  keep this : img[y+ey:y+ey+eh,x+ex:x+ex+ew] ????

            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),4)

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


cap.release()
cv2.destroyAllWindows()


generally, how can we do this fast and simple?

Mohy Fahim
  • 49
  • 9
  • 1
    Simple would be making a new matrix with np.zeros_like(img) and copying eyes as img[top:bottom,left:right,:] into it. It's probably fast enough too if not fastest. – IcedLance Jun 04 '19 at 10:25

1 Answers1

1

I think it's hard to think about how to keep parts of the matrix and zero the rest, simply because "the rest" is a rather irregular shape.

Since you can easily process rectangular sub-matrices using a Region of Interest, you can create a zero matrix of the same size as your initial matrix, compute ROIs for the regions you want to keep, and assign them to ROIs at identical positions in the zero matrix.

See OpenCV C++, getting Region Of Interest (ROI) using cv::Mat for details on how to get the ROIs.

Paul92
  • 8,827
  • 1
  • 23
  • 37