[
  {
    "path": "Confusion_matrix.py",
    "content": "\n# coding: utf-8\n\n# In[3]:\n\nimport cPickle as pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import svm, datasets\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\npath = '/Users/soledad/Box Sync/Fall 15/I590 - Collective Intelligence/CV Project/Code/svmethnicity/'\nf = open(path+ '8svm.pkl', 'rb')\nsvm = pickle.load(f)\nf.close()\n\n\ntrain_set = np.load(path + '8train_set.pkl')\ntest_set = np.load(path + '8test_set.pkl')\n\nlabels_train=np.load(path + '8labels_train.pkl')\nlabels_test=np.load(path + '8labels_test.pkl')\n\npredicted = svm.predict(test_set) \n\n\n# In[ ]:\n\nnames=['Happiness','Suprise', 'Sadness', 'Disgust', 'Fear', 'Anger']\n\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(names))\n    plt.xticks(tick_marks, names, rotation=45)\n    plt.yticks(tick_marks, names)\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\ncm = confusion_matrix(labels_test, predicted)\nnp.set_printoptions(precision=2)\nprint('Confusion matrix, without normalization')\nprint(cm)\nplt.figure()\nplot_confusion_matrix(cm)\n\n\ncm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\nprint('Normalized confusion matrix')\nprint(cm_normalized)\nplt.figure()\nplot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')\n\nplt.show()\n\n\n# In[5]:\n\nlabels_test\n\n\n# In[ ]:\n\n\n\n\n# In[6]:\n\nplt.show()\n\n\n# In[ ]:\n\n\n\n"
  },
  {
    "path": "README.md",
    "content": "# Emotion-Detection-in-Videos\nThe aim of this work is to recognize the six emotions (happiness, sadness, disgust, surprise, fear and anger) based on human facial expressions extracted from videos. To achieve this, we are considering people of different ethnicity, age and gender where each one of them reacts very different when they express their emotions. We collected a data set of 149 videos that included short videos from both, females and males, expressing each of the the emotions described before. The data set was built by students and each of them recorded a video expressing all the emotions with no directions or instructions at all.  Some videos included more body parts than others. In other cases, videos have objects in the background an even different light setups. We wanted this to be as general as possible with no restrictions at all, so it could be a very good indicator of our main goal.   The code detect_faces.py just detects faces from the video and we saved this video in the dimension 240x320. Using this algorithm creates shaky videos. Thus we then stabilized all videos. This can be done via a code or online free stabilizers are also available. After which we used the stabilized videos and ran it through code emotion_classification_videos_faces.py. in the code we developed a method to extract features based on histogram of dense optical flows (HOF) and we used a support vector machine (SVM) classifier to tackle the recognition problem.   For each video at each frame we extracted optical flows. Optical flows measure the motion relative to an observer between two frames at each point of them. Therefore, at each point in the image you will have two values that describes the vector representing the motion between the two frames: the magnitude and the angle. In our case, since videos have a resolution of 240x320, each frame will have a feature descriptor of dimensions 240x320x2. So, the final video descriptor will have a dimension of #framesx240x320x2. In order to make a video comparable to other inputs (because inputs of different length will not be comparable with each other), we need to somehow find a way to summarize the video into a single descriptor. We achieve this by calculating a histogram of the optical flows. This is, separate the extracted flows into categories and count the number of flows for each category. In more details, we split the scene into a grid of s by s bins (10 in this case) in order to record the location of each feature, and then categorized the direction of the flow as one of the 8 different motion directions considered in this problem. After this, we count for each direction the number of flows occurring in each direction bin. Finally, we end up with an s by s by 8 bins descriptor per each frame. Now, the summarizing step for each video could be the average of the histograms in each grid (average pooling method) or we could just pick the maximum value of the histograms by grid throughout all the frames on a video (max pooling   For the classification process, we used support vector machine (SVM) with a non linear kernel classifier, discussed in class, to recognize the new facial expressions. We also considered a Naïve Bayes classifier, but it is widely known that svm outperforms the last method in the computer vision field. A confusion matrix can be made to plot results better. \n\nThe aim of this work is to recognize the six emotions (happiness, sadness, disgust, surprise, fear and anger) based on human facial expressions extracted from videos. To achieve this, we are considering people of different ethnicity, age and gender where each one of them reacts very different when they express their emotions. We collected a data set of 149 videos that included short videos from both, females and males, expressing each of the the emotions described before. The data set was built by students and each of them recorded a video expressing all the emotions with no directions or instructions at all.  Some videos included more body parts than others. In other cases, videos have objects in the background an even different light setups. We wanted this to be as general as possible with no restrictions at all, so it could be a very good indicator of our main goal. \n\nThe code detect_faces.py just detects faces from the video and we saved this video in the dimension 240x320. Using this algorithm creates shaky videos. Thus we then stabilized all videos. This can be done via a code or online free stabilizers are also available. After which we used the stabilized videos and ran it through code emotion_classification_videos_faces.py. in the code we developed a method to extract features based on histogram of dense optical flows (HOF) and we used a support vector machine (SVM) classifier to tackle the recognition problem. \n\nFor each video at each frame we extracted optical flows. Optical flows measure the motion relative to an observer between two frames at each point of them. Therefore, at each point in the image you will have two values that describes the vector representing the motion between the two frames: the magnitude and the angle. In our case, since videos have a resolution of 240x320, each frame will have a feature descriptor of dimensions 240x320x2. So, the final video descriptor will have a dimension of #framesx240x320x2. In order to make a video comparable to other inputs (because inputs of different length will not be comparable with each other), we need to somehow find a way to summarize the video into a single descriptor. We achieve this by calculating a histogram of the optical flows. This is, separate the extracted flows into categories and count the number of flows for each category. In more details, we split the scene into a grid of s by s bins (10 in this case) in order to record the location of each feature, and then categorized the direction of the flow as one of the 8 different motion directions considered in this problem. After this, we count for each direction the number of flows occurring in each direction bin. Finally, we end up with an s by s by 8 bins descriptor per each frame. Now, the summarizing step for each video could be the average of the histograms in each grid (average pooling method) or we could just pick the maximum value of the histograms by grid throughout all the frames on a video (max pooling \n\nFor the classification process, we used support vector machine (SVM) with a non linear kernel classifier, discussed in class, to recognize the new facial expressions. We also considered a Naïve Bayes classifier, but it is widely known that svm outperforms the last method in the computer vision field. A confusion matrix can be made to plot results better. \n"
  },
  {
    "path": "detect_faces.py",
    "content": "#!/usr/bin/env python\n\nimport numpy as np\nimport cv2\nimport ntpath\nimport glob\n\n# local modules\nfrom video import create_capture\nfrom common import clock, draw_str\n\n\nhelp_message = '''\nUSAGE: facedetect.py [--cascade <cascade_fn>] [--nested-cascade <nested_fn>] [<video_source>]\n'''\n\ndef detect(img, cascade):\n    rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)\n    if len(rects) == 0:\n        return []\n    rects[:,2:] += rects[:,:2]\n    return rects\n\ndef draw_rects(img, rects, color):\n    for x1, y1, x2, y2 in rects:\n        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)\n\nif __name__ == '__main__':\n    import sys, getopt\n    print help_message\n    samples = 30\n    \n    path = '/Users/dhvanikotak/Box Sync/x'\n    files = glob.glob(path+ \"/*.mov\")\n    \n    for fn in files:   \n\n        print fn\n        args, video_src = getopt.getopt(fn, '', ['cascade=', 'nested-cascade='])\n        args = dict(args)\n        cascade_fn = args.get('--cascade', \"../../data/haarcascades/haarcascade_frontalface_alt2.xml\")\n        nested_fn  = args.get('--nested-cascade', \"../../data/haarcascades/haarcascade_eye.xml\")\n    \n        cascade = cv2.CascadeClassifier(cascade_fn)\n        nested = cv2.CascadeClassifier(nested_fn)\n    \n        cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')\n        fps = cam.get(5)\n        print fps\n    \n        #         w=int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH ))\n        # h =int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT ))\n        # #  video recorder\n        # f ourcc = cv2.cv.CV_FOURCC(*'XVID')  # cv2.VideoWriter_fourcc() does not exist\n        # v ideo_writer = cv2.VideoWriter(\"output.mov\", fourcc, 25, (w, h))\n    \n        # fourcc = cv2.VideoWriter_fourcc(*'MOV')\n        fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n    \n        name = ntpath.basename(fn)  \n        out = cv2.VideoWriter('face_' + name , fourcc, fps, (240,320), True)\n    \n        while True:\n            ret, img = cam.read()\n            if not ret : break\n            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n            gray = cv2.equalizeHist(gray)       \n            t = clock()\n            rects = detect(gray, cascade)\n            \n            vis = img.copy()\n            # draw_rects(vis, rects, (0, 255, 0))       \n            if not nested.empty():\n                \n                for x1, y1, x2, y2 in rects:\n                    roi = gray[y1:y2, x1:x2]\n                    vis_roi = vis[y1:y2, x1:x2]\n                    # subrects = detect(roi.copy(), nested)\n                    # draw_rects(vis_roi, subrects, (255, 0, 0))\n                    res = cv2.resize(vis_roi,(240, 320), interpolation = cv2.INTER_CUBIC)       \n                    cv2.imshow('facedetect', res)\n                    out.write(res)\n\n\n        out.release()\n\n        cv2.destroyAllWindows()\n\n    \n        # if 0xFF & cv2.waitKey(5) == 27: break   \n\n\n\n            \n"
  },
  {
    "path": "emotion_classification_videos_faces.py",
    "content": "\n# coding: utf-8\n\n# In[3]:\n\nimport numpy as np\nimport cv2\nimport glob\nfrom random import shuffle\nfrom sklearn import svm\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import MultinomialNB\nimport datetime\n\n\ndef split_data(data, percentaje):    \n    \n    shuffle(data)\n    train_n = int(percentaje*len(data))\n    train, test = np.split(data, [train_n])\n\n    s_train = zip(*train)\n    s_test = zip(*test)\n    \n    samples_train = list(s_train[0])\n    labels_train = list(s_train[1])\n\n    samples_test = list(s_test[0])\n    labels_test = list(s_test[1])\n    \n    return samples_train, labels_train, samples_test, labels_test\n\n\ndef draw_flow(img, flow, step=16):\n\n    h, w = img.shape[:2]\n    y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1)\n    fx, fy = flow[y,x].T\n    lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)\n    lines = np.int32(lines + 0.5)\n    vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n    cv2.polylines(vis, lines, 0, (0, 255, 0))\n    for (x1, y1), (x2, y2) in lines:\n        cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)\n    return vis\n\n\ndef calc_hist(flow):\n\n    mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1], angleInDegrees = 1)\n    \n    q1 = ((0 < ang) & (ang <= 45)).sum()\n    q2 = ((45 < ang) & (ang <= 90)).sum()\n    q3 = ((90 < ang) & (ang <= 135)).sum()\n    q4 = ((135 < ang) & (ang <= 180)).sum()\n    q5 = ((180 < ang) & (ang <= 225)).sum()\n    q6 = ((225 <= ang) & (ang <= 270)).sum()\n    q7 = ((270 < ang) & (ang <= 315)).sum()\n    q8 = ((315 < ang) & (ang <= 360)).sum()\n    \n    hist = [q1, q2, q3, q4 ,q5, q6, q7 ,q8]\n    \n    return (hist)\n\n\ndef process_video(fn, samples):\n\n    video_hist = []\n    hog_list = []\n    sum_desc = []\n    bins_n = 10\n\n    cap = cv2.VideoCapture(fn)\n    ret, prev = cap.read()\n            \n    prevgray = cv2.cvtColor(prev,cv2.COLOR_BGR2GRAY)\n    hog = cv2.HOGDescriptor()\n\n\n    while True:\n           \n        ret, img = cap.read()\n        \n        if not ret : break\n        \n        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n        flow = cv2.calcOpticalFlowFarneback(prevgray,gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n        \n        prevgray = gray\n\n        bins = np.hsplit(flow, bins_n)\n\n        out_bins = []\n        for b in bins:\n            out_bins.append(np.vsplit(b, bins_n))\n\n        frame_hist = []\n        for col in out_bins:\n\n            for block in col:\n                frame_hist.append(calc_hist(block))\n                                 \n        video_hist.append(np.matrix(frame_hist) )\n\n    # average per frame\n    sum_desc = video_hist[0]\n    for i in range(1, len(video_hist)):\n        sum_desc = sum_desc + video_hist[i] \n    \n    ave = sum_desc / len(video_hist)\n\n    # max per bin\n    maxx = np.amax(video_hist, 0)\n    maxx = np.matrix(maxx)\n    \n    fn = fn.lower()\n\n    if '_ha_' in fn: label = 1\n    if '_su_' in fn: label = 2\n    if '_sa_' in fn: label = 3\n    if '_di_' in fn: label = 4\n    if '_fe_' in fn: label = 5\n    if '_an_' in fn: label = 6\n            \n    print label\n    ave_desc = np.asarray(ave)\n    a_desc = []\n    a_desc.append(np.asarray(ave_desc, dtype = np.uint8).ravel())\n\n    max_desc = np.asarray(maxx)\n    m_desc = []\n    m_desc = np.asarray(max_desc, dtype = np.uint8).ravel()\n\n    return a_desc, label, m_desc\n\n\n# In[4]:\n\nif __name__ == '__main__':\n        \n    path = '/Users/dhvanikotak/Box Sync/CV Project/240x320/'\n   # path = '/Users/soledad/Box Sync/Fall 15/I590 - Collective Intelligence/CV Project/240x320/'\n    \n#     folders = glob.glob(path+ \"/*\")\n    folders = [path + 'Angry2', path + 'Surprised2', path + 'Disgusted2',\n               path + 'Fear2', path + 'Sad2', path + 'Happy2']\n    \n    happy_data = []\n    sad_data = []\n    disgust_data = []\n    fear_data = []\n    surprise_data = []\n    angry_data = []\n\n    samples = 30\n    a = datetime.datetime.now()\n    for act in folders:\n            fileList = glob.glob(act + \"/*.mov\")  \n            print(len(fileList))\n\n            for f in fileList:\n                f = f.lower()\n                print f\n    \n                if 'ha' in f:\n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        happy_data.append([video_desc[0], label, maxx])\n                    \n                if 'sa' in f:\n                      \n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        sad_data.append([video_desc[0], label, maxx])\n                \n                if 'di' in f:\n                       \n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        disgust_data.append([video_desc[0], label, maxx])\n        \n                if 'fe' in f:\n                        \n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        fear_data.append([video_desc[0], label, maxx])\n        \n                if 'su' in f:\n                       \n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        surprise_data.append([video_desc[0], label, maxx])\n        \n                if 'an' in f:\n                        \n                    video_desc, label, maxx = process_video(f, samples)\n                \n                    if (label) != 0 :\n                        angry_data.append([video_desc[0], label, maxx])\n                            \n\n    b = datetime.datetime.now()\n    \n    print (b-a)\n\n\n# In[2]:\n\nimport cPickle\npercentaje = 0.7\n\nclf = svm.SVC(kernel = 'rbf', C = 10, gamma = 0.0000001)\n\ngnb = GaussianNB()\nmnb = MultinomialNB()\n\nsvm = 0\nnb1 = 0\nnb2 = 0\n\n# all_data = happy_data + sad_data + fear_data + surprise_data + disgust_data + angry_data\n     \ntimes = 10\n\nfor i in range(0,times):\n    # happiness\n    happy_samples_train = []\n    happy_labels_train = []\n    happy_samples_test = []\n    happy_labels_test = []\n    if len(happy_data) > 0:\n        happy_samples_train, happy_labels_train, happy_samples_test, happy_labels_test = split_data(happy_data, percentaje)\n      \n    # sadness\n    sad_samples_train = []\n    sad_labels_train = []\n    sad_samples_test = []\n    sad_labels_test = []\n    if len(sad_data) > 0:\n        sad_samples_train, sad_labels_train, sad_samples_test, sad_labels_test = split_data(sad_data, percentaje)\n   \n    # fear\n    fear_samples_train = []\n    fear_labels_train = []\n    fear_samples_test = []\n    fear_labels_test = []\n    if len(fear_data) > 0:\n        fear_samples_train, fear_labels_train, fear_samples_test, fear_labels_test = split_data(fear_data, percentaje)\n    \n    # surprise\n    surprise_samples_train = []\n    surprise_labels_train = []\n    surprise_samples_test = []\n    surprise_labels_test = []\n    if len(surprise_data) > 0:\n        surprise_samples_train, surprise_labels_train, surprise_samples_test, surprise_labels_test = split_data(surprise_data, percentaje)\n  \n    # disgust\n    disgust_samples_train = []\n    disgust_labels_train = []\n    disgust_samples_test = []\n    disgust_labels_test = []\n    if len(disgust_data) > 0:\n        disgust_samples_train, disgust_labels_train, disgust_samples_test, disgust_labels_test = split_data(disgust_data, percentaje)\n    \n    # angrer\n    angry_samples_train = []\n    angry_labels_train = []\n    angry_samples_test = []\n    angry_labels_test = []\n    if len(angry_data) > 0:\n        angry_samples_train, angry_labels_train, angry_samples_test, angry_labels_test = split_data(angry_data, percentaje)\n    \n   \n    \n    train_set = happy_samples_train + sad_samples_train + fear_samples_train + surprise_samples_train + disgust_samples_train + angry_samples_train\n    test_set = happy_samples_test + sad_samples_test + fear_samples_test + surprise_samples_test + disgust_samples_test + angry_samples_test\n    labels_train = happy_labels_train + sad_labels_train + fear_labels_train + surprise_labels_train + disgust_labels_train + angry_labels_train\n    labels_test = happy_labels_test + sad_labels_test + fear_labels_test + surprise_labels_test + disgust_labels_test + angry_labels_test \n     \n\n    # train_set, labels_train, test_set, labels_test = split_data(all_data, percentaje)    \n\n    clf.fit(train_set, labels_train)\n    gnb.fit(train_set, labels_train)\n    mnb.fit(train_set, labels_train)\n    \n    y_pred_g = gnb.predict(test_set)\n    y_pred_m = mnb.predict(test_set)\n    predicted = clf.predict(test_set) \n    \n    err1 = (labels_test == predicted).mean()\n    err2 = (labels_test == y_pred_g).mean()\n    err3 = (labels_test == y_pred_m).mean()\n        \n    print 'accuracy svm: %.2f %%' % (err1*100), 'accuracy gnb: %.2f %%' % (err2*100), 'accuracy mnb: %.2f %%' % (err3*100)\n\n#     folder = '/Users/soledad/Box Sync/Fall 15/I590 - Collective Intelligence/CV Project/Code/Emotion_Out/'\n\n    folder = '/Users/dhvanikotak/Box Sync/CV Project/Code/Emotion_Out/'\n\n    outfile = open(folder + str(i)+'train_set.pkl', 'wb')\n    np.save(outfile, train_set)\n    outfile.close()\n    \n    outfile = open(folder + str(i)+'test_set.pkl', 'wb')\n    np.save(outfile, test_set)\n    outfile.close()\n    \n    outfile = open(folder + str(i)+'labels_train.pkl', 'wb')\n    np.save(outfile, labels_train)\n    outfile.close()\n    \n    outfile = open(folder + str(i)+'labels_test.pkl', 'wb')\n    np.save(outfile, labels_test)\n    outfile.close()\n\n    # save the classifier\n    with open(folder + str(i)+'svm.pkl', 'wb') as fid:\n        cPickle.dump(clf, fid)  \n    fid.close()\n    \n    with open(folder + str(i)+'mnb.pkl', 'wb') as fid:\n        cPickle.dump(mnb, fid)  \n    fid.close()\n    \n    with open(folder + str(i)+'gnb.pkl', 'wb') as fid:\n        cPickle.dump(gnb, fid)  \n    fid.close()\n    \n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n"
  }
]