├── .gitignore ├── LICENSE ├── README.md ├── assets ├── depth.png └── normal.png ├── depth_to_normal_map.py ├── requirements.txt └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Mert Cobanov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Depth to Normal Map Converter 2 | 3 | This script converts a depth map image to a normal map image. 4 | 5 | 6 | 7 | ## Requirements 8 | 9 | - Python 3.x 10 | - OpenCV (`pip install opencv-python`) 11 | - Numpy 12 | 13 | ## Usage 14 | 15 | To run the script, use the following command: 16 | 17 | ```bash 18 | python depth_to_normal_map.py --input /path/to/input_image --output /path/to/output_image --max_depth 255 19 | ``` 20 | 21 | The following arguments are available: 22 | 23 | - `--input` (`-i`): Path to the input depth map image. 24 | - `--output` (`-o`): Path to save the output normal map image. 25 | - `--max_depth` (`-m`): Maximum depth value of the input depth map image (default: 255). 26 | 27 | ## Example 28 | 29 | ```bash 30 | python depth_to_normal_map.py --input assets/depth.png --output normal_map.png --max_depth 255 31 | ``` 32 | 33 | ## License 34 | 35 | This script is licensed under the [MIT License](https://opensource.org/licenses/MIT). 36 | -------------------------------------------------------------------------------- /assets/depth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobanov/depth2normal/5e48b8bbc42362305fd89e70669a39a84a154578/assets/depth.png -------------------------------------------------------------------------------- /assets/normal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobanov/depth2normal/5e48b8bbc42362305fd89e70669a39a84a154578/assets/normal.png -------------------------------------------------------------------------------- /depth_to_normal_map.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import argparse 4 | 5 | 6 | class DepthToNormalMap: 7 | """A class for converting a depth map image to a normal map image. 8 | 9 | 10 | Attributes: 11 | depth_map (ndarray): A numpy array representing the depth map image. 12 | max_depth (int): The maximum depth value in the depth map image. 13 | """ 14 | 15 | def __init__(self, depth_map_path: str, max_depth: int = 255) -> None: 16 | """Constructs a DepthToNormalMap object. 17 | 18 | Args: 19 | depth_map_path (str): The path to the depth map image file. 20 | max_depth (int, optional): The maximum depth value in the depth map image. 21 | Defaults to 255. 22 | 23 | Raises: 24 | ValueError: If the depth map image file cannot be read. 25 | 26 | """ 27 | self.depth_map = cv2.imread(depth_map_path, cv2.IMREAD_UNCHANGED) 28 | 29 | if self.depth_map is None: 30 | raise ValueError( 31 | f"Could not read the depth map image file at {depth_map_path}" 32 | ) 33 | self.max_depth = max_depth 34 | 35 | def convert(self, output_path: str) -> None: 36 | """Converts the depth map image to a normal map image. 37 | 38 | Args: 39 | output_path (str): The path to save the normal map image file. 40 | 41 | """ 42 | rows, cols = self.depth_map.shape 43 | 44 | x, y = np.meshgrid(np.arange(cols), np.arange(rows)) 45 | x = x.astype(np.float32) 46 | y = y.astype(np.float32) 47 | 48 | # Calculate the partial derivatives of depth with respect to x and y 49 | dx = cv2.Sobel(self.depth_map, cv2.CV_32F, 1, 0) 50 | dy = cv2.Sobel(self.depth_map, cv2.CV_32F, 0, 1) 51 | 52 | # Compute the normal vector for each pixel 53 | normal = np.dstack((-dx, -dy, np.ones((rows, cols)))) 54 | norm = np.sqrt(np.sum(normal**2, axis=2, keepdims=True)) 55 | normal = np.divide(normal, norm, out=np.zeros_like(normal), where=norm != 0) 56 | 57 | # Map the normal vectors to the [0, 255] range and convert to uint8 58 | normal = (normal + 1) * 127.5 59 | normal = normal.clip(0, 255).astype(np.uint8) 60 | 61 | # Save the normal map to a file 62 | normal_bgr = cv2.cvtColor(normal, cv2.COLOR_RGB2BGR) 63 | cv2.imwrite(output_path, normal_bgr) 64 | 65 | 66 | if __name__ == "__main__": 67 | parser = argparse.ArgumentParser(description="Convert depth map to normal map") 68 | parser.add_argument("--input", type=str, help="Path to depth map image") 69 | parser.add_argument( 70 | "--max_depth", type=int, default=255, help="Maximum depth value (default: 255)" 71 | ) 72 | parser.add_argument( 73 | "--output_path", 74 | type=str, 75 | default="normal_map.png", 76 | help="Output path for normal map image (default: normal_map.png)", 77 | ) 78 | args = parser.parse_args() 79 | 80 | converter = DepthToNormalMap(args.input, max_depth=args.max_depth) 81 | converter.convert(args.output_path) 82 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | numpy -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import cv2 3 | import numpy as np 4 | import os 5 | from depth_to_normal_map import DepthToNormalMap 6 | 7 | 8 | class TestDepthToNormalMap(unittest.TestCase): 9 | def setUp(self): 10 | self.depth_map_path = "test_depth_map.png" 11 | self.normal_map_path = "test_normal_map.png" 12 | self.max_depth = 255 13 | self.expected_shape = (480, 640, 3) 14 | 15 | # create a sample depth map image 16 | self.depth_map = np.random.randint( 17 | low=0, high=self.max_depth, size=self.expected_shape[:2], dtype=np.uint16 18 | ) 19 | cv2.imwrite(self.depth_map_path, self.depth_map) 20 | 21 | def test_converting_depth_map_to_normal_map(self): 22 | # create an instance of DepthToNormalMap 23 | converter = DepthToNormalMap(self.depth_map_path, max_depth=self.max_depth) 24 | 25 | # convert the depth map to normal map 26 | converter.convert(self.normal_map_path) 27 | 28 | # assert the output file exists 29 | self.assertTrue(os.path.isfile(self.normal_map_path)) 30 | 31 | # read the output normal map 32 | normal_map = cv2.imread(self.normal_map_path) 33 | 34 | # assert the shape and data type of the normal map 35 | self.assertEqual(normal_map.shape, self.expected_shape) 36 | self.assertEqual(normal_map.dtype, np.uint8) 37 | 38 | def tearDown(self): 39 | # remove the test depth and normal map images 40 | if os.path.isfile(self.depth_map_path): 41 | os.remove(self.depth_map_path) 42 | 43 | if os.path.isfile(self.normal_map_path): 44 | os.remove(self.normal_map_path) 45 | 46 | 47 | if __name__ == "__main__": 48 | unittest.main() 49 | --------------------------------------------------------------------------------