face recognition with opencv and python

asked 2015-05-22 07:45:30 -0600

GalileoUser gravatar image

updated 2015-05-22 07:52:30 -0600

berak gravatar image

I'm trying to use the code showed here http://answers.opencv.org/answers/105... to do face recognition.

I have two folders, images and resultado, inside images I have folders person1 and person2, inside them I have pictures.

  • first question: can the type of my image data be .jpg?
  • second question: in this line [X,y] = read_images(path=sys.argv[1],sz=(70,70)) what is sys.argv[1]? Should I replace it by "images" because my data is there? When I try to run the program I find the error:

    File "facerec_demo.py", line 103 [X,y] = read_images(path=sys.argv[1],sz=(70,70)) ^ IndentationError: unexpected indent

  • third question: I want my program take a image and compare with the data. Do this line do that?cv2.imwrite("test.png", X[0]).

The code is as follows:

#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Philipp Wagner <bytefish[at]gmx[dot]de>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#  * Neither the name of the author nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.


import os
import sys
import cv2
import numpy as np

def normalize(X, low, high, dtype=None):
    """Normalizes a given array in X to a value between low and high."""
    X = np.asarray(X)
    minX, maxX = np.min(X), np.max(X)
    # normalize to [0...1].    
    X = X - float(minX)
    X = X / float((maxX - minX))
    # scale to [low...high].
    X = X * (high-low)
    X = X + low
    if dtype is None:
        return np.asarray(X)
    return np.asarray(X, dtype=dtype)


def read_images(path, sz=None):
    """Reads the images in a given folder, resizes images on the fly if size is given.

    Args:
        path: Path to a folder with subfolders representing the subjects (persons).
        sz: A tuple with the size Resizes 

    Returns:
        A list [X,y]

            X ...
(more)
edit retag flag offensive close merge delete

Comments

1:) yes, but rather avoid using jpeg at all (compression artefacts)

2:) sys.argv[1] is the 1st arg given to your program if you run it from cmdline (the folder, where your images are)

since phillip probably never called anything 'resultado', i'm sure, you typed around in that code a bit already. the indentation error is probably due to mixing tabs and spaces, so check that, wherever you changed something.

3:). cv2.imwrite("test.png", X[0]). just saves an image. the actual prediction is done in :

[p_label, p_confidence] = model.predict(np.asarray(X[0]))

also note, that this demo just uses the 1st image from the folder for testing, in real world you would have a separate img for testing (e.g. from a webcam)

berak gravatar imageberak ( 2015-05-22 09:20:24 -0600 )edit

1) opencv tutorial suggest to use pgm, then I need to convert my pictures to this format, right? 2) I'm running my program from ssh terminal on my macbook. Should I not replace the sys.argv[1] by the name of the folder where the images are? (in this case its name is 'images'), since it's an atribute of the function 'read_images'. 'resultado' is a folder where I want to save the picture after all process. In the original code phillip wrote

if __name__ == "__main__":
   # This is where we write the images, if an output_dir is given
   # in command line:
   out_dir = None
   # You'll need at least a path to your image data
GalileoUser gravatar imageGalileoUser ( 2015-05-23 22:20:13 -0600 )edit

so my program facerec_demo.py is the the folder 'root' and inside this folder I have other two folders 'images' and 'resultados'. Inside 'images' I have other two folders, 'person1' and 'person2' where the images really are, so I thought I needed to change 'None' to 'resultado', but when I do that the program says resultado isn't defined

File "facerec_demo.py", line 58, in <module>
    out_dir = resultado
NameError: name 'resultado' is not defined

but when I leave None it prints USAGE: facerec_demo.py </images> [</resultado>]

it means the program ends in the 'if'

if len(sys.argv) < 2: print "USAGE: facerec_demo.py </images> [</resultado>]" sys.exit()

what does mean len(sys.argv) < 2?

Oh ok, so it save the images as teste.png.

GalileoUser gravatar imageGalileoUser ( 2015-05-23 22:27:10 -0600 )edit

Then you said the program uses the 1st image from the folder for testing, which folder? root or the 1st image in the person1 folder (which is inside the folder images), that are actually my data? If it happens so, what do I need to change in the program to make it to user the image captured01.jpg inside root folder, which was taken by a webcam?

GalileoUser gravatar imageGalileoUser ( 2015-05-23 22:32:46 -0600 )edit

Hi Berak, are you still there?

GalileoUser gravatar imageGalileoUser ( 2015-05-25 09:37:33 -0600 )edit
  • give it the 'root' folder. this should contain a dir for each person
  • then run the training, model.train(np.asarray(X), np.asarray(y))
  • if you want to test with images from webcam,
    • use a CascadeClassifier to find the face region
    • resize that region to the same size of your train-images
    • use the result with [p_label, p_confidence] = model.predict(img)

(again you have to hack it into your desired shape, be bold and fearless ;)

berak gravatar imageberak ( 2015-05-25 10:12:07 -0600 )edit