[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "## HLNet: A Unified Framework for Real-Time Segmentation and Facial Skin Tones Evaluation\n\n## Abstract:\nReal-time semantic segmentation plays a crucial role in industrial applications, such as\nautonomous driving, the beauty industry, and so on. It is a challenging problem to balance the\nrelationship between speed and segmentation performance. To address such a complex task, this\npaper introduces an efficient convolutional neural network (CNN) architecture named HLNet for\ndevices with limited resources. Based on high-quality design modules, HLNet better integrates\nhigh-dimensional and low-dimensional information while obtaining sufficient receptive fields, which\nachieves remarkable results on three benchmark datasets. To our knowledge, the accuracy of skin\ntone classification is usually unsatisfactory due to the influence of external environmental factors such\nas illumination and background impurities. Therefore, we use HLNet to obtain accurate face regions,\nand further use color moment algorithm to extract its color features. Specifically, for a 224 × 224\ninput, using our HLNet, we achieve 78.39% mean IoU on Figaro1k dataset at over 17 FPS in the case\nof the CPU environment. We further use the masked color moment for skin tone grade evaluation\nand approximate 80% classification accuracy demonstrate the feasibility of the proposed method.  \n\n## The latest open source work:\nhttps://github.com/JACKYLUO1991/FaceParsing.\n\n## **Problem correction:**\n*It is worth noting that some training sets are mistaken for test sets in image file copying, which leads to high results in arXiv. The current version has been corrected.*\n\n## Demos\n<div><div align=center>\n  <img src=\"https://github.com/JACKYLUO1991/Face-skin-hair-segmentaiton-and-skin-color-evaluation/blob/master/res/5-4.png\" width=\"256\" height=\"256\" alt=\"raw\"/></div>\n\n## Please cited:\n```\n@article{feng2020hlnet,\n  title={HLNet: A Unified Framework for Real-Time Segmentation and Facial Skin Tones Evaluation},\n  author={Feng, Xinglong and Gao, Xianwen and Luo, Ling},\n  journal={Symmetry},\n  volume={12},\n  number={11},\n  pages={1812},\n  year={2020},\n  publisher={Multidisciplinary Digital Publishing Institute}\n}\n```\n\n"
  },
  {
    "path": "benchmark.py",
    "content": "import tensorflow as tf\n\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nimport time\nimport numpy as np\nimport argparse\nfrom tqdm import tqdm\n\nfrom model.hlnet import HLNet\nfrom model.dfanet import DFANet\nfrom model.enet import ENet\nfrom model.lednet import LEDNet\nfrom model.mobilenet import MobileNet\nfrom model.fast_scnn import Fast_SCNN\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--image_size\", '-i',\n                    help=\"image size\", type=int, default=256)\nparser.add_argument(\"--batch_size\", '-b',\n                    help=\"batch size\", type=int, default=3)\nparser.add_argument(\"--model_name\", help=\"model's name\",\n                    choices=['hlnet', 'fastscnn', 'lednet', 'dfanet', 'enet', 'mobilenet'],\n                    type=str, default='hlnet')\nparser.add_argument(\"--nums\", help=\"output num\",\n                    type=int, default=1)\nargs = parser.parse_args()\n\nIMG_SIZE = args.image_size\nCLS_NUM = args.nums\n\n\ndef get_model(name):\n    if name == 'hlnet':\n        model = HLNet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    elif name == 'fastscnn':\n        model = Fast_SCNN(num_classes=CLS_NUM, input_shape=(IMG_SIZE, IMG_SIZE, 3)).model()\n    elif name == 'lednet':\n        model = LEDNet(groups=2, classes=CLS_NUM, input_shape=(IMG_SIZE, IMG_SIZE, 3)).model()\n    elif name == 'dfanet':\n        model = DFANet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM, size_factor=2)\n    elif name == 'enet':\n        model = ENet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    elif name == 'mobilenet':\n        model = MobileNet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    else:\n        raise NameError(\"No corresponding model...\")\n\n    return model\n\n\ndef main():\n    \"\"\"Benchmark your model in your local pc.\"\"\"\n\n    model = get_model(args.model_name)\n    inputs = np.random.randn(args.batch_size, args.image_size, args.image_size, 3)\n\n    time_per_batch = []\n\n    for i in tqdm(range(500)):\n        start = time.time()\n        model.predict(inputs, batch_size=args.batch_size)\n        elapsed = time.time() - start\n        time_per_batch.append(elapsed)\n\n    time_per_batch = np.array(time_per_batch)\n\n    # Remove the first item\n    print(time_per_batch[1:].mean())\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "data_loader.py",
    "content": "import numpy as np\nimport cv2\nimport os\nimport random\nimport glob\n\nfrom keras.utils import Sequence\nfrom keras.applications.imagenet_utils import preprocess_input as pinput\n\n\nclass HairGenerator(Sequence):\n\n    def __init__(self,\n                 transformer,\n                 root_dir,\n                 mode='Training',\n                 nb_classes=3,\n                 batch_size=4,\n                 backbone=None,\n                 shuffle=False):\n\n        # backbone fit for segmentation_models，have been deleted now...\n        assert mode in ['Training', 'Testing'], \"Data set selection error...\"\n\n        self.image_path_list = sorted(\n            glob.glob(os.path.join(root_dir, 'Original', mode, '*')))\n        self.mask_path_list = sorted(\n            glob.glob(os.path.join(root_dir, 'GT', mode, '*')))\n        self.transformer = transformer\n        self.batch_size = batch_size\n        self.nb_classes = nb_classes\n        self.shuffle = shuffle\n        self.mode = mode\n        self.backbone = backbone\n\n    def __getitem__(self, idx):\n        images, masks = [], []\n\n        for (image_path, mask_path) in zip(self.image_path_list[idx * self.batch_size: (idx + 1) * self.batch_size],\n                                           self.mask_path_list[idx * self.batch_size: (idx + 1) * self.batch_size]):\n            image = cv2.imread(image_path, 1)\n            mask = cv2.imread(mask_path, 0)\n\n            image = self._padding(image)\n            mask = self._padding(mask)\n\n            # augumentation\n            augmentation = self.transformer(image=image, mask=mask)\n            image = augmentation['image']\n            mask = self._get_result_map(augmentation['mask'])\n\n            images.append(image)\n            masks.append(mask)\n\n        images = np.array(images)\n        masks = np.array(masks)\n        images = pinput(images)\n\n        return images, masks\n\n    def __len__(self):\n        \"\"\"Steps required per epoch\"\"\"\n        return len(self.image_path_list) // self.batch_size\n\n    def _padding(self, image):\n        shape = image.shape\n        h, w = shape[:2]\n        width = np.max([h, w])\n        padd_h = (width - h) // 2\n        padd_w = (width - w) // 2\n        if len(shape) == 3:\n            padd_tuple = ((padd_h, width - h - padd_h),\n                          (padd_w, width - w - padd_w), (0, 0))\n        else:\n            padd_tuple = ((padd_h, width - h - padd_h), (padd_w, width - w - padd_w))\n        image = np.pad(image, padd_tuple, 'constant')\n        return image\n\n    def on_epoch_end(self):\n        \"\"\"Shuffle image order\"\"\"\n        if self.shuffle:\n            c = list(zip(self.image_path_list, self.mask_path_list))\n            random.shuffle(c)\n            self.image_path_list, self.mask_path_list = zip(*c)\n\n    def _get_result_map(self, mask):\n        \"\"\"Processing mask data\"\"\"\n\n        # mask.shape[0]: row, mask.shape[1]: column\n        result_map = np.zeros((mask.shape[1], mask.shape[0], self.nb_classes))\n        # 0 (background pixel), 128 (face area pixel) or 255 (hair area pixel).\n        skin = (mask == 128)\n        hair = (mask == 255)\n\n        if self.nb_classes == 2:\n            # hair = (mask > 128)\n            background = np.logical_not(hair)\n            result_map[:, :, 0] = np.where(background, 1, 0)\n            result_map[:, :, 1] = np.where(hair, 1, 0)\n        elif self.nb_classes == 3:\n            background = np.logical_not(hair + skin)\n            result_map[:, :, 0] = np.where(background, 1, 0)\n            result_map[:, :, 1] = np.where(skin, 1, 0)\n            result_map[:, :, 2] = np.where(hair, 1, 0)\n        else:\n            raise Exception(\"error...\")\n\n        return result_map\n"
  },
  {
    "path": "experiments/cal_histogram.py",
    "content": "\n# 参考资料:\n# https://www.cnblogs.com/maybe2030/p/4585705.html\n# https://blog.csdn.net/zhu_hongji/article/details/80443585\n# https://blog.csdn.net/wsp_1138886114/article/details/80660014\n# https://blog.csdn.net/gfjjggg/article/details/87919658\n# https://baike.baidu.com/item/%E9%A2%9C%E8%89%B2%E7%9F%A9/19426187?fr=aladdin\n# https://blog.csdn.net/langyuewu/article/details/4144139\nfrom __future__ import print_function, division\n\nfrom sklearn import svm\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.externals import joblib\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nimport time\nfrom imutils import paths\nimport logging\nlogging.basicConfig(level=logging.INFO,\n                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nfrom utils import *\n\n\nclass RGBHistogram(Histogram):\n    '''RGB Histogram'''\n\n    def __init__(self, bins):\n        super().__init__(bins)\n\n    def describe(self, image, mask):\n        hist_b = cv.calcHist([image], [0], mask, self.bins,\n                             [0, 256])\n        hist_g = cv.calcHist([image], [1], mask, self.bins,\n                             [0, 256])\n        hist_r = cv.calcHist([image], [2], mask, self.bins,\n                             [0, 256])\n        hist_b = hist_b / np.sum(hist_b)\n        hist_g = hist_g / np.sum(hist_g)\n        hist_r = hist_r / np.sum(hist_r)\n        \n        # 24 dimensions\n        return np.concatenate([hist_b, hist_g, hist_r], axis=0).reshape(-1)\n\n\n\nclass HSVHistogram(Histogram):\n    '''HSV Histogram'''\n\n    def __init__(self, bins):\n        super().__init__(bins)\n\n    def describe(self, image, mask):\n        image = cv.cvtColor(image, cv.COLOR_BGR2HSV)\n        hist_h = cv.calcHist([image], [0], mask, self.bins,\n                             [0, 180])\n        hist_s = cv.calcHist([image], [1], mask, self.bins,\n                             [0, 256])\n        hist_v = cv.calcHist([image], [2], mask, self.bins,\n                             [0, 256])\n        hist_h = hist_h / np.sum(hist_h)\n        hist_s = hist_s / np.sum(hist_s)\n        hist_v = hist_v / np.sum(hist_v)\n\n        # 24 dimensions\n        return np.concatenate([hist_h, hist_s, hist_v], axis=0).reshape(-1)\n\n\nclass YCrCbHistogram(Histogram):\n    '''YCrCb Histogram'''\n\n    def __init__(self, bins):\n        super().__init__(bins)\n\n    def describe(self, image, mask):\n        image = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)\n        hist_y = cv.calcHist([image], [0], mask, self.bins,\n                             [0, 256])\n        hist_cr = cv.calcHist([image], [1], mask, self.bins,\n                              [0, 256])\n        hist_cb = cv.calcHist([image], [2], mask, self.bins,\n                              [0, 256])\n        hist_y = hist_y / np.sum(hist_y)\n        hist_cr = hist_cr / np.sum(hist_cr)\n        hist_cb = hist_cb / np.sum(hist_cb)\n\n        # 24 dimensions\n        return np.concatenate([hist_y, hist_cr, hist_cb], axis=0).reshape(-1)\n\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(__name__)\n\n    CLASSES = 5\n\n    images_list = []\n    masks_list = []\n    features_list = []\n    classes_list = []\n\n    hist = YCrCbHistogram([8])\n\n    s1 = time.time()\n    for i in range(0, CLASSES):\n        for imgpath in sorted(paths.list_images(str(i))):\n            if os.path.splitext(imgpath)[-1] == '.jpg':\n                images_list.append(imgpath)\n                classes_list.append(i)\n            elif os.path.splitext(imgpath)[-1] == '.png':\n                masks_list.append(imgpath)\n            else:\n                raise ValueError(\"type error...\")\n    s2 = time.time()\n    logger.info(f\"Time use: {s2 - s1} s\")\n\n    for image_path, mask_path in zip(images_list, masks_list):\n        # print(image_path, mask_path)\n        image = cv.imread(image_path)\n        mask = cv.imread(mask_path, 0)\n        features = hist.describe(image, mask)\n        # print(features)\n        features_list.append(features)\n\n    logger.info(f\"Time use: {time.time() - s2} s\")\n    logger.info(\"Data process ready...\")\n\n    # Resampling\n    sm = SMOTE(sampling_strategy='all', random_state=2019)\n    features_list, classes_list = sm.fit_resample(features_list, classes_list)\n\n    # Machine learning algorithm\n    # clf = MLPClassifier(solver='lbfgs', alpha=1e-5,\n    #                     hidden_layer_sizes=(8, ), random_state=2019)\n    clf = RandomForestClassifier(n_estimators=180, random_state=2019)\n    # kf = KFold(n_splits=CLASSES, random_state=2019, shuffle=True).\\\n    #     get_n_splits(features_list)\n    # scores = cross_val_score(clf, features_list, classes_list,\n    #                          scoring='accuracy', cv=kf)\n    # score = scores.mean()\n    # logger.info(f\"KFold score: {score}\")\n\n    # Split train and test dataset\n    X_train, X_test, y_train, y_test = train_test_split(\n        features_list, classes_list, test_size=0.2, random_state=2019)\n    y_pred = clf.fit(X_train, y_train).predict(X_test)\n\n    classify_report = classification_report(y_test, y_pred)\n    logger.info('\\n' + classify_report)\n\n    np.set_printoptions(precision=2)\n    plot_confusion_matrix(y_test, y_pred, classes=['0', '1',\n                                                   '2', '3', '4'], title='Confusion matrix')\n    plt.show()\n\n    # Save model\n    # https://blog.csdn.net/qiang12qiang12/article/details/81001839\n    # How to load model: \n    #   1. clf = joblib.load('models/histogram.pkl')\n    #   2. clf.predict(X_test)\n\n    # joblib.dump(clf, 'models/histogram.pkl')\n"
  },
  {
    "path": "experiments/cal_moments.py",
    "content": "# https://www.cnblogs.com/klchang/p/6512310.html\nfrom __future__ import print_function, division\n\nimport cv2 as cv\nimport numpy as np\nimport tqdm\nimport time\nimport os\nimport sys\nimport logging\nlogging.basicConfig(level=logging.INFO,\n                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nimport matplotlib.pyplot as plt\nfrom sklearn.externals import joblib\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom imblearn.over_sampling import SMOTE\n\nfrom utils import *\nfrom imutils import paths\n\n\ndef color_moments(image, mask, color_space):\n    \"\"\"\n    function: Color Moment Features\n    image: raw image\n    mask: image mask\n    color_space: 'rgb' or 'lab' or 'ycrcb' or 'hsv'\n    \"\"\"\n    assert image.shape[:2] == mask.shape\n    assert color_space.lower() in ['lab', 'rgb', 'ycrcb', 'hsv']\n\n    if color_space.lower() == 'rgb':\n        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n    elif color_space.lower() == 'hsv':\n        image = cv.cvtColor(image, cv.COLOR_BGR2HSV)\n    elif color_space.lower() == 'lab':\n        image = cv.cvtColor(image, cv.COLOR_BGR2LAB)\n    elif color_space.lower() == 'ycrcb':\n        image = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)\n    else:\n        raise ValueError(\"Color space error...\")\n\n    # Split image channels info\n    c1, c2, c3 = cv.split(image)\n    color_feature = []\n\n    # Only process mask != 0 channel region\n    c1 = c1[np.where(mask != 0)]\n    c2 = c2[np.where(mask != 0)]\n    c3 = c3[np.where(mask != 0)]\n\n    # Extract mean\n    mean_1 = np.mean(c1)\n    mean_2 = np.mean(c2)\n    mean_3 = np.mean(c3)\n\n    # Extract variance\n    variance_1 = np.std(c1)\n    variance_2 = np.std(c2)\n    variance_3 = np.std(c3)\n\n    # Extract skewness\n    skewness_1 = np.mean(np.abs(c1 - mean_1) ** 3) ** (1. / 3)\n    skewness_2 = np.mean(np.abs(c1 - mean_2) ** 3) ** (1. / 3)\n    skewness_3 = np.mean(np.abs(c1 - mean_3) ** 3) ** (1. / 3)\n\n    color_feature.extend(\n        [mean_1, mean_2, mean_3, variance_1, variance_2,\n            variance_3, skewness_1, skewness_2, skewness_3])\n\n    return color_feature\n\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(__name__)\n\n    CLASSES = 5\n\n    images_list = []\n    masks_list = []\n    features_list = []\n    classes_list = []\n\n    s1 = time.time()\n    for i in range(0, CLASSES):\n        for imgpath in sorted(paths.list_images(str(i))):\n            if os.path.splitext(imgpath)[-1] == '.jpg':\n                images_list.append(imgpath)\n                classes_list.append(int(i))\n            elif os.path.splitext(imgpath)[-1] == '.png':\n                masks_list.append(imgpath)\n            else:\n                raise ValueError(\"type error...\")\n    s2 = time.time()\n    logger.info(f\"Time use: {s2 - s1} s\")\n\n    for image_path, mask_path in tqdm.tqdm(zip(images_list, masks_list)):\n        image = cv.imread(image_path)\n        mask = cv.imread(mask_path, 0)\n        features = color_moments(image, mask, color_space='ycrcb')\n        features_list.append(features)\n\n    logger.info(f\"Time use: {time.time() - s2} s\")\n    logger.info(\"Data process ready...\")\n\n    # Resampling\n    sm = SMOTE(sampling_strategy='all', random_state=2019)\n    features_list, classes_list = sm.fit_resample(features_list, classes_list)\n\n    X_train, X_test, y_train, y_test = train_test_split(\n        features_list, classes_list, test_size=0.2, random_state=2019)\n\n    clf = RandomForestClassifier(n_estimators=180, random_state=2019)\n    y_pred = clf.fit(X_train, y_train).predict(X_test)\n    joblib.dump(clf, 'skinColor.pkl')\n\n    classify_report = classification_report(y_test, y_pred)\n    logger.info('\\n' + classify_report)\n\n    np.set_printoptions(precision=2)\n    plot_confusion_matrix(y_test, y_pred, classes=['0', '1',\n                                                   '2', '3', '4'], title='Confusion matrix')\n    plt.show()\n"
  },
  {
    "path": "experiments/cal_pca.py",
    "content": "# color-auto-correlogram\n# https://blog.csdn.net/u013066730/article/details/53609859\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport cv2 as cv\nimport sys\nimport os\nimport tqdm\nimport time\nimport csv\nimport pandas as pd\nfrom sklearn import svm\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.ensemble import RandomForestClassifier\nimport matplotlib.pyplot as plt\n\nimport logging\nlogging.basicConfig(level=logging.INFO,\n                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nfrom utils import *\nfrom imutils import paths\n\n\nclass RGBHistogram(Histogram):\n    '''RGB Histogram'''\n\n    def __init__(self, bins):\n        super().__init__(bins)\n\n    def describe(self, image, mask):\n        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n        hist = cv.calcHist([image], [0, 1, 2], mask,\n                           self.bins, [0, 256, 0, 256, 0, 256])\n        hist = hist / np.sum(hist)\n\n        # 512 dimensions\n        return hist.flatten()\n\n\nif __name__ == \"__main__\":\n\n    logger = logging.getLogger(__name__)\n\n    CLASSES = 5\n    K_ClUSTER = 15\n\n    images_list = []\n    masks_list = []\n    features_list = []\n    classes_list = []\n\n    s1 = time.time()\n    for i in range(0, CLASSES):\n        for imgpath in sorted(paths.list_images(str(i))):\n            if os.path.splitext(imgpath)[-1] == '.jpg':\n                images_list.append(imgpath)\n                classes_list.append(int(i))\n            elif os.path.splitext(imgpath)[-1] == '.png':\n                masks_list.append(imgpath)\n            else:\n                raise ValueError(\"type error...\")\n    s2 = time.time()\n    logger.info(f\"Time use: {s2 - s1} s\")\n\n    hist = RGBHistogram([8, 8, 8])\n\n    for image_path, mask_path in tqdm.tqdm(zip(images_list, masks_list)):\n        image = cv.imread(image_path)\n        mask = cv.imread(mask_path, 0)\n        features = hist.describe(image, mask)\n        features_list.append(features)\n\n    logger.info(f\"Time use: {time.time() - s2} s\")\n    logger.info(\"Data process ready...\")\n    \n    assert len(features_list) == len(classes_list)\n\n    # PCA Dimensionality Reduction\n    pca = PCA(n_components=K_ClUSTER, random_state=2019)\n    # pca.fit(features_list)\n    # logger.info(pca.explained_variance_ratio_)\n    newX = pca.fit_transform(features_list)\n\n    X_train, X_test, y_train, y_test = train_test_split(\n        newX, classes_list, test_size=0.2, random_state=2019)\n\n    clf = RandomForestClassifier(n_estimators=180, random_state=2019)\n    y_pred = clf.fit(X_train, y_train).predict(X_test)\n\n    classify_report = classification_report(y_test, y_pred)\n    logger.info('\\n' + classify_report)\n\n    np.set_printoptions(precision=2)\n    plot_confusion_matrix(y_test, y_pred, classes=['0', '1',\n                                                   '2', '3', '4'], title='Confusion matrix')\n    plt.show()\n"
  },
  {
    "path": "experiments/utils.py",
    "content": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes,\n                          normalize=False,\n                          title=None,\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    if not title:\n        if normalize:\n            title = 'Normalized confusion matrix'\n        else:\n            title = 'Confusion matrix, without normalization'\n\n    # Compute confusion matrix\n    cm = confusion_matrix(y_true, y_pred)\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n\n    fig, ax = plt.subplots()\n    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n    ax.figure.colorbar(im, ax=ax)\n    # We want to show all ticks...\n    ax.set(xticks=np.arange(cm.shape[1]),\n           yticks=np.arange(cm.shape[0]),\n           # ... and label them with the respective list entries\n           xticklabels=classes, yticklabels=classes,\n           title=title,\n           ylabel='True label',\n           xlabel='Predicted label')\n\n    # Rotate the tick labels and set their alignment.\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n             rotation_mode=\"anchor\")\n\n    # Loop over data dimensions and create text annotations.\n    fmt = '.2f' if normalize else 'd'\n    thresh = cm.max() / 2.\n    for i in range(cm.shape[0]):\n        for j in range(cm.shape[1]):\n            ax.text(j, i, format(cm[i, j], fmt),\n                    ha=\"center\", va=\"center\",\n                    color=\"white\" if cm[i, j] > thresh else \"black\")\n    fig.tight_layout()\n    return ax\n\n\nclass Histogram:\n    '''Histogram base class'''\n\n    def __init__(self, bins):\n        self.bins = bins\n\n    def describe(self, image, mask):\n        raise NotImplementedError\n"
  },
  {
    "path": "metric.py",
    "content": "import keras.backend as K\nimport tensorflow as tf\nfrom keras.utils.generic_utils import get_custom_objects\n\nCLS_NUM = 2  # should be modified according to class number\n\nSMOOTH = K.epsilon()\n\n# https: // blog.csdn.net/majinlei121/article/details/78965435\ndef mean_iou(y_true, y_pred, cls_num=CLS_NUM):\n    result = 0\n    nc = tf.cast(tf.shape(y_true)[-1], tf.float32)\n    for i in range(cls_num):\n        # nii = number of pixels of classe i predicted to belong to class i\n        nii = tf.reduce_sum(tf.round(tf.multiply(\n            y_true[:, :, :, i], y_pred[:, :, :, i])))\n        ti = tf.reduce_sum(y_true[:, :, :, i])  # number of pixels of class i\n        loc_sum = 0\n        for j in range(cls_num):\n            # number of pixels of classe j predicted to belong to class i\n            nji = tf.reduce_sum(tf.round(tf.multiply(\n                y_true[:, :, :, j], y_pred[:, :, :, i])))\n            loc_sum += nji\n        result += nii / (ti - nii + loc_sum)\n    return (1 / nc) * result\n\n\ndef mean_accuracy(y_true, y_pred, cls_num=CLS_NUM):\n    result = 0\n    nc = tf.cast(tf.shape(y_true)[-1], tf.float32)\n    for i in range(cls_num):\n        nii = tf.reduce_sum(tf.round(tf.multiply(\n            y_true[:, :, :, i], y_pred[:, :, :, i])))\n        ti = tf.reduce_sum(y_true[:, :, :, i])\n        if ti != 0:\n            result += (nii / ti)\n    return (1 / nc) * result\n\n\ndef frequency_weighted_iou(y_true, y_pred, cls_num=CLS_NUM):\n    result = 0\n    for i in range(cls_num):\n        nii = tf.reduce_sum(tf.round(tf.multiply(\n            y_true[:, :, :, i], y_pred[:, :, :, i])))\n        ti = tf.reduce_sum(y_true[:, :, :, i])\n        loc_sum = 0\n        for j in range(cls_num):\n            nji = tf.reduce_sum(tf.round(tf.multiply(\n                y_true[:, :, :, j], y_pred[:, :, :, i])))\n            loc_sum += nji\n        result += (loc_sum * nii) / (ti - nii + loc_sum)\n    sum_ti = tf.reduce_sum(y_true[:, :, :, :])\n    return (1 / sum_ti) * result\n\n\ndef pixel_accuracy(y_true, y_pred):\n    # nii = number of pixels of classe i predicted to belong to class i\n    sum_nii = tf.reduce_sum(tf.round(tf.multiply(\n        y_true[:, :, :, :], y_pred[:, :, :, :])))\n    # ti = number of pixels of class i\n    sum_ti = tf.reduce_sum(y_true[:, :, :, :])\n    return sum_nii / sum_ti\n\n\nget_custom_objects().update({\n    'pixel_accuracy': pixel_accuracy,\n    'frequency_weighted_iou': frequency_weighted_iou,\n    'mean_accuracy': mean_accuracy,\n    'mean_iou': mean_iou\n})\n"
  },
  {
    "path": "model/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 20:11\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    : \n# @File    : __init__.py\n# @Software: PyCharm"
  },
  {
    "path": "model/dfanet.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 19:56\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    : \n# @File    : dfanet.py\n# @Software: PyCharm\n\nfrom keras.layers import *\nfrom keras.models import Model\nimport keras.backend as K\n\n\ndef ConvBlock(inputs, n_filters, kernel_size=3, strides=1):\n    \"\"\"\n    Basic conv block for Encoder-Decoder\n    Apply successivly Convolution, BatchNormalization, ReLU nonlinearity\n    \"\"\"\n    net = Conv2D(n_filters, kernel_size, strides=strides,\n                 padding='same',\n                 kernel_initializer='he_normal',\n                 use_bias=False)(inputs)\n\n    net = BatchNormalization()(net)\n    net = Activation('relu')(net)\n    return net\n\n\ndef separable_res_block_deep(inputs, nb_filters, filter_size=3, strides=1, dilation=1, ix=0):\n    inputs = Activation('relu')(inputs)  # , name=prefix + '_sepconv1_act'\n\n    ip_nb_filter = K.get_variable_shape(inputs)[-1]\n    if ip_nb_filter != nb_filters or strides != 1:\n        residual = Conv2D(nb_filters, 1, strides=strides, use_bias=False)(inputs)\n        residual = BatchNormalization()(residual)\n    else:\n        residual = inputs\n\n    x = SeparableConv2D(nb_filters // 4, filter_size,\n                        dilation_rate=dilation,\n                        padding='same',\n                        use_bias=False,\n                        kernel_initializer='he_normal',\n                        )(inputs)\n    x = BatchNormalization()(x)  # name=prefix + '_sepconv1_bn'\n\n    x = Activation('relu')(x)  # , name=prefix + '_sepconv2_act'\n    x = SeparableConv2D(nb_filters // 4, filter_size,\n                        dilation_rate=dilation,\n                        padding='same',\n                        use_bias=False,\n                        kernel_initializer='he_normal',\n                        )(x)\n    x = BatchNormalization()(x)  # name=prefix + '_sepconv2_bn'\n    x = Activation('relu')(x)  # , name=prefix + '_sepconv3_act'\n    # if strides != 1:\n    x = SeparableConv2D(nb_filters, filter_size,\n                        strides=strides,\n                        dilation_rate=dilation,\n                        padding='same',\n                        use_bias=False,\n                        )(x)\n\n    x = BatchNormalization()(x)  # name=prefix + '_sepconv3_bn'\n    x = add([x, residual])\n    return x\n\n\ndef encoder(inputs, nb_filters, stage):\n    rep_nums = 0\n    if stage == 2 or stage == 4:\n        rep_nums = 4\n    elif stage == 3:\n        rep_nums = 6\n    x = separable_res_block_deep(inputs, nb_filters, strides=2)  # , ix = rand_nb + stage * 10\n    for i in range(rep_nums - 1):\n        x = separable_res_block_deep(x, nb_filters, strides=1)  # , ix = rand_nb + stage * 10 + i\n\n    return x\n\n\ndef AttentionRefinementModule(inputs):\n    # Global average pooling\n    nb_channels = K.get_variable_shape(inputs)[-1]\n    net = GlobalAveragePooling2D()(inputs)\n\n    net = Reshape((1, nb_channels))(net)\n    net = Conv1D(nb_channels, kernel_size=1,\n                 kernel_initializer='he_normal',\n                 )(net)\n    net = BatchNormalization()(net)\n    net = Activation('relu')(net)\n    net = Conv1D(nb_channels, kernel_size=1,\n                 kernel_initializer='he_normal',\n                 )(net)\n    net = BatchNormalization()(net)\n    net = Activation('sigmoid')(net)  # tf.sigmoid(net)\n\n    net = Multiply()([inputs, net])\n\n    return net\n\n\ndef xception_backbone(inputs, size_factor=2):\n    x = Conv2D(8, kernel_size=3, strides=2,\n               padding='same', use_bias=False)(inputs)\n    x = BatchNormalization()(x)\n    x = Activation('relu')(x)\n\n    x = encoder(x, int(16 * size_factor), 2)\n    x = encoder(x, int(32 * size_factor), 3)\n    x = encoder(x, int(64 * size_factor), 4)\n\n    x = AttentionRefinementModule(x)\n    return x\n\n\ndef DFANet(input_shape, cls_num=3, size_factor=2):\n    img_input = Input(input_shape)\n\n    x = Conv2D(8, kernel_size=5, strides=2,\n               padding='same', use_bias=False)(img_input)\n    x = BatchNormalization()(x)\n    levela_input = Activation('relu')(x)\n\n    enc2_a = encoder(levela_input, int(16 * size_factor), 2)\n\n    enc3_a = encoder(enc2_a, int(32 * size_factor), 3)\n\n    enc4_a = encoder(enc3_a, int(64 * size_factor), 4)\n\n    enc_attend_a = AttentionRefinementModule(enc4_a)\n\n    enc_upsample_a = UpSampling2D(size=4, interpolation='bilinear')(enc_attend_a)\n\n    levelb_input = Concatenate()([enc2_a, enc_upsample_a])\n    enc2_b = encoder(levelb_input, int(16 * size_factor), 2)\n\n    enc2_b_combine = Concatenate()([enc3_a, enc2_b])\n    enc3_b = encoder(enc2_b_combine, int(32 * size_factor), 3)\n\n    enc3_b_combine = Concatenate()([enc4_a, enc3_b])\n    enc4_b = encoder(enc3_b_combine, int(64 * size_factor), 4)\n\n    enc_attend_b = AttentionRefinementModule(enc4_b)\n\n    enc_upsample_b = UpSampling2D(size=4, interpolation='bilinear')(enc_attend_b)\n\n    levelc_input = Concatenate()([enc2_b, enc_upsample_b])\n    enc2_c = encoder(levelc_input, int(16 * size_factor), 2)\n\n    enc2_c_combine = Concatenate()([enc3_b, enc2_c])\n    enc3_c = encoder(enc2_c_combine, int(32 * size_factor), 3)\n\n    enc3_c_combine = Concatenate()([enc4_b, enc3_c])\n    enc4_c = encoder(enc3_c_combine, int(64 * size_factor), 4)\n\n    enc_attend_c = AttentionRefinementModule(enc4_c)\n\n    enc2_a_decoder = ConvBlock(enc2_a, 32, kernel_size=1)\n\n    enc2_b_decoder = ConvBlock(enc2_b, 32, kernel_size=1)\n    enc2_b_decoder = UpSampling2D(size=2, interpolation='bilinear')(enc2_b_decoder)\n\n    enc2_c_decoder = ConvBlock(enc2_c, 32, kernel_size=1)\n    enc2_c_decoder = UpSampling2D(size=4, interpolation='bilinear')(enc2_c_decoder)\n\n    decoder_front = Add()([enc2_a_decoder, enc2_b_decoder, enc2_c_decoder])\n    decoder_front = ConvBlock(decoder_front, 32, kernel_size=1)\n\n    att_a_decoder = ConvBlock(enc_attend_a, 32, kernel_size=1)\n    att_a_decoder = UpSampling2D(size=4, interpolation='bilinear')(att_a_decoder)\n\n    att_b_decoder = ConvBlock(enc_attend_b, 32, kernel_size=1)\n    att_b_decoder = UpSampling2D(size=8, interpolation='bilinear')(att_b_decoder)\n\n    att_c_decoder = ConvBlock(enc_attend_c, 32, kernel_size=1)\n    att_c_decoder = UpSampling2D(size=16, interpolation='bilinear')(att_c_decoder)\n\n    decoder_combine = Add()([decoder_front, att_a_decoder, att_b_decoder, att_c_decoder])\n\n    decoder_combine = ConvBlock(decoder_combine, cls_num * 2, kernel_size=1)\n\n    decoder_final = UpSampling2D(size=4, interpolation='bilinear')(decoder_combine)\n    output = Conv2D(cls_num, (1, 1), activation='softmax')(decoder_final)\n\n    return Model(img_input, output, name='DFAnet')\n\n\nif __name__ == '__main__':\n    from flops import get_flops\n\n    model = DFANet(input_shape=(256, 256, 3), cls_num=3, size_factor=2)\n    model.summary()\n\n    get_flops(model)\n"
  },
  {
    "path": "model/enet.py",
    "content": "# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 17:41\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    :\n# @File    : enet.py\n# @Software: PyCharm\n#\nfrom keras.layers import *\nfrom keras.models import Model\n\n\nclass Conv2DTransposeCustom(object):\n    \"\"\"Fixed output shape bug...\"\"\"\n\n    def __init__(self, filters, kernel_size, strides=(1, 1), padding='same'):\n        self.filters = filters\n        self.kernel_size = kernel_size\n        self.strides = strides\n        self.padding = padding\n\n    def __call__(self, layer):\n        out = Conv2DTranspose(self.filters, self.kernel_size, strides=self.strides, padding=self.padding)(layer)\n        if not isinstance(self.strides, tuple):\n            self.strides = (self.strides, self.strides)\n        out.set_shape((out.shape[0], layer.shape[1] * self.strides[0], layer.shape[2] * self.strides[1], out.shape[3]))\n        return out\n\n\ndef initial_block(inp, nb_filter=13, nb_row=3, nb_col=3, strides=(2, 2)):\n    conv = Conv2D(nb_filter, (nb_row, nb_col), padding='same', strides=strides)(inp)\n    max_pool = MaxPooling2D()(inp)\n    merged = concatenate([conv, max_pool], axis=3)\n    return merged\n\n\ndef bottleneck(inp, output, internal_scale=4, asymmetric=0, dilated=0, downsample=False, dropout_rate=0.1):\n    # main branch\n    internal = output // internal_scale\n    encoder = inp\n    # 1x1\n    input_stride = 2 if downsample else 1  # the 1st 1x1 projection is replaced with a 2x2 convolution when downsampling\n    encoder = Conv2D(internal, (input_stride, input_stride),\n                     # padding='same',\n                     strides=(input_stride, input_stride), use_bias=False)(encoder)\n    # Batch normalization + PReLU\n    encoder = BatchNormalization(momentum=0.1)(encoder)  # enet uses momentum of 0.1, keras default is 0.99\n    encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n    # conv\n    if not asymmetric and not dilated:\n        encoder = Conv2D(internal, (3, 3), padding='same')(encoder)\n    elif asymmetric:\n        encoder = Conv2D(internal, (1, asymmetric), padding='same', use_bias=False)(encoder)\n        encoder = Conv2D(internal, (asymmetric, 1), padding='same')(encoder)\n    elif dilated:\n        encoder = Conv2D(internal, (3, 3), dilation_rate=(dilated, dilated), padding='same')(encoder)\n    else:\n        raise (Exception('You shouldn\\'t be here'))\n\n    encoder = BatchNormalization(momentum=0.1)(encoder)  # enet uses momentum of 0.1, keras default is 0.99\n    encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n    # 1x1\n    encoder = Conv2D(output, (1, 1), use_bias=False)(encoder)\n\n    encoder = BatchNormalization(momentum=0.1)(encoder)  # enet uses momentum of 0.1, keras default is 0.99\n    encoder = SpatialDropout2D(dropout_rate)(encoder)\n\n    other = inp\n    # other branch\n    if downsample:\n        other = MaxPooling2D()(other)\n\n        other = Permute((1, 3, 2))(other)\n        pad_feature_maps = output - inp.get_shape().as_list()[3]\n        tb_pad = (0, 0)\n        lr_pad = (0, pad_feature_maps)\n        other = ZeroPadding2D(padding=(tb_pad, lr_pad))(other)\n        other = Permute((1, 3, 2))(other)\n\n    encoder = add([encoder, other])\n    encoder = PReLU(shared_axes=[1, 2])(encoder)\n\n    return encoder\n\n\ndef en_build(inp, dropout_rate=0.01):\n    enet = initial_block(inp)\n    enet = BatchNormalization(momentum=0.1)(enet)  # enet_unpooling uses momentum of 0.1, keras default is 0.99\n    enet = PReLU(shared_axes=[1, 2])(enet)\n    enet = bottleneck(enet, 64, downsample=True, dropout_rate=dropout_rate)  # bottleneck 1.0\n    for _ in range(4):\n        enet = bottleneck(enet, 64, dropout_rate=dropout_rate)  # bottleneck 1.i\n\n    enet = bottleneck(enet, 128, downsample=True)  # bottleneck 2.0\n    # bottleneck 2.x and 3.x\n    for _ in range(2):\n        enet = bottleneck(enet, 128)  # bottleneck 2.1\n        enet = bottleneck(enet, 128, dilated=2)  # bottleneck 2.2\n        enet = bottleneck(enet, 128, asymmetric=5)  # bottleneck 2.3\n        enet = bottleneck(enet, 128, dilated=4)  # bottleneck 2.4\n        enet = bottleneck(enet, 128)  # bottleneck 2.5\n        enet = bottleneck(enet, 128, dilated=8)  # bottleneck 2.6\n        enet = bottleneck(enet, 128, asymmetric=5)  # bottleneck 2.7\n        enet = bottleneck(enet, 128, dilated=16)  # bottleneck 2.8\n\n    return enet\n\n\n# decoder\ndef de_bottleneck(encoder, output, upsample=False, reverse_module=False):\n    internal = output // 4\n\n    x = Conv2D(internal, (1, 1), use_bias=False)(encoder)\n    x = BatchNormalization(momentum=0.1)(x)\n    x = Activation('relu')(x)\n    if not upsample:\n        x = Conv2D(internal, (3, 3), padding='same', use_bias=True)(x)\n    else:\n        x = Conv2DTransposeCustom(filters=internal, kernel_size=(3, 3), strides=(2, 2), padding='same')(x)\n    x = BatchNormalization(momentum=0.1)(x)\n    x = Activation('relu')(x)\n\n    x = Conv2D(output, (1, 1), padding='same', use_bias=False)(x)\n\n    other = encoder\n    if encoder.get_shape()[-1] != output or upsample:\n        other = Conv2D(output, (1, 1), padding='same', use_bias=False)(other)\n        other = BatchNormalization(momentum=0.1)(other)\n        if upsample and reverse_module is not False:\n            other = UpSampling2D(size=(2, 2))(other)\n\n    if upsample and reverse_module is False:\n        decoder = x\n    else:\n        x = BatchNormalization(momentum=0.1)(x)\n        decoder = add([x, other])\n        decoder = Activation('relu')(decoder)\n\n    return decoder\n\n\ndef de_build(encoder, nc):\n    enet = de_bottleneck(encoder, 64, upsample=True, reverse_module=True)  # bottleneck 4.0\n    enet = de_bottleneck(enet, 64)  # bottleneck 4.1\n    enet = de_bottleneck(enet, 64)  # bottleneck 4.2\n    enet = de_bottleneck(enet, 16, upsample=True, reverse_module=True)  # bottleneck 5.0\n    enet = de_bottleneck(enet, 16)  # bottleneck 5.1\n\n    enet = Conv2DTransposeCustom(filters=nc, kernel_size=(2, 2), strides=(2, 2), padding='same')(enet)\n    return enet\n\n\ndef ENet(input_shape, cls_num=3):\n    # Make sure the dimensions are multiples of 32\n    assert input_shape[0] % 32 == 0\n    assert input_shape[1] % 32 == 0\n    img_input = Input(input_shape)\n    enet = en_build(img_input)\n    enet = de_build(enet, cls_num)\n    enet = Activation('softmax')(enet)\n    return Model(img_input, enet)\n\n\nif __name__ == '__main__':\n    from flops import get_flops\n\n    model = ENet(input_shape=(256, 256, 3), cls_num=3)\n    # model.summary()\n\n    get_flops(model, True)\n"
  },
  {
    "path": "model/fast_scnn.py",
    "content": "import keras\nimport tensorflow as tf\n\n\ndef resize_image(image):\n    return tf.image.resize_images(image, (256, 256))\n\n\nclass Fast_SCNN:\n\n    def __init__(self, num_classes=3, input_shape=(256, 256, 3)):\n        self.classes = num_classes\n        self.input_shape = input_shape\n        self.height = input_shape[0]\n        self.width = input_shape[1]\n\n    def conv_block(self, inputs, conv_type, kernel, kernel_size, strides, padding='same', relu=True):\n        if conv_type == 'ds':\n            x = keras.layers.SeparableConv2D(kernel, kernel_size, padding=padding, strides=strides)(inputs)\n        else:\n            x = keras.layers.Conv2D(kernel, kernel_size, padding=padding, strides=strides)(inputs)\n\n        x = keras.layers.BatchNormalization()(x)\n\n        if relu:\n            x = keras.layers.ReLU()(x)\n\n        return x\n\n    def learning_to_downsample(self):\n        # Input Layer\n        self.input_layer = keras.layers.Input(shape=self.input_shape, name='input_layer')\n\n        self.lds_layer = self.conv_block(self.input_layer, 'conv', 32, (3, 3), strides=(2, 2))\n        self.lds_layer = self.conv_block(self.lds_layer, 'ds', 48, (3, 3), strides=(2, 2))\n        self.lds_layer = self.conv_block(self.lds_layer, 'ds', 64, (3, 3), strides=(2, 2))\n\n    def global_feature_extractor(self):\n        self.gfe_layer = self.bottleneck_block(self.lds_layer, 64, (3, 3), t=6, strides=2, n=3)\n        self.gfe_layer = self.bottleneck_block(self.gfe_layer, 96, (3, 3), t=6, strides=2, n=3)\n        self.gfe_layer = self.bottleneck_block(self.gfe_layer, 128, (3, 3), t=6, strides=1, n=3)\n        # self.gfe_layer = self.pyramid_pooling_block(self.gfe_layer, [2, 4, 6, 8])\n        self.gfe_layer = self.pyramid_pooling_block(self.gfe_layer, [1, 2, 4])\n\n    def _res_bottleneck(self, inputs, filters, kernel, t, s, r=False):\n        tchannel = keras.backend.int_shape(inputs)[-1] * t\n\n        x = self.conv_block(inputs, 'conv', tchannel, (1, 1), strides=(1, 1))\n\n        x = keras.layers.DepthwiseConv2D(kernel, strides=(s, s), depth_multiplier=1, padding='same')(x)\n        x = keras.layers.BatchNormalization()(x)\n        x = keras.layers.ReLU()(x)\n\n        x = self.conv_block(x, 'conv', filters, (1, 1), strides=(1, 1), padding='same', relu=False)\n\n        if r:\n            x = keras.layers.add([x, inputs])\n        return x\n\n    def bottleneck_block(self, inputs, filters, kernel, t, strides, n):\n        x = self._res_bottleneck(inputs, filters, kernel, t, strides)\n\n        for i in range(1, n):\n            x = self._res_bottleneck(x, filters, kernel, t, 1, True)\n\n        return x\n\n    def pyramid_pooling_block(self, input_tensor, bin_sizes):\n        concat_list = [input_tensor]\n        w = self.width // 32\n        h = self.height // 32\n\n        for bin_size in bin_sizes:\n            x = keras.layers.AveragePooling2D(pool_size=(bin_size, bin_size),\n                                              strides=(bin_size, bin_size))(input_tensor)\n            x = keras.layers.Conv2D(128, (3, 3), strides=2, padding='same')(x)\n            x = keras.layers.BatchNormalization()(x)\n            x = keras.layers.ReLU()(x)\n            x = keras.layers.UpSampling2D(size=(bin_size * 2, bin_size * 2))(x)\n            concat_list.append(x)\n\n        return keras.layers.concatenate(concat_list)\n\n    def feature_fusion(self):\n        ff_layer1 = self.conv_block(self.lds_layer, 'conv', 128, (1, 1), padding='same', strides=(1, 1), relu=False)\n\n        ff_layer2 = keras.layers.UpSampling2D((4, 4))(self.gfe_layer)\n        ff_layer2 = keras.layers.DepthwiseConv2D((3, 3), strides=(1, 1), depth_multiplier=1, padding='same')(ff_layer2)\n        ff_layer2 = keras.layers.BatchNormalization()(ff_layer2)\n        ff_layer2 = keras.layers.ReLU()(ff_layer2)\n        ff_layer2 = keras.layers.Conv2D(128, (1, 1), strides=1, padding='same', activation=None)(ff_layer2)\n\n        self.ff_final = keras.layers.add([ff_layer1, ff_layer2])\n        self.ff_final = keras.layers.BatchNormalization()(self.ff_final)\n        self.ff_final = keras.layers.ReLU()(self.ff_final)\n\n    def classifier(self):\n        self.classifier = keras.layers.SeparableConv2D(128, (3, 3), padding='same', strides=(1, 1),\n                                                       name='DSConv1_classifier')(self.ff_final)\n        self.classifier = keras.layers.BatchNormalization()(self.classifier)\n        self.classifier = keras.layers.ReLU()(self.classifier)\n\n        self.classifier = keras.layers.SeparableConv2D(128, (3, 3), padding='same', strides=(1, 1),\n                                                       name='DSConv2_classifier')(self.classifier)\n        self.classifier = keras.layers.BatchNormalization()(self.classifier)\n        self.classifier = keras.layers.ReLU()(self.classifier)\n\n        self.classifier = self.conv_block(self.classifier, 'conv', self.classes, (1, 1), strides=(1, 1), padding='same',\n                                          relu=False)\n        self.classifier = keras.layers.Lambda(lambda image: resize_image(image), name='Resize')(self.classifier)\n        self.classifier = keras.layers.Dropout(0.3)(self.classifier)\n\n    def activation(self, activation='softmax'):\n        x = keras.layers.Activation(activation,\n                                    name=activation)(self.classifier)\n        return x\n\n    def model(self, activation='softmax'):\n        self.learning_to_downsample()\n        self.global_feature_extractor()\n        self.feature_fusion()\n        self.classifier()\n        self.output_layer = self.activation(activation)\n\n        model = keras.Model(inputs=self.input_layer,\n                            outputs=self.output_layer,\n                            name='Fast_SCNN')\n        return model\n\n\nif __name__ == '__main__':\n    from flops import get_flops\n\n    model = Fast_SCNN(num_classes=3, input_shape=(256, 256, 3)).model()\n    model.summary()\n\n    get_flops(model)\n"
  },
  {
    "path": "model/flops.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 17:49\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    :\n# @File    : flops.py\n# @Software: PyCharm\n\n# https://github.com/ckyrkou/Keras_FLOP_Estimator\n\nimport keras.backend as K\n\n\ndef get_flops(model, table=False):\n    if table:\n        print('%25s | %16s | %16s | %16s | %16s | %6s | %6s' % (\n            'Layer Name', 'Input Shape', 'Output Shape', 'Kernel Size', 'Filters', 'Strides', 'FLOPS'))\n        print('-' * 170)\n\n    t_flops = 0\n    t_macc = 0\n\n    for l in model.layers:\n\n        o_shape, i_shape, strides, ks, filters = ['', '', ''], ['', '', ''], [1, 1], [0, 0], [0, 0]\n        flops = 0\n        macc = 0\n        name = l.name\n\n        factor = 1e9\n\n        if 'InputLayer' in str(l):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = i_shape\n\n        if 'Reshape' in str(l):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = l.output.get_shape()[1:4].as_list()\n\n        if 'Add' in str(l) or 'Maximum' in str(l) or 'Concatenate' in str(l):\n            i_shape = l.input[0].get_shape()[1:4].as_list() + [len(l.input)]\n            o_shape = l.output.get_shape()[1:4].as_list()\n            flops = (len(l.input) - 1) * i_shape[0] * i_shape[1] * i_shape[2]\n\n        if 'Average' in str(l) and 'pool' not in str(l):\n            i_shape = l.input[0].get_shape()[1:4].as_list() + [len(l.input)]\n            o_shape = l.output.get_shape()[1:4].as_list()\n            flops = len(l.input) * i_shape[0] * i_shape[1] * i_shape[2]\n\n        if 'BatchNormalization' in str(l):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = l.output.get_shape()[1:4].as_list()\n\n            bflops = 1\n            for i in range(len(i_shape)):\n                bflops *= i_shape[i]\n            flops /= factor\n\n        if 'Activation' in str(l) or 'activation' in str(l):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = l.output.get_shape()[1:4].as_list()\n            bflops = 1\n            for i in range(len(i_shape)):\n                bflops *= i_shape[i]\n            flops /= factor\n\n        if 'pool' in str(l) and ('Global' not in str(l)):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            strides = l.strides\n            ks = l.pool_size\n            flops = ((i_shape[0] / strides[0]) * (i_shape[1] / strides[1]) * (ks[0] * ks[1] * i_shape[2]))\n\n        if 'Flatten' in str(l):\n            i_shape = l.input.shape[1:4].as_list()\n            flops = 1\n            out_vec = 1\n            for i in range(len(i_shape)):\n                flops *= i_shape[i]\n                out_vec *= i_shape[i]\n            o_shape = flops\n            flops = 0\n\n        if 'Dense' in str(l):\n            print(l.input)\n            i_shape = l.input.shape[1:4].as_list()[0]\n            if i_shape is None:\n                i_shape = out_vec\n\n            o_shape = l.output.shape[1:4].as_list()\n            flops = 2 * (o_shape[0] * i_shape)\n            macc = flops / 2\n\n        if 'Padding' in str(l):\n            flops = 0\n\n        if 'Global' in str(l):\n            i_shape = l.input.get_shape()[1:4].as_list()\n            flops = ((i_shape[0]) * (i_shape[1]) * (i_shape[2]))\n            o_shape = [l.output.get_shape()[1:4].as_list(), 1, 1]\n            out_vec = o_shape\n\n        if 'Conv2D' in str(l) and 'DepthwiseConv2D' not in str(l) and 'SeparableConv2D' not in str(l):\n            strides = l.strides\n            ks = l.kernel_size\n            filters = l.filters\n            # if 'Conv2DTranspose' in str(l):\n            #     i_shape = list(K.int_shape(l.input)[1:4])\n            #     o_shape = list(K.int_shape(l.output)[1:4])\n            # else:\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = l.output.get_shape()[1:4].as_list()\n\n            if filters is None:\n                filters = i_shape[2]\n\n            flops = 2 * ((filters * ks[0] * ks[1] * i_shape[2]) * (\n                    (i_shape[0] / strides[0]) * (i_shape[1] / strides[1])))\n            macc = flops / 2\n\n        if 'Conv2D' in str(l) and 'DepthwiseConv2D' in str(l) and 'SeparableConv2D' not in str(l):\n            strides = l.strides\n            ks = l.kernel_size\n            filters = l.filters\n            i_shape = l.input.get_shape()[1:4].as_list()\n            o_shape = l.output.get_shape()[1:4].as_list()\n\n            if filters is None:\n                filters = i_shape[2]\n\n            flops = 2 * ((ks[0] * ks[1] * i_shape[2]) * ((i_shape[0] / strides[0]) * (\n                    i_shape[1] / strides[1]))) / factor\n            macc = flops / 2\n\n        t_macc += macc\n\n        t_flops += flops\n\n        if table:\n            print('%25s | %16s | %16s | %16s | %16s | %6s | %5.4f' % (\n                name, str(i_shape), str(o_shape), str(ks), str(filters), str(strides), flops))\n    t_flops = t_flops / factor\n\n    print('Total FLOPS (x 10^-9): %10.8f G' % (t_flops))\n    print('Total MACCs: %10.8f\\n' % (t_macc))\n\n    return\n"
  },
  {
    "path": "model/hlnet.py",
    "content": "# Fast-SCNN\n# HRNet\n# MobileNetv2-v3\n# ASPP\nfrom keras.layers import *\nfrom keras.models import Model\nfrom keras.utils import plot_model\n\nimport keras.backend as K\n\n\ndef _conv_block(inputs, filters, kernel, strides=1, padding='same', use_activation=False):\n    \"\"\"Convolution Block\n    This function defines a 2D convolution operation with BN and relu.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        strides: An integer or tuple/list of 2 integers,\n            specifying the strides of the convolution along the width and height.\n            Can be a single integer to specify the same value for\n            all spatial dimensions.\n    # Returns\n        Output tensor.\n    \"\"\"\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x = Conv2D(filters, kernel, padding=padding, strides=strides,\n               use_bias=False)(inputs)\n    x = BatchNormalization(axis=channel_axis)(x)\n\n    if use_activation:\n        x = Activation('relu')(x)\n\n    return x\n\n\ndef _bottleneck(inputs, filters, kernel, t, s, r=False):\n    \"\"\"Bottleneck\n    This function defines a basic bottleneck structure.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        t: Integer, expansion factor.\n            t is always applied to the input size.\n        s: An integer or tuple/list of 2 integers,specifying the strides\n            of the convolution along the width and height.Can be a single\n            integer to specify the same value for all spatial dimensions.\n        r: Boolean, Whether to use the residuals.\n    # Returns\n        Output tensor.\n    \"\"\"\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n    tchannel = K.int_shape(inputs)[channel_axis] * t\n\n    x = _conv_block(inputs, tchannel, (1, 1))\n\n    x = DepthwiseConv2D(kernel, strides=(\n        s, s), depth_multiplier=1, padding='same')(x)\n    x = BatchNormalization(axis=channel_axis)(x)\n    # relu6\n    x = ReLU(max_value=6)(x)\n\n    x = Conv2D(filters, (1, 1), strides=(1, 1), padding='same')(x)\n    x = BatchNormalization(axis=channel_axis)(x)\n\n    if r:\n        x = add([x, inputs])\n    return x\n\n\ndef _inverted_residual_block(inputs, filters, kernel, t, strides, n):\n    \"\"\"Inverted Residual Block\n    This function defines a sequence of 1 or more identical layers.\n    # Arguments\n        inputs: Tensor, input tensor of conv layer.\n        filters: Integer, the dimensionality of the output space.\n        kernel: An integer or tuple/list of 2 integers, specifying the\n            width and height of the 2D convolution window.\n        t: Integer, expansion factor.\n            t is always applied to the input size.\n        s: An integer or tuple/list of 2 integers,specifying the strides\n            of the convolution along the width and height.Can be a single\n            integer to specify the same value for all spatial dimensions.\n        n: Integer, layer repeat times.\n    # Returns\n        Output tensor.\n    \"\"\"\n    x = _bottleneck(inputs, filters, kernel, t, strides)\n\n    for i in range(1, n):\n        x = _bottleneck(x, filters, kernel, t, 1, True)\n\n    return x\n\n\ndef _depthwise_separable_block(inputs, kernel, strides, padding='same', depth_multiplier=1):\n    '''Depth separable point convolution module'''\n    channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n\n    x = DepthwiseConv2D(kernel_size=kernel, strides=strides, padding=padding,\n                        depth_multiplier=depth_multiplier)(inputs)\n    x = BatchNormalization(axis=channel_axis)(x)\n    return Activation('relu')(x)\n\n\ndef HLNet(input_shape, cls_num=3):\n    \"\"\"Higt-Low Resolution Information fusion Network\"\"\"\n    # input_shape: input image shape\n    # cls_num: output class number\n    inputs = Input(input_shape)\n    # Step 1: Feature dimension drops to 1/4\n    x = _conv_block(inputs, 32, (3, 3), strides=2, use_activation=True)\n    x = _depthwise_separable_block(x, (3, 3), strides=2, depth_multiplier=2)\n    x = _depthwise_separable_block(x, (3, 3), strides=2)\n\n    # step 2:\n    x21 = _inverted_residual_block(\n        x, 64, kernel=(3, 3), t=6, strides=1, n=3\n    )\n    x22 = _inverted_residual_block(\n        x, 96, kernel=(3, 3), t=6, strides=2, n=3\n    )\n    x23 = _inverted_residual_block(\n        x, 128, kernel=(3, 3), t=6, strides=4, n=3\n    )\n\n    # step 3:\n    x31_t1 = x21\n    x31_t2 = UpSampling2D(interpolation='bilinear')(\n        _conv_block(x22, 64, (1, 1), use_activation=True))\n    x31_t3 = UpSampling2D(size=(4, 4), interpolation='bilinear')(\n        _conv_block(x23, 64, (1, 1), use_activation=True))\n    x31 = Add()([x31_t1, x31_t2, x31_t3])\n\n    x32_t1 = _conv_block(x21, 96, (1, 1), strides=2, use_activation=True)\n    x32_t2 = _conv_block(x22, 96, (1, 1), use_activation=True)\n    x32_t3 = UpSampling2D(interpolation='bilinear')(\n        _conv_block(x23, 96, (1, 1), use_activation=True))\n    x32 = Add()([x32_t1, x32_t2, x32_t3])\n\n    x33_t1 = _conv_block(x21, 128, (1, 1), strides=4, use_activation=True)\n    x33_t2 = _conv_block(x22, 128, (1, 1), strides=2, use_activation=True)\n    x33_t3 = _conv_block(x23, 128, (1, 1), use_activation=True)\n    x33 = Add()([x33_t1, x33_t2, x33_t3])\n\n    # step 4:\n    x41 = _conv_block(x33, 96, (1, 1))\n    x42 = UpSampling2D(interpolation='bilinear')(x41)\n    x43 = Concatenate()([x42, x32])\n    x44 = _conv_block(x43, 64, (1, 1))\n    x45 = UpSampling2D(interpolation='bilinear')(x44)\n    x46 = Concatenate()([x45, x31])\n\n    # step 5: FFM module in BiSeNet\n    x50 = _conv_block(x46, 64, (3, 3))\n    x51 = AveragePooling2D(pool_size=(1, 1))(x50)\n    x52 = Conv2D(64, (1, 1), use_bias=False, activation='relu')(x51)\n    x53 = Conv2D(64, (1, 1), use_bias=False, activation='sigmoid')(x52)\n    x54 = Multiply()([x53, x50])\n    x55 = Add()([x50, x54])\n\n    # step6:\n    x61 = Conv2D(32, (3, 3), padding='same', dilation_rate=2)(x55)\n    x62 = Conv2D(32, (3, 3), padding='same', dilation_rate=4)(x55)\n    x63 = Conv2D(32, (3, 3), padding='same', dilation_rate=8)(x55)\n    x64 = Add()([x61, x62, x63])\n    # x61 = _conv_block(x62, cls_num, (1, 1), use_activation=False)\n    x65 = UpSampling2D(size=(8, 8), interpolation='bilinear')(x64)\n    x66 = _conv_block(x65, cls_num, (1, 1), use_activation=False)\n    out = Activation('softmax')(x66)\n\n    return Model(inputs, out)\n\n\nif __name__ == \"__main__\":\n    from flops import get_flops\n\n    # Testing network design\n    model = HLNet(input_shape=(256, 256, 3), cls_num=3)\n    model.summary()\n\n    get_flops(model)\n"
  },
  {
    "path": "model/lednet.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 17:42\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    : \n# @File    : lednet.py\n# @Software: PyCharm\n\nfrom keras import layers, models\nimport tensorflow as tf\n\n\nclass LEDNet:\n    def __init__(self, groups, classes, input_shape):\n        self.groups = groups\n        self.classes = classes\n        self.input_shape = input_shape\n\n    def ss_bt(self, x, dilation, strides=(1, 1), padding='same'):\n        x1, x2 = self.channel_split(x)\n        filters = (int(x.shape[-1]) // self.groups)\n        x1 = layers.Conv2D(filters, kernel_size=(3, 1), strides=strides, padding=padding)(x1)\n        x1 = layers.Activation('relu')(x1)\n        x1 = layers.Conv2D(filters, kernel_size=(1, 3), strides=strides, padding=padding)(x1)\n        x1 = layers.BatchNormalization()(x1)\n        x1 = layers.Activation('relu')(x1)\n        x1 = layers.Conv2D(filters, kernel_size=(3, 1), strides=strides, padding=padding, dilation_rate=(dilation, 1))(\n            x1)\n        x1 = layers.Activation('relu')(x1)\n        x1 = layers.Conv2D(filters, kernel_size=(1, 3), strides=strides, padding=padding, dilation_rate=(1, dilation))(\n            x1)\n        x1 = layers.BatchNormalization()(x1)\n        x1 = layers.Activation('relu')(x1)\n\n        x2 = layers.Conv2D(filters, kernel_size=(1, 3), strides=strides, padding=padding)(x2)\n        x2 = layers.Activation('relu')(x2)\n        x2 = layers.Conv2D(filters, kernel_size=(3, 1), strides=strides, padding=padding)(x2)\n        x2 = layers.BatchNormalization()(x2)\n        x2 = layers.Activation('relu')(x2)\n        x2 = layers.Conv2D(filters, kernel_size=(1, 3), strides=strides, padding=padding, dilation_rate=(1, dilation))(\n            x2)\n        x2 = layers.Activation('relu')(x2)\n        x2 = layers.Conv2D(filters, kernel_size=(3, 1), strides=strides, padding=padding, dilation_rate=(dilation, 1))(\n            x2)\n        x2 = layers.BatchNormalization()(x2)\n        x2 = layers.Activation('relu')(x2)\n        x_concat = layers.concatenate([x1, x2], axis=-1)\n        x_add = layers.add([x, x_concat])\n        output = self.channel_shuffle(x_add)\n        return output\n\n    def channel_shuffle(self, x):\n        n, h, w, c = x.shape.as_list()\n        x_reshaped = layers.Reshape([h, w, self.groups, int(c // self.groups)])(x)\n        x_transposed = layers.Permute((1, 2, 4, 3))(x_reshaped)\n        output = layers.Reshape([h, w, c])(x_transposed)\n        return output\n\n    def channel_split(self, x):\n        def splitter(y):\n            # keras Lambda saving bug!!!\n            # x_left = layers.Lambda(lambda y: y[:, :, :, :int(int(y.shape[-1]) // self.groups)])(x)\n            # x_right = layers.Lambda(lambda y: y[:, :, :, int(int(y.shape[-1]) // self.groups):])(x)\n            # return x_left, x_right\n            return tf.split(y, num_or_size_splits=self.groups, axis=-1)\n\n        return layers.Lambda(lambda y: splitter(y))(x)\n\n    def down_sample(self, x, filters):\n        x_filters = int(x.shape[-1])\n        x_conv = layers.Conv2D(filters - x_filters, kernel_size=3, strides=(2, 2), padding='same')(x)\n        x_pool = layers.MaxPool2D()(x)\n        x = layers.concatenate([x_conv, x_pool], axis=-1)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation('relu')(x)\n        return x\n\n    def apn_module(self, x):\n\n        def right(x):\n            x = layers.AveragePooling2D()(x)\n            x = layers.Conv2D(self.classes, kernel_size=1, padding='same')(x)\n            x = layers.BatchNormalization()(x)\n            x = layers.Activation('relu')(x)\n            x = layers.UpSampling2D(interpolation='bilinear')(x)\n            return x\n\n        def conv(x, filters, kernel_size, stride):\n            x = layers.Conv2D(filters, kernel_size=kernel_size, strides=(stride, stride), padding='same')(x)\n            x = layers.BatchNormalization()(x)\n            x = layers.Activation('relu')(x)\n            return x\n\n        x_7 = conv(x, int(x.shape[-1]), 7, stride=2)\n        x_5 = conv(x_7, int(x.shape[-1]), 5, stride=2)\n        x_3 = conv(x_5, int(x.shape[-1]), 3, stride=2)\n\n        x_3_1 = conv(x_3, self.classes, 3, stride=1)\n        x_3_1_up = layers.UpSampling2D(interpolation='bilinear')(x_3_1)\n        x_5_1 = conv(x_5, self.classes, 5, stride=1)\n        x_3_5 = layers.add([x_5_1, x_3_1_up])\n        x_3_5_up = layers.UpSampling2D(interpolation='bilinear')(x_3_5)\n        x_7_1 = conv(x_7, self.classes, 3, stride=1)\n        x_3_5_7 = layers.add([x_7_1, x_3_5_up])\n        x_3_5_7_up = layers.UpSampling2D(interpolation='bilinear')(x_3_5_7)\n\n        x_middle = conv(x, self.classes, 1, stride=1)\n        x_middle = layers.multiply([x_3_5_7_up, x_middle])\n\n        x_right = right(x)\n        x_middle = layers.add([x_middle, x_right])\n        return x_middle\n\n    def encoder(self, x):\n        x = self.down_sample(x, filters=32)\n        for _ in range(3):\n            x = self.ss_bt(x, dilation=1)\n\n        x = self.down_sample(x, filters=64)\n        for _ in range(2):\n            x = self.ss_bt(x, dilation=1)\n\n        x = self.down_sample(x, filters=128)\n\n        dilation_rate = [1, 2, 5, 9, 2, 5, 9, 17]\n        for dilation in dilation_rate:\n            x = self.ss_bt(x, dilation=dilation)\n        return x\n\n    def decoder(self, x):\n        x = self.apn_module(x)\n        x = layers.UpSampling2D(size=8, interpolation='bilinear')(x)\n        x = layers.Conv2D(self.classes, kernel_size=3, padding='same')(x)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation('softmax')(x)\n        return x\n\n    def model(self):\n        inputs = layers.Input(shape=self.input_shape)\n        encoder_out = self.encoder(inputs)\n        output = self.decoder(encoder_out)\n        return models.Model(inputs, output)\n\n\nif __name__ == '__main__':\n    from flops import get_flops\n\n    model = LEDNet(2, 3, (256, 256, 3)).model()\n    model.summary()\n\n    get_flops(model)\n"
  },
  {
    "path": "model/mobilenet.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2020/3/27 17:43\n# @Author  : JackyLUO\n# @E-mail  : lingluo@stumail.neu.edu.cn\n# @Site    : \n# @File    : mobilenet.py\n# @Software: PyCharm\n\nfrom keras.models import *\nfrom keras.layers import *\n\n\ndef conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)):\n    filters = int(filters * alpha)\n    x = ZeroPadding2D(padding=(1, 1), name='conv1_pad')(inputs)\n    x = Conv2D(filters, kernel, padding='valid', use_bias=False, strides=strides, name='conv1')(x)\n    x = BatchNormalization(axis=3, name='conv1_bn')(x)\n    return ReLU(6, name='conv1_relu')(x)\n\n\ndef depthwise_conv_block(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1):\n    pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n    x = ZeroPadding2D((1, 1), name='conv_pad_%d' % block_id)(inputs)\n    x = DepthwiseConv2D((3, 3), padding='valid', depth_multiplier=depth_multiplier, strides=strides, use_bias=False,\n                        name='conv_dw_%d' % block_id)(x)\n    x = BatchNormalization(axis=3, name='conv_dw_%d_bn' % block_id)(x)\n    x = ReLU(6, name='conv_dw_%d_relu' % block_id)(x)\n    x = Conv2D(pointwise_conv_filters, (1, 1), padding='same', use_bias=False, strides=(1, 1),\n               name='conv_pw_%d' % block_id)(x)\n    x = BatchNormalization(axis=3, name='conv_pw_%d_bn' % block_id)(x)\n    return ReLU(6, name='conv_pw_%d_relu' % block_id)(x)\n\n\ndef MobileNet(input_shape, cls_num, alpha=0.5):\n    inputs = Input(input_shape)\n    x = conv_block(inputs, 16, alpha, strides=(2, 2))\n    x = depthwise_conv_block(x, 16, alpha, 6, block_id=1)\n    f1 = x\n    x = depthwise_conv_block(x, 32, alpha, 6, strides=(2, 2), block_id=2)\n    x = depthwise_conv_block(x, 32, alpha, 6, block_id=3)\n    f2 = x\n    x = depthwise_conv_block(x, 64, alpha, 6, strides=(2, 2), block_id=4)\n    x = depthwise_conv_block(x, 64, alpha, 6, block_id=5)\n    f3 = x\n    x = depthwise_conv_block(x, 128, alpha, 6, strides=(2, 2), block_id=6)\n    x = depthwise_conv_block(x, 128, alpha, 6, block_id=7)\n    x = depthwise_conv_block(x, 128, alpha, 6, block_id=8)\n    x = depthwise_conv_block(x, 128, alpha, 6, block_id=9)\n    x = depthwise_conv_block(x, 128, alpha, 6, block_id=10)\n    x = depthwise_conv_block(x, 128, alpha, 6, block_id=11)\n\n    o = x\n    o = Conv2D(128, (3, 3), activation='relu', padding='same')(o)\n    o = BatchNormalization()(o)\n    # decode\n    o = UpSampling2D((2, 2))(o)\n    o = concatenate([o, f3], axis=-1)\n    o = Conv2D(64, (3, 3), padding='same')(o)\n    o = BatchNormalization()(o)\n\n    o = UpSampling2D((2, 2))(o)\n    o = concatenate([o, f2], axis=-1)\n    o = Conv2D(32, (3, 3), padding='same')(o)\n    o = BatchNormalization()(o)\n\n    o = UpSampling2D((2, 2))(o)\n    o = concatenate([o, f1], axis=-1)\n\n    o = Conv2D(16, (3, 3), padding='same')(o)\n    o = BatchNormalization()(o)\n\n    o = Conv2D(cls_num, (3, 3), padding='same')(o)\n    o = UpSampling2D((2, 2))(o)\n    o = Activation('softmax')(o)\n\n    return Model(inputs, o)\n\n\nif __name__ == '__main__':\n    from flops import get_flops\n\n    model = MobileNet(input_shape=(256, 256, 3), cls_num=3)\n    model.summary()\n\n    get_flops(model, True)\n"
  },
  {
    "path": "pipline_test.py",
    "content": "from __future__ import print_function, division\n\nfrom keras.models import load_model\nimport numpy as np\nimport time\nimport cv2 as cv\nimport os\nimport sys\nimport argparse\nfrom sklearn.externals import joblib\nimport matplotlib.pyplot as plt\nfrom keras.applications.imagenet_utils import preprocess_input as pinput\nfrom keras import backend as K\n\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nfrom segmentation_models.backbones import get_preprocessing\nfrom model.hlnet import HLRNet\nfrom model.hrnet import HRNet\nfrom segmentation_models import PSPNet, Unet, FPN, Linknet\nfrom mtcnn.mtcnn import MTCNN\nfrom metric import *\nfrom imutils import paths\n\nIMG_SIZE = None\n\n\ndef color_moments(image, mask, color_space):\n    \"\"\"\n    function: Color Moment Features\n    image: raw image\n    mask: image mask\n    color_space: 'rgb' or 'lab' or 'ycrcb' or 'hsv'\n    \"\"\"\n    assert image.shape[:2] == mask.shape\n    assert color_space.lower() in ['lab', 'rgb', 'ycrcb', 'hsv']\n\n    if color_space.lower() == 'rgb':\n        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n    elif color_space.lower() == 'hsv':\n        image = cv.cvtColor(image, cv.COLOR_BGR2HSV)\n    elif color_space.lower() == 'lab':\n        image = cv.cvtColor(image, cv.COLOR_BGR2LAB)\n    elif color_space.lower() == 'ycrcb':\n        image = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)\n    else:\n        raise ValueError(\"Color space error...\")\n\n    # Split image channels info\n    c1, c2, c3 = cv.split(image)\n    color_feature = []\n\n    # Only process mask != 0 channel region\n    c1 = c1[np.where(mask != 0)]\n    c2 = c2[np.where(mask != 0)]\n    c3 = c3[np.where(mask != 0)]\n\n    # Extract mean\n    mean_1 = np.mean(c1)\n    mean_2 = np.mean(c2)\n    mean_3 = np.mean(c3)\n\n    # Extract variance\n    variance_1 = np.std(c1)\n    variance_2 = np.std(c2)\n    variance_3 = np.std(c3)\n\n    # Extract skewness\n    skewness_1 = np.mean(np.abs(c1 - mean_1) ** 3) ** (1. / 3)\n    skewness_2 = np.mean(np.abs(c1 - mean_2) ** 3) ** (1. / 3)\n    skewness_3 = np.mean(np.abs(c1 - mean_3) ** 3) ** (1. / 3)\n\n    color_feature.extend(\n        [mean_1, mean_2, mean_3, variance_1, variance_2,\n            variance_3, skewness_1, skewness_2, skewness_3])\n\n    return color_feature\n\n\ndef _result_map_toimg(result_map):\n    '''show result map'''\n    img = np.zeros((IMG_SIZE, IMG_SIZE, 3), dtype=np.uint8)\n\n    argmax_id = np.argmax(result_map, axis=-1)\n    background = (argmax_id == 0)\n    skin = (argmax_id == 1)\n    hair = (argmax_id == 2)\n\n    img[:, :, 0] = np.where(background, 255, 0)\n    img[:, :, 1] = np.where(skin, 255, 0)\n    img[:, :, 2] = np.where(hair, 255, 0)\n\n    return img\n\n\ndef imcrop(img, x1, y1, x2, y2):\n    if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:\n        img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)\n    return img[y1:y2, x1:x2, :]\n\n\ndef pad_img_to_fit_bbox(img, x1, x2, y1, y2):\n    img = cv.copyMakeBorder(img, - min(0, y1), max(y2 - img.shape[0], 0),\n                            -min(0, x1), max(x2 - img.shape[1], 0), cv.BORDER_REPLICATE)\n    y2 += -min(0, y1)\n    y1 += -min(0, y1)\n    x2 += -min(0, x1)\n    x1 += -min(0, x1)\n    return img, x1, x2, y1, y2\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--image_size\", '-is',\n                        help=\"size of image\", type=int, default=224)\n    parser.add_argument(\"--backbone\", '-bb',\n                        help=\"backbone of image\", type=str, default='seresnet18')\n    parser.add_argument(\"--model_path\", '-mp',\n                        help=\"the path of model\", type=str,\n                        default='./checkpoints/CelebA/HLNet/model-222-0.159.h5')\n    parser.add_argument(\"--margin\",\n                        help=\"margin of image\", type=float, default=0.3)\n    parser.add_argument('--use_design', action='store_false')\n    args = parser.parse_args()\n\n    IMG_SIZE = args.image_size\n    MODEL_PATH = args.model_path\n    BACKBONE = args.backbone\n    USE_DESIGN = args.use_design\n\n    detector = MTCNN()\n    clf = joblib.load('./experiments/skinGrade/skinColor.pkl')\n    model = load_model(MODEL_PATH, custom_objects={'mean_accuracy': mean_accuracy,\n                                                   'mean_iou': mean_iou,\n                                                   'frequency_weighted_iou': frequency_weighted_iou,\n                                                   'pixel_accuracy': pixel_accuracy})\n    colorHue = ['Ivory white', 'Porcelain white',\n                'natural color', 'Yellowish', 'Black']\n\n    for img_path in paths.list_images(\"./data/Testing\"):\n        t = time.time()\n\n        org_img = cv.imread(img_path)\n        try:\n            org_img.shape\n        except:\n            raise ValueError(\"Reading image error...\")\n\n        org_img_rgb = org_img[:, :, ::-1] # RGB\n        detected = detector.detect_faces(org_img_rgb)\n\n        if len(detected) != 1:\n            print(\"[INFO] multi faces or no face...\")\n            continue\n\n        d = detected[0]['box']\n        x1, y1, x2, y2, w, h = d[0], d[1], d[0] + d[2], d[1] + d[3], d[2], d[3]\n        xw1 = int(x1 - args.margin * w)\n        yw1 = int(y1 - args.margin * h)\n        xw2 = int(x2 + args.margin * w)\n        yw2 = int(y2 + args.margin * h)\n        cropped_img = imcrop(org_img, xw1, yw1, xw2, yw2)\n        o_h, o_w, _ = cropped_img.shape\n\n        cropped_img_resize = cv.resize(cropped_img, (IMG_SIZE, IMG_SIZE))\n        img = cropped_img_resize[np.newaxis, :]\n\n\n        # only subtract mean value\n        img = pinput(img)\n\n        result_map = model.predict(img)[0]\n        mask = _result_map_toimg(result_map)\n        mask = cv.resize(mask, (o_w, o_h))\n\n        # Face channel\n        mask_face = mask[:, :, 1]\n        features = color_moments(cropped_img, mask_face, color_space='ycrcb')\n        features = np.array(features, np.float32)[np.newaxis, :]\n        skinHue = colorHue[clf.predict(features)[0]]\n\n        cv.rectangle(org_img, (x1, y1), (x2, y2), (255, 0, 0), 2)\n        cv.putText(org_img, 'Color: {}'.format(skinHue), (x1, y1+30),\n                    cv.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 1)\n        print(time.time() - t)  # testing time\n        cv.imshow(\"image\", org_img)\n        cv.waitKey(-1)\n\n"
  },
  {
    "path": "test.py",
    "content": "from __future__ import print_function, division\n\nfrom keras.models import load_model\nfrom keras.applications.imagenet_utils import preprocess_input as pinput\n\nimport cv2 as cv\nimport numpy as np\nimport os\nimport argparse\nfrom metric import *\nimport glob\nfrom model.fast_scnn import resize_image\nfrom segmentation_models.losses import *\n\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\nimport tensorflow as tf\n\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nIMG_SIZE = None\n\n\ndef vis_parsing_maps(im, parsing_anno, data_name):\n    part_colors = [[255, 255, 255], [0, 255, 0], [255, 0, 0]]\n\n    if data_name == 'figaro1k':\n        part_colors = [[255, 255, 255], [255, 0, 0]]\n\n    im = np.array(im)\n    vis_im = im.copy().astype(np.uint8)\n    vis_parsing_anno_color = np.zeros(\n        (parsing_anno.shape[0], parsing_anno.shape[1], 3))\n\n    for pi in range(len(part_colors)):\n        index = np.where(parsing_anno == pi)\n        vis_parsing_anno_color[index[0], index[1], :] = part_colors[pi]\n    vis_parsing_anno_color = vis_parsing_anno_color.astype(np.uint8)\n\n    # Guided filter\n    # vis_parsing_anno_color = cv.ximgproc.guidedFilter(\n    #     guide=vis_im, src=vis_parsing_anno_color, radius=4, eps=50, dDepth=-1)\n    vis_im = cv.addWeighted(vis_im, 0.7, vis_parsing_anno_color, 0.3, 0)\n\n    return vis_im\n\n\nif __name__ == '__main__':\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--image_size\",\n                        help=\"size of image\", type=int, default=256)\n    parser.add_argument(\"--model_path\",\n                        help=\"the path of model\", type=str,\n                        default='./weights/celebhair/exper/fastscnn/model.h5')\n    args = parser.parse_args()\n\n    IMG_SIZE = args.image_size\n    MODEL_PATH = args.model_path\n\n    if MODEL_PATH.split('/')[-2] == 'lednet':\n        from model.lednet import LEDNet\n\n        model = LEDNet(2, 3, (256, 256, 3)).model()\n        model.load_weights(MODEL_PATH)\n\n    else:\n        model = load_model(MODEL_PATH, custom_objects={'mean_accuracy': mean_accuracy,\n                                                       'mean_iou': mean_iou,\n                                                       'frequency_weighted_iou': frequency_weighted_iou,\n                                                       'pixel_accuracy': pixel_accuracy,\n                                                       'categorical_crossentropy_plus_dice_loss': cce_dice_loss,\n                                                       'resize_image': resize_image})\n\n    data_name = MODEL_PATH.split('/')[2]\n\n    for img_path in glob.glob(os.path.join(\"./demo\", data_name, \"*.jpg\")):\n        img_basename = os.path.basename(img_path)\n        name = os.path.splitext(img_basename)[0]\n\n        org_img = cv.imread(img_path)\n        try:\n            h, w, _ = org_img.shape\n        except:\n            raise IOError(\"Reading image error...\")\n\n        img_resize = cv.resize(org_img, (IMG_SIZE, IMG_SIZE))\n        img = img_resize[np.newaxis, :]\n        # pre-processing\n        img = pinput(img)\n\n        result_map = np.argmax(model.predict(img)[0], axis=-1)\n        out = vis_parsing_maps(img_resize, result_map, data_name)\n        out = cv.resize(out, (w, h), interpolation=cv.INTER_NEAREST)\n\n        cv.imwrite(os.path.join(\"./demo\", data_name, \"{}.png\").format(name), out)\n"
  },
  {
    "path": "train.py",
    "content": "import argparse\nfrom data_loader import HairGenerator\nfrom keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard, LearningRateScheduler\nimport os\nimport warnings\nfrom keras import optimizers\nfrom keras.regularizers import l2\nfrom metric import *\nfrom segmentation_models.losses import *\nimport numpy as np\n\nfrom albumentations import *\nfrom model.hlnet import HLNet\nfrom model.dfanet import DFANet\nfrom model.enet import ENet\nfrom model.lednet import LEDNet\nfrom model.mobilenet import MobileNet\nfrom model.fast_scnn import Fast_SCNN\n\nwarnings.filterwarnings(\"ignore\")\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\nimport tensorflow as tf\n\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--batch_size\", '-b',\n                    help=\"batch size\", type=int, default=64)\nparser.add_argument(\"--image_size\", '-i',\n                    help=\"image size\", type=int, default=256)\nparser.add_argument(\"--backbone\", '-bb',\n                    help=\"backbone of the network\", type=str, default=None)\nparser.add_argument(\"--epoches\", '-e', help=\"epoch size\",\n                    type=int, default=150)\nparser.add_argument(\"--model_name\", help=\"model's name\",\n                    choices=['hlnet', 'fastscnn', 'lednet', 'dfanet', 'enet', 'mobilenet'],\n                    type=str, default='hlnet')\nparser.add_argument(\"--learning_rate\", help=\"learning rate\", type=float, default=2.5e-3)\nparser.add_argument(\"--checkpoints\",\n                    help=\"where is the checkpoint\", type=str, default='./weights')\nparser.add_argument(\"--class_number\",\n                    help=\"number of output\", type=int, default=3)\nparser.add_argument(\"--data_dir\",\n                    help=\"path of dataset\", type=str, default='./data/CelebA')\nargs = parser.parse_args()\n\n\ndef get_model(name):\n    if name == 'hlnet':\n        model = HLNet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    elif name == 'fastscnn':\n        model = Fast_SCNN(num_classes=CLS_NUM, input_shape=(IMG_SIZE, IMG_SIZE, 3)).model()\n    elif name == 'lednet':\n        model = LEDNet(groups=2, classes=CLS_NUM, input_shape=(IMG_SIZE, IMG_SIZE, 3)).model()\n    elif name == 'dfanet':\n        model = DFANet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM, size_factor=2)\n    elif name == 'enet':\n        model = ENet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    elif name == 'mobilenet':\n        model = MobileNet(input_shape=(IMG_SIZE, IMG_SIZE, 3), cls_num=CLS_NUM)\n    else:\n        raise NameError(\"No corresponding model...\")\n\n    return model\n\n\nclass PolyDecay:\n    '''Exponential decay strategy implementation'''\n\n    def __init__(self, initial_lr, power, n_epochs):\n        self.initial_lr = initial_lr\n        self.power = power\n        self.n_epochs = n_epochs\n\n    def scheduler(self, epoch):\n        return self.initial_lr * np.power(1.0 - 1.0 * epoch / self.n_epochs, self.power)\n\n\ndef set_regularization(model,\n                       kernel_regularizer=None,\n                       bias_regularizer=None,\n                       activity_regularizer=None):\n    '''Parameter regularization processing to prevent model overfitting'''\n    for layer in model.layers:\n        if kernel_regularizer is not None and hasattr(layer, 'kernel_regularizer'):\n            layer.kernel_regularizer = kernel_regularizer\n\n        if bias_regularizer is not None and hasattr(layer, 'bias_regularizer'):\n            layer.bias_regularizer = bias_regularizer\n\n        if activity_regularizer is not None and hasattr(layer, 'activity_regularizer'):\n            layer.activity_regularizer = activity_regularizer\n\n\ndef main():\n    config = tf.ConfigProto()\n    config.gpu_options.allow_growth = True\n    session = tf.Session(config=config)\n\n    global IMG_SIZE\n    global CLS_NUM\n\n    ROOT_DIR = args.data_dir\n    BACKBONE = args.backbone\n    BATCH_SIZE = args.batch_size\n    IMG_SIZE = args.image_size\n    EPOCHS = args.epoches\n    LR = args.learning_rate\n    CHECKPOINT = args.checkpoints\n    CLS_NUM = args.class_number\n    MODEL_NAME = args.model_name\n\n    train_transformer = Compose([  # GaussNoise(p=0.2),\n        ShiftScaleRotate(\n            shift_limit=0.1, scale_limit=0.2, rotate_limit=20, p=0.5),\n        HorizontalFlip(p=0.5),\n        #  HueSaturationValue(p=0.5),\n        #  RandomBrightnessContrast(0.5),\n        # GridDistortion(distort_limit=0.2, p=0.5),\n        Resize(height=IMG_SIZE, width=IMG_SIZE, always_apply=True),\n    ])\n    val_transformer = Compose(\n        [Resize(height=IMG_SIZE, width=IMG_SIZE, always_apply=True)])\n\n    train_generator = HairGenerator(\n        train_transformer, ROOT_DIR, mode='Training', batch_size=BATCH_SIZE, nb_classes=CLS_NUM,\n        backbone=BACKBONE, shuffle=True)\n\n    val_generator = HairGenerator(\n        val_transformer, ROOT_DIR, mode='Testing', batch_size=BATCH_SIZE, nb_classes=CLS_NUM,\n        backbone=BACKBONE)\n\n    # Loading models\n    model = get_model(MODEL_NAME)\n    set_regularization(model, kernel_regularizer=l2(2e-5))\n    model.compile(optimizer=optimizers.SGD(lr=LR, momentum=0.98),\n                  loss=cce_dice_loss, metrics=[mean_iou, frequency_weighted_iou, mean_accuracy, pixel_accuracy])\n\n    CHECKPOINT = CHECKPOINT + '/' + MODEL_NAME\n    if not os.path.exists(CHECKPOINT):\n        os.makedirs(CHECKPOINT)\n\n    checkpoint = ModelCheckpoint(filepath=os.path.join(CHECKPOINT, 'model-{epoch:03d}.h5'),\n                                 monitor='val_loss',\n                                 save_best_only=True,\n                                 verbose=1)\n    tensorboard = TensorBoard(log_dir=os.path.join(CHECKPOINT, 'logs'))\n    csvlogger = CSVLogger(\n        os.path.join(CHECKPOINT, \"result.csv\"))\n\n    lr_decay = LearningRateScheduler(PolyDecay(LR, 0.9, EPOCHS).scheduler)\n\n    model.fit_generator(\n        train_generator,\n        len(train_generator),\n        validation_data=val_generator,\n        validation_steps=len(val_generator),\n        epochs=EPOCHS,\n        verbose=1,\n        callbacks=[checkpoint, tensorboard, csvlogger, lr_decay]\n    )\n\n    K.clear_session()\n\n\nif __name__ == '__main__':\n    main()\n"
  }
]