If you have grayscale images given to you in CSV format (from kaggle), it is very easy to dump the images into numpy and then directly pass the numpy array to openCV to detect faces, eye, mouth or whatever using the haar cascades. The tutorial in opencv website http://docs.opencv.org/trunk/doc/py_tutorials/py_objdetect/py_face_detection/py_face_detection.html only shows the example of color images not the grayscale.

facedetect 3

1. First install the opencv in your computer along with python

sudo apt-get install python-opencv

or in mac you can install opencv using brew

2. Locate the haar cascades xml files installed in your computer. Usually in /usr/share/opencv/haarcascade in ubuntu

pbu@pbu-OptiPlex-740-Enhanced:~/Desktop$ ls /usr/share/opencv/haarcascades
haarcascade_eye_tree_eyeglasses.xml 
haarcascade_lowerbody.xml 
haarcascade_mcs_righteye.xml
haarcascade_eye.xml 
haarcascade_mcs_eyepair_big.xml 
haarcascade_mcs_upperbody.xml
haarcascade_frontalface_alt2.xml 
haarcascade_mcs_eyepair_small.xml 
haarcascade_profileface.xml
haarcascade_frontalface_alt_tree.xml 
haarcascade_mcs_leftear.xml 
haarcascade_righteye_2splits.xml
haarcascade_frontalface_alt.xml 
haarcascade_mcs_lefteye.xml 
haarcascade_smile.xml
haarcascade_frontalface_default.xml 
haarcascade_mcs_mouth.xml 
haarcascade_upperbody.xml
haarcascade_fullbody.xml 
haarcascade_mcs_nose.xml
haarcascade_lefteye_2splits.xml 
haarcascade_mcs_rightear.xml

3. Write a python script which imports into numpy array and then we pass on to opencv. Remember for grayscale images it must be uint8 to work properly.

import cv2
from math import sin, cos, radians
import pandas as pd
import numpy as np
import matplotlib.pyplot as pl

df = pd.read_csv('training.csv',header=0)

df['Image'] = df['Image'].apply(lambda im: np.fromstring(im, sep=' ') )
X = np.vstack (df['Image'].values)
X = X.astype(np.uint8)
X = X.reshape(-1,96,96)

face = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_mcs_mouth.xml")

# Lets run face detect for 10 images from set 200-210
for k in xrange(200,210):
img = X[k]
detected = face.detectMultiScale(img,1.3,1)
print detected

for (x,y,w,h) in detected:
cv2.rectangle(img,(x,y),(x+w,y+h),(200,0,0),2)

cv2.imshow('facedetect', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Final output you will see rectangles drawn on detected grayscale images.