Raspberry Pi Face Recognition Using OpenCV with Python

Installing OpenCV For Python

To install OpenCV for Python, all you have to do is use apt-get like below:
sudo apt-get install python-opencv
To test the installation of OpenCV, run this Python script, it will switch on your camera for video streaming if it is working.
1import cv
2 
3cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
4camera_index = 0
5capture = cv.CaptureFromCAM(camera_index)
6 
7def repeat():
8    global capture #declare as globals since we are assigning to them now
9    global camera_index
10    frame = cv.QueryFrame(capture)
11    cv.ShowImage("w1", frame)
12    = cv.WaitKey(10)
13    if(c=="n"): #in "n" key is pressed while the popup window is in focus
14        camera_index += 1 #try the next camera index
15        capture = cv.CaptureFromCAM(camera_index)
16        if not capture: #if the next camera index didn't work, reset to 0.
17            camera_index = 0
18            capture = cv.CaptureFromCAM(camera_index)
19 
20while True:
21    repeat()

Simple Example of Raspberry Pi Face Recognition

This example is a demonstration for Raspberry Pi face recognition using haar-like features. it finds faces in the camera and puts a red square around it. I am surprised how fast the detection is given the limited capacity of the Raspberry Pi (about 3 to 4 fps). Although it’s still much slower than a laptop, but it would still be useful in some robotics applications.
Raspberry Pi Face Recognition and Object Detection Using OpenCV
You will need to download this trained face file:
1#!/usr/bin/python
2 
3The program finds faces in a camera image or video stream anddisplays a red box around them.
4 
5import sys
6import cv2.cv as cv
7from optparse import OptionParser
8 
9min_size = (2020)
10image_scale = 2
11haar_scale = 1.2
12min_neighbors = 2
13haar_flags = 0
14 
15def detect_and_draw(img, cascade):
16    # allocate temporary images
17    gray = cv.CreateImage((img.width,img.height), 81)
18    small_img = cv.CreateImage((cv.Round(img.width / image_scale),
19                   cv.Round (img.height / image_scale)), 81)
20 
21    # convert color input image to grayscale
22    cv.CvtColor(img, gray, cv.CV_BGR2GRAY)
23 
24    # scale input image for faster processing
25    cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)
26    cv.EqualizeHist(small_img, small_img)
27 
28    if(cascade):
29        = cv.GetTickCount()
30        faces = cv.HaarDetectObjects(small_img, cascade, cv.CreateMemStorage(0),
31                                     haar_scale, min_neighbors, haar_flags, min_size)
32        = cv.GetTickCount() - t
33        print "time taken for detection = %gms" %(t/(cv.GetTickFrequency()*1000.))
34        if faces:
35            for ((x, y, w, h), n) in faces:
36                # the input to cv.HaarDetectObjects was resized, so scale the
37                # bounding box of each face and convert it to two CvPoints
38                pt1 = (int(x * image_scale), int(y * image_scale))
39                pt2 = (int((x + w) * image_scale), int((y + h) *image_scale))
40                cv.Rectangle(img, pt1, pt2, cv.RGB(25500), 38,0)
41 
42    cv.ShowImage("video", img)
43 
44if __name__ == '__main__':
45 
46    parser = OptionParser(usage = "usage: %prog [options] [filename|camera_index]")
47    parser.add_option("-c""--cascade", action="store", dest="cascade"type="str"help="Haar cascade file, default %default", default ="../data/haarcascades/haarcascade_frontalface_alt.xml")
48    (options, args) = parser.parse_args()
49 
50    cascade = cv.Load(options.cascade)
51 
52    if len(args) != 1:
53        parser.print_help()
54        sys.exit(1)
55 
56    input_name = args[0]
57    if input_name.isdigit():
58        capture = cv.CreateCameraCapture(int(input_name))
59    else:
60        capture = None
61 
62    cv.NamedWindow("video"1)
63 
64    #size of the video
65    width = 160
66    height = 120
67 
68    if width is None:
69        width = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH))
70    else:
71        cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,width)
72 
73    if height is None:
74    height = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))
75    else:
76    cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,height)
77 
78    if capture:
79        frame_copy = None
80        while True:
81 
82            frame = cv.QueryFrame(capture)
83            if not frame:
84                cv.WaitKey(0)
85                break
86            if not frame_copy:
87                frame_copy =cv.CreateImage((frame.width,frame.height),
88                                            cv.IPL_DEPTH_8U, frame.nChannels)
89 
90            if frame.origin == cv.IPL_ORIGIN_TL:
91                cv.Copy(frame, frame_copy)
92            else:
93                cv.Flip(frame, frame_copy, 0)
94 
95            detect_and_draw(frame_copy, cascade)
96 
97            if cv.WaitKey(10) >= 0:
98                break
99    else:
100        image = cv.LoadImage(input_name, 1)
101        detect_and_draw(image, cascade)
102        cv.WaitKey(0)
103 
104    cv.DestroyWindow("video")
To run this program, type in this command in your VNC Viewer’s terminal:
python facedetect.py --cascade=face.xml 0
The number at the end represents the number of your video device.

2 comments:

  1. Hi sir,

    I got error from my raspi. It showed
    HIGHGUI ERROR: V4L/V4L2: VIDIOC_CROPCAP
    /dev/video does not support memory mapping
    VIDIOC_QBUF: Bad file descriptor
    ....

    By the way I am using raspi camera and usb camera. Same error.

    ReplyDelete
    Replies
    1. have u got answer for that ...... run successfully ...?

      Delete