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
    faces = face_cascade.detectMultiScale(img, 1.3)
    for (x,y,w,h) in faces:
    k = cv2.waitKey(30) & 0xff
    if k == 27:

“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.