summaryrefslogtreecommitdiff
path: root/megapixels/notebooks/face_analysis/beauty.ipynb
blob: d5da1cb2f20fdb0a85342b2c3fec355f6ace4460 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from os.path import join\n",
    "import os.path as osp\n",
    "import cv2\n",
    "import numpy as np\n",
    "from PIL import Image, ImageDraw\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import math\n",
    "import dlib\n",
    "from pathlib import Path\n",
    "%reload_ext autoreload\n",
    "%autoreload 2\n",
    "#from utils import imx # Image function extensions\n",
    "#from config import config as cfg\n",
    "\n",
    "import sys\n",
    "sys.path.append('/work/megapixels_dev/megapixels/')\n",
    "from app.settings import app_cfg as cfg\n",
    "from app.utils import im_utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import Conv2D, Input, MaxPool2D,Flatten, Dense, Permute, GlobalAveragePooling2D\n",
    "from keras.models import Model\n",
    "from keras.optimizers import adam\n",
    "import numpy as np\n",
    "import pickle\n",
    "import keras\n",
    "import cv2\n",
    "import sys\n",
    "import dlib\n",
    "import os.path\n",
    "from keras.models import Sequential\n",
    "from keras.applications.resnet50 import ResNet50\n",
    "#from keras.applications.resnet50 import Dense\n",
    "from keras.layers import Dense\n",
    "from keras.optimizers import Adam\n",
    "import pickle\n",
    "import numpy as np\n",
    "import cv2\n",
    "import os\n",
    "from keras.layers import Dropout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#model_path = parent_path+\"/common/mmod_human_face_detector.dat\"\n",
    "model_path = '/data_store_hdd/apps/megapixels/models/dlib/mmod_human_face_detector.dat'\n",
    "#cnn_face_detector = dlib.cnn_face_detection_model_v1(model_path)\n",
    "cnn_face_detector = dlib.get_frontal_face_detector()\n",
    "\n",
    "resnet = ResNet50(include_top=False, pooling='avg')\n",
    "model = Sequential()\n",
    "model.add(resnet)\n",
    "model.add(Dense(5, activation='softmax'))\n",
    "model.layers[0].trainable = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fp_model = join(cfg.DIR_MODELS, 'keras', 'model-ldl-resnet.h5')\n",
    "print(fp_model)\n",
    "model.load_weights(fp_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def score_mapping(modelScore):\n",
    "\n",
    "    if modelScore <= 1.9:\n",
    "        mappingScore = ((4 - 2.5) / (1.9 - 1.0)) * (modelScore-1.0) + 2.5\n",
    "    elif modelScore <= 2.8:\n",
    "        mappingScore = ((5.5 - 4) / (2.8 - 1.9)) * (modelScore-1.9) + 4\n",
    "    elif modelScore <= 3.4:\n",
    "        mappingScore = ((6.5 - 5.5) / (3.4 - 2.8)) * (modelScore-2.8) + 5.5\n",
    "    elif modelScore <= 4:\n",
    "        mappingScore = ((8 - 6.5) / (4 - 3.4)) * (modelScore-3.4) + 6.5\n",
    "    elif modelScore < 5:\n",
    "        mappingScore = ((9 - 8) / (5 - 4)) * (modelScore-4) + 8\n",
    "\n",
    "    return mappingScore\n",
    "\n",
    "def beauty_predict(fp_im):\n",
    "    im = cv2.imread(fp_im)\n",
    "\n",
    "    if im.shape[0] > 1280:\n",
    "      new_shape = (1280, im.shape[1] * 1280 / im.shape[0])\n",
    "    elif im.shape[1] > 1280:\n",
    "      new_shape = (im.shape[0] * 1280 / im.shape[1], 1280)\n",
    "    elif im.shape[0] < 640 or im0.shape[1] < 640:\n",
    "      new_shape = (im.shape[0] * 2, im.shape[1] * 2)\n",
    "    else:\n",
    "      new_shape = im.shape[0:2]\n",
    "\n",
    "    im = cv2.resize(im, (int(new_shape[1]), int(new_shape[0])))\n",
    "    dets = cnn_face_detector(im, 0)\n",
    "\n",
    "    for i, d in enumerate(dets):\n",
    "      #face = [d.rect.left(), d.rect.top(), d.rect.right(), d.rect.bottom()]\n",
    "      face = [d.left(), d.top(), d.right(), d.bottom()]\n",
    "      croped_im = im[face[1]:face[3], face[0]:face[2], :]\n",
    "      resized_im = cv2.resize(croped_im, (224, 224))\n",
    "      normed_im = np.array([(resized_im - 127.5) / 127.5])\n",
    "\n",
    "      import time\n",
    "      st = time.time()\n",
    "      pred = model.predict(normed_im)\n",
    "      print(f'{(time.time()-st)}ms')\n",
    "      ldList = pred[0]\n",
    "      out = 1 * ldList[0] + 2 * ldList[1] + 3 * ldList[2] + 4 * ldList[3] + 5 * ldList[4]\n",
    "\n",
    "      out = score_mapping(out)\n",
    "\n",
    "      print(Path(fp_im).stem + \"Score:\" + str('%.2f' % (out)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "beauty_predict('/home/adam/Downloads/faces/Arnold_Schwarzenegger_0014.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:megapixels]",
   "language": "python",
   "name": "conda-env-megapixels-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}