| 6 | |
| 7 | # wrapper for openface |
| 8 | class OpenFaceEmbedding: |
| 9 | # constructor |
| 10 | def __init__(self, image_dim, shape_predictor_path, network_path): |
| 11 | print 'shape_predictor_path', shape_predictor_path |
| 12 | print 'network_path', network_path |
| 13 | print 'loading network...', |
| 14 | self.image_dim = image_dim |
| 15 | self.align = openface.AlignDlib(shape_predictor_path) |
| 16 | self.net = openface.TorchNeuralNet(network_path, self.image_dim) |
| 17 | print 'done' |
| 18 | |
| 19 | # this method calculates a real vector which represents the given face image |
| 20 | def embed(self, bgr_image, is_rgb=False): |
| 21 | rgb_image = bgr_image |
| 22 | if not is_rgb: |
| 23 | rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB) |
| 24 | |
| 25 | bb = self.align.getLargestFaceBoundingBox(rgb_image) |
| 26 | # bb = self.align_hueristic(rgb_image) |
| 27 | if bb is None: |
| 28 | if rgb_image.shape[0] > 64: |
| 29 | scale = 0.5 |
| 30 | print 're-try with smaller size', int(rgb_image.shape[0] * scale) |
| 31 | rgb_image = cv2.resize(rgb_image, (int(rgb_image.shape[1] * scale), int(rgb_image.shape[0] * scale))) |
| 32 | return self.embed(rgb_image, True) |
| 33 | print 'warning : failed to obtain face bounding box!!' |
| 34 | return None |
| 35 | print 'warning : use heuristic align!!' |
| 36 | bb = self.align_hueristic(rgb_image) |
| 37 | |
| 38 | aligned = self.align.align(self.image_dim, rgb_image, bb, landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE) |
| 39 | if aligned is None: |
| 40 | print 'warning : failed to align input face!!' |
| 41 | return None |
| 42 | |
| 43 | return self.net.forward(aligned) |
| 44 | |
| 45 | def align_hueristic(self, rgb_image): |
| 46 | top = int(rgb_image.shape[0] * 0.25) |
| 47 | bottom = int(rgb_image.shape[0] * 0.9) |
| 48 | left = int(rgb_image.shape[1] * 0.15) |
| 49 | right = int(rgb_image.shape[1] * 0.85) |
| 50 | return dlib.rectangle(top, left, bottom, right) |
no outgoing calls
no test coverage detected