Face detection on PC display by OpenCV & Python
There are many articles on the web that explain how to do face detection with OpenCV and Python. However most of them uses image files, video files or web camera as input source. I will explain how to use a specific area of PC display as input source of face detection.
The source code I will introduce is based on that of the following web site.
The modified source code is as follows:
import numpy as np import serial import time import sys import cv2 import PIL.ImageGrab as ImageGrab face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') left = 1000 top = 220 width = 500 height = 500 width2 = int(width / 2) height2 = int(height / 2) while 1: box = (left,top,left+width,top+height) screen = ImageGrab.grab(box) screen = cv2.cvtColor(np.array(screen), cv2.COLOR_RGB2BGR) cap = screen ret, img = 1, cap cv2.line(img,(width,height2),(0,height2),(0,255,0),1) cv2.line(img,(width2,0),(width2,height),(0,255,0),1) faces = face_cascade.detectMultiScale(img, 1.3) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),5) cv2.imshow('img',img) k = cv2.waitKey(30) & 0xff if k == 27: break
“left", “top", “width" and “height" shows the area captured from PC display as input source.
I’m beginner of OpenCV and Python so I cannot explain why the following is needed, but it works fine.
ret, img = 1, cap
The following video shows the program is working.