[
  {
    "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/\npip-wheel-metadata/\nshare/python-wheels/\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.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\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# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\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.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Ibai Gorordo\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# HITNET-Stereo-Depth-estimation\nPython scripts for performing stereo depth estimation using the [HITNET Tensorflow model from Google Research](https://github.com/google-research/google-research/tree/master/hitnet).\n\n![Hitnet stereo depth estimation](https://github.com/ibaiGorordo/HITNET-Stereo-Depth-estimation/blob/main/doc/img/out.jpg)\n*Stereo depth estimation on the cones images from the Middlebury dataset (https://vision.middlebury.edu/stereo/data/scenes2003/)*\n\n# Requirements\n\n * **OpenCV**, **numpy** and **tensorflo**. **pafy** (`pip install git+https://github.com/zizo-pro/pafy@b8976f22c19e4ab5515cacbfae0a3970370c102b`) and **youtube-dl** are required for youtube video inference. \n * For the drivingStereo dataset, download the data from: https://drivingstereo-dataset.github.io/\n\n# Tensorflow models\nDownload the tensorflow models from the [original repository](https://github.com/google-research/google-research/tree/master/hitnet) and save them into the **[models](https://github.com/ibaiGorordo/HITNET-Stereo-Depth-estimation/tree/main/models)** folder. \n\n# Examples\n\n * **Image inference**:\n \n ```\n python imageDepthEstimation.py \n ```\n \n  * **Video inference**:\n \n ```\n python videoDepthEstimation.py\n ```\n \n * **DrivingStereo dataset inference**:\n \n ```\n python drivingStereoTest.py\n ```\n \n  # [Inference video Example](https://youtu.be/ge2iN8Ga4Dg) \n ![!Hitnet stereo depth estimation on video](https://github.com/ibaiGorordo/HITNET-Stereo-Depth-estimation/blob/main/doc/img/hitnetDepthEstimation.gif)\n\n# References:\n* Hitnet model: https://github.com/google-research/google-research/tree/master/hitnet\n* DrivingStereo dataset: https://drivingstereo-dataset.github.io/\n* Original paper: https://arxiv.org/abs/2007.12140\n"
  },
  {
    "path": "drivingStereoTest.py",
    "content": "import cv2\nimport pafy\nimport tensorflow as tf\nimport numpy as np\nimport glob\nfrom hitnet import HitNet, ModelType, draw_disparity, draw_depth, CameraConfig\n\nout = cv2.VideoWriter('outpy2.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 30, (881*3,400))\n\n# Get image list\nleft_images = glob.glob('DrivingStereo images/left/*.jpg')\nleft_images.sort()\nright_images = glob.glob('DrivingStereo images/right/*.jpg')\nright_images.sort()\ndepth_images = glob.glob('DrivingStereo images/depth/*.png')\ndepth_images.sort()\n\n# Select model type\nmodel_type = ModelType.middlebury\n# model_type = ModelType.flyingthings\n# model_type = ModelType.eth3d\n\nif model_type == ModelType.middlebury:\n\tmodel_path = \"models/middlebury_d400.pb\"\nelif model_type == ModelType.flyingthings:\n\tmodel_path = \"models/flyingthings_finalpass_xl.pb\"\nelif model_type == ModelType.eth3d:\n\tmodel_path = \"models/eth3d.pb\"\n\ncamera_config = CameraConfig(0.546, 1000)\nmax_distance = 50\n\n# Initialize model\nhitnet_depth = HitNet(model_path, model_type, camera_config)\n\ncv2.namedWindow(\"Estimated depth\", cv2.WINDOW_NORMAL)\t\nfor left_path, right_path, depth_path in zip(left_images[1500:1700:2], right_images[1500:1700:2], depth_images[1500:1700:2]):\n\n\t# Read frame from the video\n\tleft_img = cv2.imread(left_path)\n\tright_img = cv2.imread(right_path)\n\tdepth_img = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED).astype(np.float32)/256\n\n\t# Estimate the depth\n\tdisparity_map = hitnet_depth(left_img, right_img)\n\tdepth_map = hitnet_depth.get_depth()\n\n\tcolor_disparity = draw_disparity(disparity_map)\n\tcolor_depth = draw_depth(depth_map, max_distance)\n\tcolor_real_depth = draw_depth(depth_img, max_distance)\n\tcobined_image = np.hstack((left_img,color_real_depth, color_depth))\n\n\tout.write(cobined_image)\n\tcv2.imshow(\"Estimated depth\", cobined_image)\n\n\t# Press key q to stop\n\tif cv2.waitKey(1) == ord('q'):\n\t\tbreak\n\nout.release()\ncv2.destroyAllWindows()"
  },
  {
    "path": "hitnet/__init__.py",
    "content": "from hitnet.hitnet import HitNet\nfrom hitnet.utils_hitnet import *"
  },
  {
    "path": "hitnet/hitnet.py",
    "content": "import tensorflow as tf\nimport numpy as np\nimport time\nimport cv2\nfrom hitnet.utils_hitnet import *\n\n\ndrivingStereo_config = CameraConfig(0.546, 1000)\n\nclass HitNet():\n\n\tdef __init__(self, model_path, model_type=ModelType.eth3d, camera_config=drivingStereo_config):\n\n\t\tself.fps = 0\n\t\tself.timeLastPrediction = time.time()\n\t\tself.frameCounter = 0\n\t\tself.camera_config = camera_config\n\n\t\t# Initialize model\n\t\tself.model = self.initialize_model(model_path, model_type)\n\n\tdef __call__(self, left_img, right_img):\n\n\t\treturn self.estimate_disparity(left_img, right_img)\n\n\tdef initialize_model(self, model_path, model_type):\n\n\t\tself.model_type = model_type\n\n\t\twith tf.io.gfile.GFile(model_path, \"rb\") as f:\n\t\t\tgraph_def = tf.compat.v1.GraphDef()\n\t\t\tloaded = graph_def.ParseFromString(f.read())\n\n\t\t# Wrap frozen graph to ConcreteFunctions\n\t\tif self.model_type == ModelType.flyingthings:\n\t\t\tmodel = wrap_frozen_graph(graph_def=graph_def,\n\t\t\t\t\t\t\t\t\t\tinputs=\"input:0\",\n\t\t\t\t\t\t\t\t\t\toutputs=[\"reference_output_disparity:0\",\"secondary_output_disparity:0\"])\n\n\t\telse:\n\t\t\tmodel = wrap_frozen_graph(graph_def=graph_def,\n\t\t\t\t\t\t\t\t\t\tinputs=\"input:0\",\n\t\t\t\t\t\t\t\t\t\toutputs=\"reference_output_disparity:0\")\n\n\t\treturn model\n\n\tdef estimate_disparity(self, left_img, right_img):\n\n\t\tinput_tensor = self.prepare_input(left_img, right_img)\n\n\t\t# Perform inference on the image\n\t\tif self.model_type == ModelType.flyingthings:\n\t\t\tleft_disparity, right_disparity = self.inference(input_tensor)\n\t\t\tself.disparity_map = left_disparity\n\t\telse:\n\t\t\tself.disparity_map = self.inference(input_tensor)\n\n\t\treturn self.disparity_map\n\n\tdef get_depth(self):\n\t\treturn self.camera_config.f*self.camera_config.baseline/self.disparity_map\n\n\tdef prepare_input(self, left_img, right_img):\n\n\t\tif (self.model_type == ModelType.eth3d):\n\n\t\t\t# Shape (1, None, None, 2)\n\t\t\tleft_img = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY)\n\t\t\tright_img = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY)\n\n\t\t\tleft_img = np.expand_dims(left_img,2)\n\t\t\tright_img = np.expand_dims(right_img,2)\n\t\t\tcombined_img = np.concatenate((left_img, right_img), axis=-1) / 255.0\n\t\telse:\n\t\t\t# Shape (1, None, None, 6)\n\t\t\tleft_img = cv2.cvtColor(left_img, cv2.COLOR_BGR2RGB)\n\t\t\tright_img = cv2.cvtColor(right_img, cv2.COLOR_BGR2RGB)\n\t\t\tcombined_img = np.concatenate((left_img, right_img), axis=-1) / 255.0\n\n\n\t\treturn tf.convert_to_tensor(np.expand_dims(combined_img, 0), dtype=tf.float32)\n\t\t\n\tdef inference(self, input_tensor):\n\t\toutput = self.model(input_tensor)\n\n\t\treturn np.squeeze(output)\n\n\n\n\t\n\n\n\n\n\n\n"
  },
  {
    "path": "hitnet/utils_hitnet.py",
    "content": "from enum import Enum\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport urllib\nfrom dataclasses import dataclass\n\nclass ModelType(Enum):\n\teth3d = 0\n\tmiddlebury = 1\n\tflyingthings = 2\n\n@dataclass\nclass CameraConfig:\n    baseline: float\n    f: float\n\ndef wrap_frozen_graph(graph_def, inputs, outputs):\n\tdef _imports_graph_def():\n\t\ttf.compat.v1.import_graph_def(graph_def, name=\"\")\n\twrapped_import = tf.compat.v1.wrap_function(_imports_graph_def, [])\n\timport_graph = wrapped_import.graph\n\treturn wrapped_import.prune(\n\t\ttf.nest.map_structure(import_graph.as_graph_element, inputs),\n\t\ttf.nest.map_structure(import_graph.as_graph_element, outputs))\n\ndef draw_disparity(disparity_map):\n\n\tdisparity_map = disparity_map.astype(np.uint8)\n\tnorm_disparity_map = (255*((disparity_map-np.min(disparity_map))/(np.max(disparity_map) - np.min(disparity_map))))\n\treturn cv2.applyColorMap(cv2.convertScaleAbs(norm_disparity_map,1), cv2.COLORMAP_MAGMA)\n\ndef draw_depth(depth_map, max_dist):\n\t\n\tnorm_depth_map = 255*(1-depth_map/max_dist)\n\tnorm_depth_map[norm_depth_map < 0] =0\n\tnorm_depth_map[depth_map == 0] =0\n\n\treturn cv2.applyColorMap(cv2.convertScaleAbs(norm_depth_map,1), cv2.COLORMAP_MAGMA)\n\ndef load_img(url):\n\treq = urllib.request.urlopen(url)\n\tarr = np.asarray(bytearray(req.read()), dtype=np.uint8)\n\treturn cv2.imdecode(arr, -1) # 'Load it as it is'\n\n\n"
  },
  {
    "path": "imageDepthEstimation.py",
    "content": "import cv2\nimport tensorflow as tf\nimport numpy as np\n\nfrom hitnet import HitNet, ModelType, draw_disparity, draw_depth, CameraConfig, load_img\n\n# Select model type\n# model_type = ModelType.middlebury\n# model_type = ModelType.flyingthings\nmodel_type = ModelType.eth3d\n\nif model_type == ModelType.middlebury:\n\tmodel_path = \"models/middlebury_d400.pb\"\nelif model_type == ModelType.flyingthings:\n\tmodel_path = \"models/flyingthings_finalpass_xl.pb\"\nelif model_type == ModelType.eth3d:\n\tmodel_path = \"models/eth3d.pb\"\n\n\n# Initialize model\nhitnet_depth = HitNet(model_path, model_type)\n\n# Load images\nleft_img = load_img(\"https://vision.middlebury.edu/stereo/data/scenes2003/newdata/cones/im2.png\")\nright_img = load_img(\"https://vision.middlebury.edu/stereo/data/scenes2003/newdata/cones/im6.png\")\n\n# Estimate the depth\ndisparity_map = hitnet_depth(left_img, right_img)\n\ncolor_disparity = draw_disparity(disparity_map)\ncobined_image = np.hstack((left_img, right_img, color_disparity))\n\ncv2.namedWindow(\"Estimated disparity\", cv2.WINDOW_NORMAL)\t\ncv2.imshow(\"Estimated disparity\", cobined_image)\ncv2.waitKey(0)\n\ncv2.imwrite(\"out.jpg\", cobined_image)\n\ncv2.destroyAllWindows()"
  },
  {
    "path": "models/.gitkeep",
    "content": ""
  },
  {
    "path": "requirements.txt",
    "content": "tensorflow>=2.6\nopencv-python\nnumpy\nimread-from-url"
  },
  {
    "path": "videoDepthEstimation.py",
    "content": "import cv2\nimport pafy\nimport tensorflow as tf\nimport numpy as np\n\nfrom hitnet import HitNet, ModelType, draw_disparity, draw_depth, CameraConfig\n\n# Initialize video\n# cap = cv2.VideoCapture(\"video.mp4\")\n\nvideoUrl = 'https://youtu.be/Yui48w71SG0'\nvideoPafy = pafy.new(videoUrl)\nprint(videoPafy.streams)\ncap = cv2.VideoCapture(videoPafy.getbestvideo().url)\n\n\n# Select model type\n# model_type = ModelType.middlebury\n# model_type = ModelType.flyingthings\nmodel_type = ModelType.eth3d\n\nif model_type == ModelType.middlebury:\n\tmodel_path = \"models/middlebury_d400.pb\"\nelif model_type == ModelType.flyingthings:\n\tmodel_path = \"models/flyingthings_finalpass_xl.pb\"\nelif model_type == ModelType.eth3d:\n\tmodel_path = \"models/eth3d.pb\"\n\n# Store baseline (m) and focal length (pixel)\ncamera_config = CameraConfig(0.1, 320)\nmax_distance = 5\n\n# Initialize model\nhitnet_depth = HitNet(model_path, model_type, camera_config)\n\ncv2.namedWindow(\"Estimated depth\", cv2.WINDOW_NORMAL)\t\nwhile cap.isOpened():\n\n\ttry:\n\t\t# Read frame from the video\n\t\tret, frame = cap.read()\n\t\tif not ret:\t\n\t\t\tbreak\n\texcept:\n\t\tcontinue\n\n\t# Extract the left and right images\n\tleft_img  = frame[:,:frame.shape[1]//3]\n\tright_img = frame[:,frame.shape[1]//3:frame.shape[1]*2//3]\n\tcolor_real_depth = frame[:,frame.shape[1]*2//3:]\n\n\t# Estimate the depth\n\tdisparity_map = hitnet_depth(left_img, right_img)\n\tdepth_map = hitnet_depth.get_depth()\n\n\tcolor_disparity = draw_disparity(disparity_map)\n\tcolor_depth = draw_depth(depth_map, max_distance)\n\tcobined_image = np.hstack((left_img,color_real_depth, color_depth))\n\n\tcv2.imshow(\"Estimated depth\", cobined_image)\n\n\t# Press key q to stop\n\tif cv2.waitKey(1) == ord('q'):\n\t\tbreak\n\ncap.release()\ncv2.destroyAllWindows()"
  }
]