├── .gitignore ├── LICENSE ├── README.md ├── convert_blazeface.py ├── convert_facemesh.py ├── coreml_models ├── blazeface.mlmodel ├── blazeface_pipeline.mlmodel └── facemesh.mlmodel ├── create_blazeface_coreml_pipeline.py ├── keras_models ├── blazeface_tf.h5 └── facemesh_tf.h5 ├── landmark_contours.txt ├── layers.py ├── live_demo.py ├── results ├── blazeface_out.jpg ├── facemesh_out.jpg └── usain.gif ├── sample.jpg ├── tflite_models ├── face_detection_front.tflite └── face_mesh.tflite └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | **/__pycache__ 2 | **/.DS_Store 3 | *.ipynb_checkpoints 4 | *.tar.gz 5 | *.ipynb 6 | temp* 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Face Mesh - Coreml 2 | 3 | This repository contains the code for converting tflite models of blazeface and facemesh present in the [Mediapipe](https://github.com/google/mediapipe/tree/master/mediapipe/models) library to coreml and tensorflow. Blazeface is intended for realtime face detection while facemesh is used to detect 468-3D facial landmarks. 4 | 5 | ## Requirements 6 | 7 | - tensorflow == 2.2.0 8 | - coremltools == 3.4 9 | - matplotlib 10 | - opencv 11 | - PIL 12 | 13 | ## Blazeface conversion 14 | Run `python convert_blazeface.py` to convert the tflite model of blazeface present in `tflite_models` folder to tensorflow and keras version. Converted models are placed in `keras_models` and `coreml_models` folders. Blazeface accepts inputs of size 128x128x3 and outputs 896 proposals where each proposal contains a bounding box and 6 facial landmarks along with confidence. NMS should be run on the proposal boxes to filter duplicates. Original mediapipe version uses weighted NMS while here normal NMS is used for simplicity. Use [Netron](https://github.com/lutzroeder/netron) to visualize the network from .h5 or .mlmodel file 15 | 16 | ## Blazeface CoreML pipeline 17 | Run `create_blazeface_coreml_pipeline.py` to create a pipeline CoreML model that includes blazeface and NMS in a single mlmodel. This model takes an input image and gives out the bounding boxes and confidence after NMS. 18 | 19 | ## Facemesh conversion 20 | Run `convert_facemesh.py` to convert tflite model of facemesh to CoreML and tensorflow. Facemesh takes an input image of shape 192x192x3 and outputs 468 3-D facial landmarks. 21 | 22 | ## Running on live video 23 | Run `live_demo.py` to take the camera feed and run both the blazeface, facemesh in sequence. Input frame is first fed to blazeface to find the faces present in the image. After this step bounding boxes are slightly adjusted to have some extra space around face region as required by facemesh. These cropped faces are then fed to the facemesh network to find the landmarks. All the conversion between input image space and cropped face are handled in `utils.py` 24 | ![Results](https://github.com/gouthamvgk/facemesh_coreml_tf/blob/master/results/usain.gif) -------------------------------------------------------------------------------- /convert_blazeface.py: -------------------------------------------------------------------------------- 1 | #This file takes the tflite model of blazeface and converts it to coreml, tf format 2 | import tensorflow as tf 3 | import numpy as np 4 | from tensorflow.keras.layers import * 5 | from layers import * 6 | from utils import * 7 | import coremltools 8 | import tfcoreml 9 | from PIL import Image 10 | import cv2 11 | import matplotlib.pyplot as plt 12 | print(tf.__version__) 13 | 14 | tflite_path = "./tflite_models/face_detection_front.tflite" 15 | interpreter = tf.lite.Interpreter(model_path=tflite_path) 16 | interpreter.allocate_tensors() 17 | tf_lite_mapping = {} 18 | for i in interpreter.get_tensor_details(): 19 | if (("ker" in i["name"].lower()) or ("bia" in i["name"].lower())) and not ("dequant" in i["name"].lower()): 20 | tf_lite_mapping[i['name']] = interpreter.get_tensor(i["index"]) 21 | 22 | def create_blazeface(input_shape, grid_8, grid_16, batch_size = 1, pos1=512, pos2=384, data_format="channels_last"): 23 | x_scale = input_shape[1] 24 | y_scale = input_shape[2] 25 | 26 | inp_tensor = Input(shape=input_shape, batch_size=batch_size, name="input_image") 27 | pre_conv_out = Conv2D(filters=24, kernel_size=(5,5), strides=(2,2), padding="SAME", data_format=data_format)(inp_tensor) 28 | act_out = ReLU()(pre_conv_out) 29 | 30 | block1 = face_block(act_out, 24) 31 | block2 = face_block(block1, 28) 32 | block3 = face_block(block2, 32, strides=(2,2)) 33 | block4 = face_block(block3, 36) 34 | block5 = face_block(block4, 42) 35 | block6 = face_block(block5, 48, strides=(2,2)) 36 | block7 = face_block(block6, 56) 37 | block8 = face_block(block7, 64) 38 | block9 = face_block(block8, 72) 39 | block10 = face_block(block9, 80) 40 | block11 = face_block(block10, 88) 41 | 42 | block12 = face_block(block11, 96, strides=(2,2)) 43 | block13 = face_block(block12, 96) 44 | block14 = face_block(block13, 96) 45 | block15 = face_block(block14, 96) 46 | block16 = face_block(block15, 96) 47 | 48 | classifier_16 = Conv2D(filters=2, kernel_size=(1,1), strides=(1,1), name="classificator_8")(block11) 49 | classifier_16 = Reshape((pos1,1))(classifier_16) 50 | classifier_8 = Conv2D(filters=6, kernel_size=(1,1), strides=(1,1), name="classificator_16")(block16) 51 | classifier_8 = Reshape((pos2,1))(classifier_8) 52 | classifier = Concatenate(axis=1)([classifier_16, classifier_8]) 53 | classifier = tf.clip_by_value(classifier, -100, 100) 54 | classifier = tf.math.sigmoid(classifier) 55 | #All the post processing stage involving anchor multiplication and offset adjustment is done as part of the model itself 56 | points_16 = Conv2D(filters=32, kernel_size=(1,1), strides=(1,1), name="regressor_8")(block11) 57 | points_16 = Reshape((16, 16, 2, 16))(points_16) 58 | point_16_box_xy = points_16[:, :, :, :, :2] / x_scale + grid_16[..., :2] 59 | point_16_box_wh = points_16[:, :, :, :, 2:4] / x_scale 60 | point_16_land_slice = points_16[:, :, :, :, 4:] 61 | 62 | point_16_land_xy = point_16_land_slice / x_scale + grid_16 63 | point_16_all = Concatenate(axis=-1)([point_16_box_xy, point_16_box_wh, point_16_land_xy]) 64 | point_16_all = Reshape((-1, 16))(point_16_all) 65 | 66 | points_8 = Conv2D(filters=96, kernel_size=(1,1), strides=(1,1), name="regressor_16")(block16) 67 | points_8 = Reshape((8, 8, 6, 16))(points_8) 68 | point_8_box_xy = points_8[:, :, :, :, :2] / x_scale + grid_8[..., :2] 69 | point_8_box_wh = points_8[:, :, :, :, 2:4] / x_scale 70 | point_8_land_slice = points_8[:, :, :, :, 4:] 71 | point_8_land_xy = point_8_land_slice / x_scale + grid_8 72 | point_8_all = Concatenate(axis=-1)([point_8_box_xy, point_8_box_wh, point_8_land_xy]) 73 | point_8_all = Reshape((-1, 16))(point_8_all) 74 | 75 | points = Concatenate(axis=1)([point_16_all, point_8_all]) 76 | all_output = Concatenate(axis=-1)([points, classifier]) 77 | 78 | return tf.keras.Model(inputs=[inp_tensor], outputs=[all_output]) 79 | 80 | 81 | data_format = "channels_last" 82 | grid_8 = np.array(np.meshgrid(np.arange(0, 1, 1/8), np.arange(0, 1, 1/8))).transpose((1,2, 0)) + 1/16 83 | grid_8 = np.tile(np.expand_dims(grid_8, 2), 6) 84 | grid_16 = np.array(np.meshgrid(np.arange(0, 1, 1/16), np.arange(0, 1, 1/16))).transpose((1,2, 0)) + 1/32 85 | grid_16 = np.tile(np.expand_dims(grid_16, 2), 6) 86 | blazeface_tf = create_blazeface((128, 128, 3),grid_8, grid_16, batch_size=None, data_format=data_format) 87 | restore_variables(blazeface_tf, tf_lite_mapping, data_format) 88 | blazeface_tf.save("./keras_models/blazeface_tf.h5") 89 | 90 | tf.keras.backend.clear_session() 91 | coreml_tf = tf.keras.models.load_model("./keras_models/blazeface_tf.h5") 92 | inp_node = coreml_tf.inputs[0].name[:-2].split('/')[-1] 93 | out_node = coreml_tf.outputs[0].name[:-2].split('/')[-1] 94 | print(inp_node, out_node) 95 | blazeface_coreml = tfcoreml.convert( 96 | "./keras_models/blazeface_tf.h5", 97 | output_feature_names = [out_node], 98 | input_name_shape_dict = {inp_node: [1, *list(coreml_tf.inputs[0].shape[1:])]}, 99 | image_input_names = [inp_node], 100 | image_scale = 1/127.5, 101 | red_bias = -1, 102 | green_bias = -1, 103 | blue_bias=-1, 104 | minimum_ios_deployment_target='13' 105 | ) 106 | 107 | blazeface_coreml._spec.description.output[0].type.multiArrayType.shape.extend([1, 896, 17]) 108 | blazeface_coreml._spec.description.output[0].name = "box_landmarks_conf" 109 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "box_landmarks_conf" 110 | blazeface_coreml._spec.neuralNetwork.layers[-1].output[0] = "box_landmarks_conf" 111 | 112 | blazeface_coreml.save("./coreml_models/blazeface.mlmodel") 113 | 114 | inp_image = Image.open("./sample.jpg") 115 | inp_image = inp_image.resize((128, 128)) 116 | inp_image_int = np.array(inp_image) 117 | inp_image_np = inp_image_int.astype(np.float32) 118 | inp_image_np = np.expand_dims((inp_image_np/127.5) - 1, 0) 119 | blazeface_coreml = coremltools.models.MLModel("./coreml_models/blazeface.mlmodel") 120 | 121 | print("Checking model sanity across tensorflow, and coreml") 122 | tf_out = coreml_tf.predict(inp_image_np)[0] 123 | coreml_output = blazeface_coreml.predict({"input_image": inp_image}, useCPUOnly=True)["box_landmarks_conf"][0] #currently runs only on CPU 124 | print("Tensorflow output mean: {}".format(tf_out.mean())) 125 | print("CoreMl output mean: {}".format(coreml_output.mean())) 126 | 127 | box_tlbr = xywh_to_tlbr(tf_out[:, 0:4], y_first=True) 128 | out_boxes = tf.image.non_max_suppression(box_tlbr, tf_out[:, -1], 5, score_threshold=0.75) 129 | final_boxes = (tf_out[out_boxes.numpy(), :]*128).astype(np.int32) 130 | final_boxes = xywh_to_tlbr(final_boxes).astype(np.int32) 131 | for bx in final_boxes: 132 | cv2.rectangle(inp_image_int, (bx[0], bx[1]), (bx[2], bx[3]), (255, 0, 255), 1) 133 | landmarks = final_boxes[:, 4:-1].reshape(6,2) 134 | plt.imshow(inp_image_int) 135 | plt.scatter(landmarks[:, 0], landmarks[:, 1], marker="+") 136 | plt.savefig("blazeface_out.jpg") 137 | plt.show() -------------------------------------------------------------------------------- /convert_facemesh.py: -------------------------------------------------------------------------------- 1 | #This file takes the tflite model of facemesh and converts it to coreml, tf format 2 | import tensorflow as tf 3 | import numpy as np 4 | from tensorflow.keras.layers import * 5 | from layers import * 6 | from utils import * 7 | import coremltools 8 | import tfcoreml 9 | from PIL import Image 10 | import matplotlib.pyplot as plt 11 | print(tf.__version__) 12 | 13 | tflite_path = "./tflite_models/face_mesh.tflite" 14 | interpreter = tf.lite.Interpreter(model_path=tflite_path) 15 | interpreter.allocate_tensors() 16 | tf_lite_mapping = {} 17 | for i in interpreter.get_tensor_details(): 18 | if ("ker" in i["name"].lower()) or ("bia" in i["name"].lower()) or ("alph" in i["name"].lower()): 19 | tf_lite_mapping[i['name']] = interpreter.get_tensor(i["index"]) 20 | 21 | 22 | def create_facenet(input_shape, batch_size = 1, output_dim=1404, data_format="channels_last"): 23 | if data_format == "channels_first": 24 | shared_axes = [2,3] 25 | else: 26 | shared_axes = [1,2] 27 | input_tensor = Input(shape=input_shape, batch_size = batch_size, name="input_image") 28 | pre_conv_out = Conv2D(16, kernel_size=(3,3), strides=(2,2), padding="SAME", data_format=data_format)(input_tensor) 29 | act_out = PReLU(shared_axes=shared_axes)(pre_conv_out) 30 | block1 = res_block(act_out, 16, data_format=data_format) 31 | down1 = down_sampling(block1, 32, data_format=data_format) 32 | block2 = res_block(down1, 32, data_format=data_format) 33 | down2 = down_sampling(block2, 64, data_format=data_format) 34 | block3 = res_block(down2, 64, data_format=data_format) 35 | down3 = down_sampling(block3, 128, data_format=data_format) 36 | block4 = res_block(down3, 128, data_format=data_format) 37 | down4 = down_sampling(block4, 128, data_format=data_format) 38 | block5 = res_block(down4, 128, data_format=data_format) 39 | 40 | land1 = down_sampling(block5, 128, data_format=data_format) 41 | land2 = res_block(land1, 128, data_format=data_format) 42 | land3 = Conv2D(32, kernel_size=(1,1), strides=(1,1), data_format=data_format)(land2) 43 | land3 = PReLU(shared_axes=shared_axes)(land3) 44 | land4 = DepthwiseConv2D(kernel_size=(3,3), strides=(1,1), padding="SAME", data_format=data_format)(land3) 45 | land4 = Conv2D(32, kernel_size=(1,1), strides=(1,1), data_format=data_format)(land4) 46 | land_add_out = Add()([land3, land4]) 47 | land_act_out = PReLU(shared_axes=shared_axes)(land_add_out) 48 | land_final = Conv2D(output_dim, kernel_size=(3,3), strides=(1,1), data_format=data_format)(land_act_out) 49 | land_final = Reshape((output_dim,), name="landmarks")(land_final) 50 | 51 | conf1 = down_sampling(block5, 128, data_format=data_format) 52 | conf2 = Conv2D(32, kernel_size=(1,1), strides=(1,1), name="conv2d_28", data_format=data_format)(conf1) 53 | conf2 = PReLU(shared_axes=shared_axes, name="p_re_lu_26")(conf2) 54 | conf3 = DepthwiseConv2D(kernel_size=(3,3), strides=(1,1), padding="SAME", name="depthwise_conv2d_23",data_format=data_format)(conf2) 55 | conf3 = Conv2D(32, kernel_size=(1,1), strides=(1,1), name="conv2d_29", data_format=data_format)(conf3) 56 | conf_add_out = Add()([conf2, conf3]) 57 | conf_act_out = PReLU(shared_axes=shared_axes, name="p_re_lu_27")(conf_add_out) 58 | conf_final = Conv2D(1, kernel_size=(3,3), strides=(1,1), name="conv2d_30", data_format=data_format)(conf_act_out) 59 | conf_final = Reshape((1,), name="confidence")(conf_final) 60 | final_out = Concatenate()([land_final, conf_final]) #concatenation 1404D landmarks and 1D confidence into 1405D output 61 | return tf.keras.Model(inputs=[input_tensor], outputs=[final_out]) 62 | 63 | data_format = "channels_last" 64 | facemesh_tf = create_facenet((192,192,3), batch_size=None, output_dim=1404, data_format=data_format) 65 | restore_variables(facemesh_tf, tf_lite_mapping, data_format) 66 | facemesh_tf.save("./keras_models/facemesh_tf.h5") 67 | 68 | tf.keras.backend.clear_session() 69 | coreml_tf = tf.keras.models.load_model("./keras_models/facemesh_tf.h5") 70 | inp_node = coreml_tf.inputs[0].name[:-2].split('/')[-1] 71 | out_node = coreml_tf.outputs[0].name[:-2].split('/')[-1] 72 | print(inp_node, out_node) 73 | facemesh_coreml = tfcoreml.convert( 74 | "./keras_models/facemesh_tf.h5", 75 | output_feature_names = [out_node], 76 | input_name_shape_dict = {inp_node: [1, *list(coreml_tf.inputs[0].shape[1:])]}, 77 | image_input_names = [inp_node], 78 | image_scale = 1/127.5, 79 | red_bias = -1, 80 | green_bias = -1, 81 | blue_bias=-1, 82 | minimum_ios_deployment_target='13' 83 | ) 84 | facemesh_coreml._spec.description.output[0].type.multiArrayType.shape.extend([1, 1405]) 85 | facemesh_coreml._spec.description.output[0].name = "points_confidence" 86 | facemesh_coreml._spec.neuralNetwork.layers[-1].name = "points_confidence" 87 | facemesh_coreml._spec.neuralNetwork.layers[-1].output[0] = "points_confidence" #giving appropriate name for output nodes 88 | facemesh_coreml.save("./coreml_models/facemesh.mlmodel") #currently this coreml model doesnt run on GPU due to coreml bug 89 | 90 | inp_image = Image.open("sample.jpg") 91 | inp_image = inp_image.resize((192,192)) 92 | inp_image_np = np.array(inp_image).astype(np.float32) 93 | inp_image_np = np.expand_dims((inp_image_np/127.5) - 1, 0) 94 | facemesh_coreml = coremltools.models.MLModel("./coreml_models/facemesh.mlmodel") 95 | 96 | print("Checking model sanity across tensorflow, tflite and coreml") 97 | tf_output = coreml_tf.predict(inp_image_np) 98 | coreml_output = facemesh_coreml.predict({"input_image": inp_image}, useCPUOnly=True)["points_confidence"] 99 | interpreter.set_tensor(0, inp_image_np) 100 | interpreter.invoke() 101 | 102 | print("Tensorflow output mean: {}, {}".format(tf_output[:, :-1].mean(), tf_output[:, -1])) 103 | print("Tflite output mean: {}, {}".format(interpreter.get_tensor(213).mean(), interpreter.get_tensor(210).mean())) 104 | print("CoreMl output mean: {}, {}".format(coreml_output[:, :-1].mean(), coreml_output[:, -1])) 105 | 106 | detections = coreml_output[:, :-1].reshape(468, 3)[:, :2] 107 | plt.imshow(inp_image) 108 | plt.scatter(detections[:, 0], detections[:, 1], s = 1.0, marker="+") 109 | plt.savefig("facemesh_out.jpg") 110 | plt.show() -------------------------------------------------------------------------------- /coreml_models/blazeface.mlmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/coreml_models/blazeface.mlmodel -------------------------------------------------------------------------------- /coreml_models/blazeface_pipeline.mlmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/coreml_models/blazeface_pipeline.mlmodel -------------------------------------------------------------------------------- /coreml_models/facemesh.mlmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/coreml_models/facemesh.mlmodel -------------------------------------------------------------------------------- /create_blazeface_coreml_pipeline.py: -------------------------------------------------------------------------------- 1 | """ 2 | this file takes the converted blazeface coreml model from convert_blazeface.py 3 | and adds Non-maximum suppresion to create a pipeline. 4 | currently multiple outputs in coreML with tf2.0 Keras is not working so working around to change the single 5 | output in coreml to multiple output 6 | """ 7 | import coremltools 8 | from coremltools.models import datatypes 9 | from coremltools.models.pipeline import * 10 | from PIL import Image 11 | 12 | include_landmarks = False 13 | blazeface_coreml = coremltools.models.MLModel("./coreml_models/blazeface.mlmodel") 14 | blazeface_coreml._spec.description.output.pop(-1) 15 | blazeface_coreml._spec.neuralNetwork.layers.pop(-1) 16 | 17 | #adding the boxes output layer 18 | blazeface_coreml._spec.neuralNetwork.layers.add() 19 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.MergeFromString(b'') 20 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "boxes_pre" 21 | blazeface_coreml._spec.neuralNetwork.layers[-1].input.append("model/concatenate_3/concat") 22 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor.add() 23 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].rank = 3 24 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].dimValue.extend([1, 896, 16]) 25 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor.add() 26 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].rank = 3 27 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].dimValue.extend([1,896, 4]) 28 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.strides.extend([1,1,1]) 29 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.beginIds.extend([0, 0, 0]) 30 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.endIds.extend([2147483647, 2147483647, 4]) 31 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.beginMasks.extend([True, True, True]) 32 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.endMasks.extend([True, True, False]) 33 | blazeface_coreml._spec.neuralNetwork.layers[-1].output.append("boxes_pre") 34 | #squeezing the first dimension 35 | blazeface_coreml._spec.neuralNetwork.layers.add() 36 | blazeface_coreml._spec.neuralNetwork.layers[-1].squeeze.MergeFromString(b'') 37 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "boxes" 38 | blazeface_coreml._spec.neuralNetwork.layers[-1].input.append("boxes_pre") 39 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor.add() 40 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].rank = 3 41 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].dimValue.extend([1, 896, 4]) 42 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor.add() 43 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].rank = 2 44 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].dimValue.extend([896, 4]) 45 | blazeface_coreml._spec.neuralNetwork.layers[-1].squeeze.squeezeAll = True 46 | blazeface_coreml._spec.neuralNetwork.layers[-1].output.append("boxes") 47 | 48 | #creating the landmarks output layer 49 | confidence_index = -6 50 | if include_landmarks: 51 | confidence_index = -8 52 | blazeface_coreml._spec.neuralNetwork.layers.add() 53 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.MergeFromString(b'') 54 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "landmarks_pre" 55 | blazeface_coreml._spec.neuralNetwork.layers[-1].input.append("model/concatenate_3/concat") 56 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor.add() 57 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].rank = 3 58 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].dimValue.extend([1, 896, 16]) 59 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor.add() 60 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].rank = 3 61 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].dimValue.extend([1,896, 12]) 62 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.strides.extend([1,1,1]) 63 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.beginIds.extend([0, 0, 4]) 64 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.endIds.extend([2147483647, 2147483647, 16]) 65 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.beginMasks.extend([True, True, False]) 66 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.endMasks.extend([True, True, True]) 67 | blazeface_coreml._spec.neuralNetwork.layers[-1].output.append("landmarks_pre") 68 | 69 | blazeface_coreml._spec.neuralNetwork.layers.add() 70 | blazeface_coreml._spec.neuralNetwork.layers[-1].squeeze.MergeFromString(b'') 71 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "landmarks" 72 | blazeface_coreml._spec.neuralNetwork.layers[-1].input.append("landmarks_pre") 73 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor.add() 74 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].rank = 3 75 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].dimValue.extend([1, 896, 12]) 76 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor.add() 77 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].rank = 2 78 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].dimValue.extend([896, 12]) 79 | blazeface_coreml._spec.neuralNetwork.layers[-1].squeeze.squeezeAll = True 80 | blazeface_coreml._spec.neuralNetwork.layers[-1].output.append("landmarks") 81 | 82 | # creating a new layer by squeezing confidence output 83 | blazeface_coreml._spec.neuralNetwork.layers.add() 84 | blazeface_coreml._spec.neuralNetwork.layers[-1].sliceStatic.MergeFromString(b'') 85 | blazeface_coreml._spec.neuralNetwork.layers[-1].name = "box_confidence" 86 | blazeface_coreml._spec.neuralNetwork.layers[-1].input.append(blazeface_coreml._spec.neuralNetwork.layers[confidence_index].output[0]) 87 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor.add() 88 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].rank = 3 89 | blazeface_coreml._spec.neuralNetwork.layers[-1].inputTensor[0].dimValue.extend([1, 896, 1]) 90 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor.add() 91 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].rank = 2 92 | blazeface_coreml._spec.neuralNetwork.layers[-1].outputTensor[0].dimValue.extend([896, 1]) 93 | blazeface_coreml._spec.neuralNetwork.layers[-1].squeeze.squeezeAll = True 94 | blazeface_coreml._spec.neuralNetwork.layers[-1].output.append("box_confidence") 95 | 96 | #adding the output nodes to description 97 | #adding box score layers 98 | blazeface_coreml._spec.description.output.add() 99 | blazeface_coreml._spec.description.output[0].name = "box_confidence" 100 | blazeface_coreml._spec.description.output[0].type.multiArrayType.shape.extend([896, 1]) 101 | blazeface_coreml._spec.description.output[0].type.multiArrayType.dataType = datatypes._FeatureTypes_pb2.ArrayFeatureType.DOUBLE 102 | 103 | #adding box output 104 | blazeface_coreml._spec.description.output.add() 105 | blazeface_coreml._spec.description.output[1].name = "boxes" 106 | blazeface_coreml._spec.description.output[1].type.multiArrayType.shape.extend([896, 4]) 107 | blazeface_coreml._spec.description.output[1].type.multiArrayType.dataType = datatypes._FeatureTypes_pb2.ArrayFeatureType.DOUBLE 108 | 109 | #adding landmark output 110 | if include_landmarks: 111 | blazeface_coreml._spec.description.output.add() 112 | blazeface_coreml._spec.description.output[2].name = "landmarks" 113 | blazeface_coreml._spec.description.output[2].type.multiArrayType.shape.extend([896, 12]) 114 | blazeface_coreml._spec.description.output[2].type.multiArrayType.dataType = datatypes._FeatureTypes_pb2.ArrayFeatureType.DOUBLE 115 | 116 | nms_spec = coremltools.proto.Model_pb2.Model() 117 | nms_spec.specificationVersion = 3 118 | for i in range(2): 119 | blazeface_output = blazeface_coreml._spec.description.output[i].SerializeToString() 120 | nms_spec.description.input.add() 121 | nms_spec.description.input[i].ParseFromString(blazeface_output) 122 | nms_spec.description.output.add() 123 | nms_spec.description.output[i].ParseFromString(blazeface_output) 124 | 125 | nms_spec.description.output[0].name = "confidence" 126 | nms_spec.description.output[1].name = "coordinates" 127 | 128 | output_sizes = [1, 4] 129 | for i in range(2): 130 | ma_type = nms_spec.description.output[i].type.multiArrayType 131 | ma_type.shapeRange.sizeRanges.add() 132 | ma_type.shapeRange.sizeRanges[0].lowerBound = 0 133 | ma_type.shapeRange.sizeRanges[0].upperBound = -1 134 | ma_type.shapeRange.sizeRanges.add() 135 | ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i] 136 | ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i] 137 | del ma_type.shape[:] 138 | 139 | nms = nms_spec.nonMaximumSuppression 140 | nms.confidenceInputFeatureName = "box_confidence" 141 | nms.coordinatesInputFeatureName = "boxes" 142 | nms.confidenceOutputFeatureName = "confidence" 143 | nms.coordinatesOutputFeatureName = "coordinates" 144 | nms.iouThresholdInputFeatureName = "iouThreshold" 145 | nms.confidenceThresholdInputFeatureName = "confidenceThreshold" 146 | 147 | default_iou_threshold = 0.5 148 | default_confidence_threshold = 0.75 149 | nms.iouThreshold = default_iou_threshold 150 | nms.confidenceThreshold = default_confidence_threshold 151 | nms.stringClassLabels.vector.extend(["face"]) 152 | nms_model = coremltools.models.MLModel(nms_spec) 153 | 154 | 155 | input_features = [("input_image", datatypes.Array(3,128,128)), ("iouThreshold", datatypes.Double()), 156 | ("confidenceThreshold", datatypes.Double())] #cannot directly pass imageType as input type here. 157 | output_features = [ "confidence", "coordinates"] 158 | pipeline = Pipeline(input_features, output_features) 159 | 160 | pipeline.add_model(blazeface_coreml._spec) 161 | pipeline.add_model(nms_model._spec) 162 | pipeline.spec.description.input[0].ParseFromString(blazeface_coreml._spec.description.input[0].SerializeToString()) 163 | pipeline.spec.description.input[1].type.isOptional = True 164 | pipeline.spec.description.input[2].type.isOptional = True 165 | pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString()) 166 | pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString()) 167 | 168 | final_model = coremltools.models.MLModel(pipeline.spec) 169 | final_model.save("./coreml_models/blazeface_pipeline.mlmodel") 170 | 171 | inp_image = Image.open("./sample.jpg") 172 | inp_image = inp_image.resize((128, 128)) 173 | 174 | predictions = final_model.predict({'input_image': inp_image}, useCPUOnly=True) 175 | print(predictions) -------------------------------------------------------------------------------- /keras_models/blazeface_tf.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/keras_models/blazeface_tf.h5 -------------------------------------------------------------------------------- /keras_models/facemesh_tf.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/keras_models/facemesh_tf.h5 -------------------------------------------------------------------------------- /landmark_contours.txt: -------------------------------------------------------------------------------- 1 | lips 61 146 146 91 91 181 181 84 84 17 17 314 314 405 405 321 321 375 375 291 61 185 185 40 40 39 39 37 37 0 0 267 267 269 269 270 270 409 409 291 78 95 95 88 88 178 178 87 87 14 14 317 317 402 402 318 318 324 324 308 78 191 191 80 80 81 81 82 82 13 13 312 312 311 311 310 310 415 415 308 2 | left_eye 33 7 7 163 163 144 144 145 145 153 153 154 154 155 155 133 33 246 246 161 161 160 160 159 159 158 158 157 157 173 173 133 3 | right_eye 263 249 249 390 390 373 373 374 374 380 380 381 381 382 382 362 263 466 466 388 388 387 387 386 386 385 385 384 384 398 398 362 4 | left_eyebrow 46 53 53 52 52 65 65 55 70 63 63 105 105 66 66 107 5 | right_eyebrow 276 283 283 282 282 295 295 285 300 293 293 334 334 296 296 336 6 | face 10 338 338 297 297 332 332 284 284 251 251 389 389 356 356 454 454 323 323 361 361 288 288 397 397 365 365 379 379 378 378 400 400 377 377 152 152 148 148 176 176 149 149 150 150 136 136 172 172 58 58 132 132 93 93 234 234 127 127 162 162 21 21 54 54 103 103 67 67 109 109 10 7 | -------------------------------------------------------------------------------- /layers.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from tensorflow.keras.layers import * 4 | print(tf.__version__) 5 | 6 | def res_block(inp_tensor, out_filters, kernel_size=(3,3), strides=(1,1), data_format="channels_last"): 7 | if data_format == "channels_first": 8 | shared_axes = [2,3] 9 | else: 10 | shared_axes = [1,2] 11 | depth1 = DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding="SAME",data_format=data_format)(inp_tensor) 12 | conv1 = Conv2D(out_filters, kernel_size=(1,1), strides=(1,1),data_format=data_format)(depth1) 13 | add1_out = Add()([inp_tensor, conv1]) 14 | act_1 = PReLU(shared_axes=shared_axes)(add1_out) 15 | depth2 = DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding="SAME", data_format=data_format)(act_1) 16 | conv2 = Conv2D(out_filters, kernel_size=(1,1), strides=(1,1), data_format=data_format)(depth2) 17 | add2_out = Add()([act_1, conv2]) 18 | act2 = PReLU(shared_axes=shared_axes)(add2_out) 19 | return act2 20 | 21 | def down_sampling(inp_tensor, out_filters, strides=(2,2), kernel_size=(3,3), data_format="channels_last"): 22 | 23 | if data_format == "channels_first": 24 | pad_dim = out_filters - inp_tensor.shape[1] 25 | shared_axes = [2,3] 26 | pad_val = [[0,0], [0, pad_dim], [0,0], [0,0]] 27 | else: 28 | pad_dim = out_filters - inp_tensor.shape[3] 29 | shared_axes = [1,2] 30 | pad_val = [[0,0], [0,0], [0,0], [0, pad_dim]] 31 | 32 | depth1 = DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding="SAME", data_format=data_format)(inp_tensor) 33 | conv1 = Conv2D(out_filters, kernel_size=(1,1), strides=(1,1), data_format=data_format)(depth1) 34 | max_pool = MaxPool2D(pool_size=(2,2), strides=strides, data_format=data_format)(inp_tensor) 35 | if pad_dim != 0: 36 | max_pool = tf.pad(max_pool, pad_val) 37 | add1_out = Add()([conv1, max_pool]) 38 | act_1 = PReLU(shared_axes=shared_axes)(add1_out) 39 | return act_1 40 | 41 | def face_block(inp_tensor, out_filters, kernel_size=(3,3), strides=(1,1), data_format="channels_last"): 42 | residual = inp_tensor 43 | if data_format == "channels_last": 44 | pad_dim = out_filters - inp_tensor.shape[3] 45 | pad_value = [[0,0], [0,0], [0,0], [0, pad_dim]] 46 | elif data_format == "channels_first": 47 | pad_dim = out_filters = inp_tensor.shape[1] 48 | pad_value = [[0,0], [0, pad_dim], [0,0], [0,0]] 49 | depth1 = DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding="SAME")(inp_tensor) 50 | conv1 = Conv2D(out_filters, kernel_size=(1,1), strides=(1,1))(depth1) 51 | if strides[0] == 2: 52 | residual = MaxPool2D(pool_size=strides, strides=strides)(residual) 53 | if pad_dim != 0: 54 | residual = tf.pad(residual, pad_value) 55 | add_result = Add()([conv1, residual]) 56 | act_out = ReLU()(add_result) 57 | return act_out -------------------------------------------------------------------------------- /live_demo.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import tensorflow as tf 3 | import matplotlib.pyplot as plt 4 | from utils import * 5 | import time 6 | 7 | video = cv2.VideoCapture(0) 8 | blazeface_tf = tf.keras.models.load_model("./keras_models/blazeface_tf.h5") 9 | facemesh_tf = tf.keras.models.load_model("./keras_models/facemesh_tf.h5") 10 | mappings = open("landmark_contours.txt").readlines() 11 | contours = {} 12 | for line in mappings: 13 | line = line.strip().split(" ") 14 | contours[line[0]] = [int(i) for i in line[1:]] 15 | 16 | 17 | def predict_frame(orig_frame): 18 | orig_h, orig_w = orig_frame.shape[0:2] 19 | frame = create_letterbox_image(orig_frame, 128) 20 | h,w = frame.shape[0:2] 21 | input_frame = cv2.cvtColor(cv2.resize(frame, (128, 128)), cv2.COLOR_BGR2RGB) 22 | input_tensor = np.expand_dims(input_frame.astype(np.float32), 0) / 127.5 - 1 23 | result = blazeface_tf.predict(input_tensor)[0] 24 | final_boxes, landmarks_proposals = process_detections(result,(orig_h, orig_w),5, 0.75, 0.5, pad_ratio=0.5) 25 | if len(final_boxes) == 0: return orig_frame 26 | landmarks_input = get_landmarks_crop(orig_frame, landmarks_proposals, (192, 192)) 27 | landmarks_result = facemesh_tf.predict(landmarks_input)[:, :-1] 28 | final_landmarks = process_landmarks(landmarks_result, landmarks_proposals, (orig_h, orig_w), 192) 29 | assert len(final_boxes) == len(final_landmarks) 30 | for (bx,land) in zip(final_boxes, final_landmarks): 31 | cv2.rectangle(orig_frame, (bx[0], bx[1]), (bx[2], bx[3]), (255, 0, 255), 1) 32 | cv2.drawContours(orig_frame, land[np.newaxis, contours["face"], :], -1, (255, 0, 0), thickness=2) 33 | for pt in land: 34 | cv2.circle(orig_frame, (pt[0], pt[1]), 1, (0, 0, 255), -1) 35 | return orig_frame 36 | 37 | while True: 38 | ret, frame = video.read() 39 | if ret: 40 | cv2.imshow("image", predict_frame(frame)) 41 | else: 42 | break 43 | if cv2.waitKey(1) & 0xFF == ord('q'): 44 | break 45 | video.release() 46 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /results/blazeface_out.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/results/blazeface_out.jpg -------------------------------------------------------------------------------- /results/facemesh_out.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/results/facemesh_out.jpg -------------------------------------------------------------------------------- /results/usain.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/results/usain.gif -------------------------------------------------------------------------------- /sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/sample.jpg -------------------------------------------------------------------------------- /tflite_models/face_detection_front.tflite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/tflite_models/face_detection_front.tflite -------------------------------------------------------------------------------- /tflite_models/face_mesh.tflite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gouthamvgk/facemesh_coreml_tf/e65a8211ca694dd9517dd17837965d5858ee2e5f/tflite_models/face_mesh.tflite -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import tensorflow as tf 4 | 5 | def get_clean_name(string): 6 | if "depth" in string.lower() and "kernel" in string.lower(): 7 | return string.split('/')[0] + '/' + 'Kernel' 8 | elif "depth" in string.lower() and "bias" in string.lower(): 9 | return string.split('/')[0] + '/' + 'Bias' 10 | elif "conv2d" in string.lower() and "kernel" in string.lower(): 11 | return string.split('/')[0] + '/' + 'Kernel' 12 | elif "conv2d" in string.lower() and "bias" in string.lower(): 13 | return string.split('/')[0] + '/' + 'Bias' 14 | elif "lu" in string.lower(): 15 | return string.split('/')[0] + '/' + "Alpha" 16 | elif "kernel" in string.lower(): 17 | return string.split('/')[0] + '/' + "Kernel" 18 | elif "bias" in string.lower(): 19 | return string.split('/')[0] + '/' + "Bias" 20 | else: 21 | raise ValueError("Input string not understood") 22 | 23 | exception_mapping = { 24 | "depthwise_conv2d_18/depthwise_kernel" : "depthwise_conv2d_22/Kernel", 25 | "depthwise_conv2d_18/bias": "depthwise_conv2d_22/Bias", 26 | "conv2d_21/kernel" : "conv2d_27/Kernel", 27 | "conv2d_21/bias": "conv2d_27/Bias", 28 | "p_re_lu_20/alpha": "p_re_lu_25/Alpha" 29 | } 30 | 31 | def restore_variables(model,tf_lite_mapping, data_format): 32 | channels_first = True if data_format == "channels_first" else False 33 | restored = 0 34 | total_params = 0 35 | for var in model.variables: 36 | try: 37 | name = get_clean_name(var.name) 38 | weight = tf_lite_mapping[name] 39 | except KeyError: 40 | map_string = exception_mapping[var.name[:-2]] 41 | name = get_clean_name(map_string) 42 | weight = tf_lite_mapping[name] 43 | if weight.ndim == 4: 44 | weight = np.transpose(weight, (1,2,3,0)) # conv transpose 45 | elif weight.ndim ==3: 46 | if channels_first: weight = np.transpose(weight, (2, 0, 1)) #prelu_transpose 47 | total_params += np.product(weight.shape) 48 | var.assign(weight) 49 | print("{} assinged with {}".format(var.name, name)) 50 | restored += 1 51 | print("Restored {} variables from tflite file".format(restored)) 52 | print("Restore {} float values".format(total_params)) 53 | 54 | def xywh_to_tlbr(boxes, y_first=False): 55 | """ 56 | boxes - (N, 4) 57 | """ 58 | final_boxes = boxes.copy() 59 | if not y_first: 60 | final_boxes[:, 0:2] = np.clip(boxes[:, 0:2] - (boxes[:, 2:4]/2), 0, None) #clipping at 0 since image dim starts at 0 61 | final_boxes[:, 2:4] = boxes[:, 0:2] + (boxes[:, 2:4]/2) 62 | else: 63 | final_boxes[:, 0:2] = np.clip(boxes[:, [1,0]] - (boxes[:, [3,2]]/2), 0, None) 64 | final_boxes[:, 2:4] = boxes[:, [1,0]] + (boxes[:, [3,2]]/2) 65 | return final_boxes 66 | 67 | def create_letterbox_image(frame, dim): 68 | h, w = frame.shape[0:2] 69 | scale = min(dim/h, dim/w) 70 | nh, nw = int(scale*h), int(scale*w) 71 | resized = cv2.resize(frame, (nw, nh)) 72 | new_image = np.zeros((dim, dim, 3), np.uint8) 73 | new_image.fill(256) 74 | dx = (dim-nw)//2 75 | dy = (dim-nh)//2 76 | new_image[dy:dy+nh, dx:dx+nw,:] = resized 77 | return new_image 78 | 79 | #takes the letterbox dimensions and the original dimensions to map the results in letterbox image coordinates 80 | #to original image coordinates 81 | def convert_to_orig_points(results, orig_dim, letter_dim): 82 | if results.ndim == 1: np.expand_dims(results, 0) 83 | inter_scale = min(letter_dim/orig_dim[0], letter_dim/orig_dim[1]) 84 | inter_h, inter_w = int(inter_scale*orig_dim[0]), int(inter_scale*orig_dim[1]) 85 | offset_x, offset_y = (letter_dim - inter_w)/2.0/letter_dim, (letter_dim - inter_h)/2.0/letter_dim 86 | scale_x, scale_y = letter_dim/inter_w, letter_dim/inter_h 87 | results[:, 0:2] = (results[:, 0:2] - [offset_x, offset_y]) * [scale_x, scale_y] 88 | results[:, 2:4] = results[:, 2:4] * [scale_x, scale_y] 89 | results[:, 4:16:2] = (results[:, 4:16:2] - offset_x) * scale_x 90 | results[:, 5:17:2] = (results[:, 5:17:2] - offset_y) * scale_y 91 | #converting from 0-1 range to (orign_dim) range 92 | results[:, 0:16:2] *= orig_dim[1] 93 | results[:, 1:17:2] *= orig_dim[0] 94 | 95 | return results.astype(np.int32) 96 | 97 | def process_detections(results, orig_dim, max_boxes=5, score_threshold=0.75, iou_threshold=0.5, pad_ratio=0.5): 98 | box_tlbr = xywh_to_tlbr(results[:, 0:4], y_first=True) 99 | out_boxes = tf.image.non_max_suppression(box_tlbr, results[:, -1], max_boxes, 100 | score_threshold=score_threshold, iou_threshold=iou_threshold) 101 | filter_boxes = results[out_boxes.numpy(), :-1] 102 | orig_points = convert_to_orig_points(filter_boxes, orig_dim, 128) 103 | landmarks_xywh = orig_points.copy() 104 | landmarks_xywh[:, 2:4] += (landmarks_xywh[:, 2:4] * pad_ratio).astype(np.int32) #adding some padding around detection for landmark detection step. 105 | landmarks_xywh[:, 1:2] -= (landmarks_xywh[:, 3:4]*0.08).astype(np.int32) #adjusting center_y since the detector outputs boxes from forehead and to account for that bias 106 | final_boxes = xywh_to_tlbr(orig_points).astype(np.int32) 107 | return final_boxes, landmarks_xywh 108 | 109 | def get_landmarks_crop(orig_frame, landmarks_proposals, input_dim): 110 | landmarks_proposals = xywh_to_tlbr(landmarks_proposals).astype(np.int32) 111 | proposals = [] 112 | for prop in landmarks_proposals: 113 | proposals.append(cv2.cvtColor(cv2.resize(orig_frame[prop[1]:prop[3], prop[0]:prop[2], :], (input_dim[1], input_dim[0])), cv2.COLOR_BGR2RGB)) 114 | proposals = np.array(proposals).astype(np.float32)/127.5 - 1 115 | return proposals 116 | 117 | def process_landmarks(landmarks_result, landmarks_proposals, orig_dim, land_dim): 118 | landmarks_result = np.reshape(landmarks_result, (-1, 468, 3))[:, :, :2] 119 | proposal_orig_scale = landmarks_proposals[:, 2:4] / land_dim 120 | landmarks_result[:, :, :2] *= proposal_orig_scale[:, np.newaxis, :] 121 | landmarks_prop_tlwh = xywh_to_tlbr(landmarks_proposals) 122 | landmarks_result += landmarks_prop_tlwh[:,np.newaxis, 0:2] 123 | landmarks_result = landmarks_result.astype(np.int32) 124 | return landmarks_result 125 | --------------------------------------------------------------------------------