0

I am trying to achieve emotion detection using opencv2. However when I run the python script it would have this error:

In 1: runfile('C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py', wdir='C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master')

usage: EmoDetect.py [-h] [-i I [I ...]]

optional arguments:

-h, --help show this help message and exit

-i I [I ...] Enter the filenames with extention of an Image

Initializing Dlib face Detector..

Loading landmark identification data...

Unable to find trained facial shape predictor.

You can download a trained facial shape predictor from:

http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2

Loading trained data.....

Unable to load trained data.

Make sure that traindata.pkl and pcadata.pkl are in the current directory

Traceback (most recent call last):

File "", line 1, in

runfile('C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py',

wdir='C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master')

File "C:\Users\Belay Mendez\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile

execfile(filename, namespace)

File "C:\Users\Belay Mendez\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile

exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Belay Mendez/Desktop/SIGNLAB PROJECT/face-expression-detect-master/EmoDetect.py", line 105, in

for filename in arg.i:

TypeError: 'NoneType' object is not iterable

TypeError: 'NoneType' object is not iterable

It would then crash the kernel and is unable to start it and then leads to this:

libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data
libpng warning: Image width is zero in IHDR
libpng warning: Image height is zero in IHDR
libpng error: Invalid IHDR data

I don't know what is wrong, here is our codes below:

import argparse,sys

try:
    from FeatureGen import*
except ImportError:
    print ("Make sure FeatureGen.pyc file is in the current directory")
    exit()

try:
    import dlib
    from skimage import io
    import numpy
    import cv2
    from sklearn.externals import joblib
except ImportError:
        print ("Make sure you have OpenCV, dLib, scikit learn and skimage libraries properly installed")
        exit()

emotions={ 1:"Anger", 2:"Contempt", 3:"Disgust", 4:"Fear", 5:"Happy", 6:"Sadness", 7:"Surprise"}

def Predict_Emotion(filename):

    print ("Opening image....")
    try:
        img=io.imread(filename)
        cvimg=cv2.imread(filename)
    except:
        print ("Exception: File Not found.")
        return

    win.clear_overlay()
    win.set_image(img)

    dets=detector(img,1)

    if len(dets)==0:
        print ("Unable to find any face.")
        return

    for k,d in enumerate(dets):

        shape=predictor(img,d)
        landmarks=[]
        for i in range(68):
            landmarks.append(shape.part(i).x)
            landmarks.append(shape.part(i).y)


        landmarks=numpy.array(landmarks)

        print ("Generating features......")
        features=generateFeatures(landmarks)
        features= numpy.asarray(features)

        print ("Performing PCA Transform.......")
        pca_features=pca.transform(features)

        print ("Predicting using trained model........")
        emo_predicts=classify.predict(pca_features)
        print ("Predicted emotion using trained data is { " + emotions[int(emo_predicts[0])] + " }")
        print ("")

        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(cvimg,emotions[int(emo_predicts[0])],(20,20), font, 1,(0,255,255),2)

        win.add_overlay(shape)

    cv2.namedWindow("Output")
    cv2.imshow("Output",cvimg)
    cv2.waitKey(0)


if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('-i', type=str, nargs='+', help="Enter the filenames with extention of an Image")
    arg=parser.parse_args()

    if not len(sys.argv) > 1:
        parser.print_help()
        exit()

    landmark_path="shape_predictor_68_face_landmarks.dat"

    print ("Initializing Dlib face Detector..")
    detector= dlib.get_frontal_face_detector()

    print ("Loading landmark identification data...")
    try:
        predictor= dlib.shape_predictor(landmark_path)
    except:
        print ("Unable to find trained facial shape predictor. \nYou can download a trained facial shape predictor from: \nhttp://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2")
        exit()


    win=dlib.image_window()

    print ("Loading trained data.....")

    try:
        classify=joblib.load("traindata.pkl")
        pca=joblib.load("pcadata.pkl")
    except:
        print ("Unable to load trained data. \nMake sure that traindata.pkl and pcadata.pkl are in the current directory")
        exit()

    for filename in arg.i:
        Predict_Emotion(filename)

I do not know why it does not perform the same as the video I copied it from which is this: Face Expression Recognition using python The files needed for the code is also here face-expression prediction using python. Last, it also crashes the kernel.

Your help will be appreciated.

Isabela
  • 1
  • 2
  • 1
    It seems that your input image file path is invalid. Inside `for filename in arg.i:` use `print file_name` to see if it prints a valid image file path. – ZdaR Apr 02 '18 at 05:47
  • Can you post the entire stack frame, not just the error? It should show the exact line causing the problem so we don't have to search through your code and guess. – tdelaney Apr 02 '18 at 05:51
  • @ZdaR I am unable to test it because it crashes the kernel. :( – Isabela Apr 02 '18 at 05:51
  • @tdelaney I already edited and displayed the error that is contained in the html file. – Isabela Apr 02 '18 at 05:57
  • Then try with commenting `Predict_Emotion(filename)` – ZdaR Apr 02 '18 at 06:12
  • I am puzzled. `if not len(sys.argv) > 1:` prints the help text but the `exit()` doesn't exit. It should have terminated because there wasn't a `-i` argument. Any chance you are running an old version of the code that didn't call exit? Or perhaps there is morre code and its defined `def exit()` ?? – tdelaney Apr 02 '18 at 06:12
  • As an aside, argparse considers `-` and `--` options to be optional. One could argue that you should just list the file names and not use `-i` at all (and then argparse would do the exit for you). But if you prefer keeping the mandatory option `-i`, you can check it with `if arg.i is None:` instead of `if len(sys.argv) > 1`. If you add another option later, it will still work while your current solution will break. – tdelaney Apr 02 '18 at 06:16
  • You could `import builtins` and then change `exit()` to `builtins.exit()`. If that works then you know that somebody has redefined that function. then have a chat with that person... – tdelaney Apr 02 '18 at 06:27

0 Answers0