Add Github repository content
Browse filesFiles changed (4)
- DA-2K.mdAdded+51
- README.md+136-13
- run.pyAdded+74
- run_video.pyAdded+89
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# DA-2K Evaluation Benchmark
## Introduction

DA-2K is proposed in [Depth Anything V2](https://depth-anything-v2.github.io) to evaluate the relative depth estimation capability. It encompasses eight representative scenarios of `indoor`, `outdoor`, `non_real`, `transparent_reflective`, `adverse_style`, `aerial`, `underwater`, and `object`. It consists of 1K diverse high-quality images and 2K precise pair-wise relative depth annotations.
Please refer to our [paper](https://arxiv.org/abs/2406.09414) for details in constructing this benchmark.
## Usage
Please first [download the benchmark](https://huggingface.co/datasets/depth-anything/DA-2K/tree/main).
All annotations are stored in `annotations.json`. The annotation file is a JSON object where each key is the path to an image file, and the value is a list of annotations associated with that image. Each annotation describes two points and identifies which point is closer to the camera. The structure is detailed below:
```{ "image_path": [ { "point1": [h1, w1], # (vertical position, horizontal position) "point2": [h2, w2], # (vertical position, horizontal position) "closer_point": "point1" # we always set "point1" as the closer one }, ... ], ...}```
To visualize the annotations:```bashpython visualize.py [--scene-type <type>]```
**Options**- `--scene-type <type>` (optional): Specify the scene type (`indoor`, `outdoor`, `non_real`, `transparent_reflective`, `adverse_style`, `aerial`, `underwater`, and `object`). Skip this argument or set <type> as `""` to include all scene types.
## Citation
If you find this benchmark useful, please consider citing:
```bibtex@article{depth_anything_v2, title={Depth Anything V2}, author={Yang, Lihe and Kang, Bingyi and Huang, Zilong and Zhao, Zhen and Xu, Xiaogang and Feng, Jiashi and Zhao, Hengshuang}, journal={arXiv:2406.09414}, year={2024}}```12345678910111213---title: Depth Anything V2emoji: 🌖colorFrom: redcolorTo: indigosdk: gradiosdk_version: 4.36.0app_file: app.pypinned: falselicense: bsd-2-clause---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136<div align="center"><h1>Depth Anything V2</h1>[**Lihe Yang**](https://liheyoung.github.io/)<sup>1</sup> · [**Bingyi Kang**](https://bingykang.github.io/)<sup>2†</sup> · [**Zilong Huang**](http://speedinghzl.github.io/)<sup>2</sup><br>[**Zhen Zhao**](http://zhaozhen.me/) · [**Xiaogang Xu**](https://xiaogang00.github.io/) · [**Jiashi Feng**](https://sites.google.com/site/jshfeng/)<sup>2</sup> · [**Hengshuang Zhao**](https://hszhao.github.io/)<sup>1*</sup><sup>1</sup>HKU   <sup>2</sup>TikTok<br>†project lead *corresponding author<a href="https://arxiv.org/abs/2406.09414"><img src='https://img.shields.io/badge/arXiv-Depth Anything V2-red' alt='Paper PDF'></a><a href='https://depth-anything-v2.github.io'><img src='https://img.shields.io/badge/Project_Page-Depth Anything V2-green' alt='Project Page'></a><a href='https://huggingface.co/spaces/depth-anything/Depth-Anything-V2'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a><a href='https://huggingface.co/datasets/depth-anything/DA-2K'><img src='https://img.shields.io/badge/Benchmark-DA--2K-yellow' alt='Benchmark'></a></div>This work presents Depth Anything V2. It significantly outperforms [V1](https://github.com/LiheYoung/Depth-Anything) in fine-grained details and robustness. Compared with SD-based models, it enjoys faster inference speed, fewer parameters, and higher depth accuracy.## News- **2024-06-14:** Paper, project page, code, models, demo, and benchmark are all released.## Pre-trained ModelsWe provide **four models** of varying scales for robust relative depth estimation:| Model | Params | Checkpoint ||:-|-:|:-:|| Depth-Anything-V2-Small | 24.8M | [Download](https://huggingface.co/depth-anything/Depth-Anything-V2-Small/resolve/main/depth_anything_v2_vits.pth?download=true) || Depth-Anything-V2-Base | 97.5M | [Download](https://huggingface.co/depth-anything/Depth-Anything-V2-Base/resolve/main/depth_anything_v2_vitb.pth?download=true) || Depth-Anything-V2-Large | 335.3M | [Download](https://huggingface.co/depth-anything/Depth-Anything-V2-Large/resolve/main/depth_anything_v2_vitl.pth?download=true) || Depth-Anything-V2-Giant | 1.3B | Coming soon |### Code snippet to use our models```pythonimport cv2import torchfrom depth_anything_v2.dpt import DepthAnythingV2# take depth-anything-v2-large as an examplemodel = DepthAnythingV2(encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024])model.load_state_dict(torch.load('checkpoints/depth_anything_v2_vitl.pth', map_location='cpu'))model.eval()raw_img = cv2.imread('your/image/path')depth = model.infer_image(raw_img) # HxW raw depth map```## Usage### Installation```bashgit clone https://github.com/DepthAnything/Depth-Anything-V2cd Depth-Anything-V2pip install -r requirements.txt```### Running```bashpython run.py --encoder <vits | vitb | vitl | vitg> --img-path <path> --outdir <outdir> [--input-size <size>] [--pred-only] [--grayscale]```Options:- `--img-path`: You can either 1) point it to an image directory storing all interested images, 2) point it to a single image, or 3) point it to a text file storing all image paths.- `--input-size` (optional): By default, we use input size `518` for model inference. **You can increase the size for even more fine-grained results.**- `--pred-only` (optional): Only save the predicted depth map, without raw image.- `--grayscale` (optional): Save the grayscale depth map, without applying color palette.For example:```bashpython run.py --encoder vitl --img-path assets/examples --outdir depth_vis```**If you want to use Depth Anything V2 on videos:**```bashpython run_video.py --encoder vitl --video-path assets/examples_video --outdir video_depth_vis```*Please note that our larger model has better temporal consistency on videos.*### Gradio demoTo use our gradio demo locally:```bashpython app.py```You can also try our [online demo](https://huggingface.co/spaces/Depth-Anything/Depth-Anything-V2).**Note:** Compared to V1, we have made a minor modification to the DINOv2-DPT architecture (originating from this [issue](https://github.com/LiheYoung/Depth-Anything/issues/81)). In V1, we *unintentionally* used features from the last four layers of DINOv2 for decoding. In V2, we use [intermediate features](https://github.com/DepthAnything/Depth-Anything-V2/blob/2cbc36a8ce2cec41d38ee51153f112e87c8e42d8/depth_anything_v2/dpt.py#L164-L169) instead. Although this modification did not improve details or accuracy, we decided to follow this common practice.## Fine-tuned to Metric Depth EstimationPlease refer to [metric depth estimation](./metric_depth).## DA-2K Evaluation BenchmarkPlease refer to [DA-2K benchmark](./DA-2K.md).## LICENSEDepth-Anything-V2-Small model is under the Apache-2.0 license. Depth-Anything-V2-Base/Large/Giant models are under the CC-BY-NC-4.0 license.## CitationIf you find this project useful, please consider citing:```bibtex@article{depth_anything_v2,title={Depth Anything V2},author={Yang, Lihe and Kang, Bingyi and Huang, Zilong and Zhao, Zhen and Xu, Xiaogang and Feng, Jiashi and Zhao, Hengshuang},journal={arXiv:2406.09414},year={2024}}@inproceedings{depth_anything_v1,title={Depth Anything: Unleashing the Power of Large-Scale Unlabeled Data},author={Yang, Lihe and Kang, Bingyi and Huang, Zilong and Xu, Xiaogang and Feng, Jiashi and Zhao, Hengshuang},booktitle={CVPR},year={2024}}```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import argparseimport cv2import globimport matplotlibimport numpy as npimport osimport torch
from depth_anything_v2.dpt import DepthAnythingV2
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Depth Anything V2') parser.add_argument('--img-path', type=str) parser.add_argument('--input-size', type=int, default=518) parser.add_argument('--outdir', type=str, default='./vis_depth') parser.add_argument('--encoder', type=str, default='vitl', choices=['vits', 'vitb', 'vitl', 'vitg']) parser.add_argument('--pred-only', dest='pred_only', action='store_true', help='only display the prediction') parser.add_argument('--grayscale', dest='grayscale', action='store_true', help='do not apply colorful palette') args = parser.parse_args() DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu' # we are undergoing company review procedures to release Depth-Anything-Giant checkpoint model_configs = { 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]}, 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]}, 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]}, 'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]} } depth_anything = DepthAnythingV2(**model_configs[args.encoder]) depth_anything.load_state_dict(torch.load(f'checkpoints/depth_anything_v2_{args.encoder}.pth', map_location='cpu')) depth_anything = depth_anything.to(DEVICE).eval() if os.path.isfile(args.img_path): if args.img_path.endswith('txt'): with open(args.img_path, 'r') as f: filenames = f.read().splitlines() else: filenames = [args.img_path] else: filenames = glob.glob(os.path.join(args.img_path, '**/*'), recursive=True) os.makedirs(args.outdir, exist_ok=True) cmap = matplotlib.colormaps.get_cmap('Spectral_r') for k, filename in enumerate(filenames): print(f'Progress {k+1}/{len(filenames)}: {filename}') raw_image = cv2.imread(filename) depth = depth_anything.infer_image(raw_image, args.input_size) depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0 depth = depth.astype(np.uint8) if args.grayscale: depth = np.repeat(depth[..., np.newaxis], 3, axis=-1) else: depth = (cmap(depth)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8) if args.pred_only: cv2.imwrite(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), depth) else: split_region = np.ones((raw_image.shape[0], 50, 3), dtype=np.uint8) * 255 combined_result = cv2.hconcat([raw_image, split_region, depth]) cv2.imwrite(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), combined_result)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import argparseimport cv2import globimport matplotlibimport numpy as npimport osimport torch
from depth_anything_v2.dpt import DepthAnythingV2
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Depth Anything V2') parser.add_argument('--video-path', type=str) parser.add_argument('--input-size', type=int, default=518) parser.add_argument('--outdir', type=str, default='./vis_video_depth') parser.add_argument('--encoder', type=str, default='vitl', choices=['vits', 'vitb', 'vitl', 'vitg']) parser.add_argument('--pred-only', dest='pred_only', action='store_true', help='only display the prediction') parser.add_argument('--grayscale', dest='grayscale', action='store_true', help='do not apply colorful palette') args = parser.parse_args() DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu' # 'we are undergoing company review procedures to release Depth-Anything-Giant checkpoint model_configs = { 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]}, 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]}, 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]}, 'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]} } depth_anything = DepthAnythingV2(**model_configs[args.encoder]) depth_anything.load_state_dict(torch.load(f'checkpoints/depth_anything_v2_{args.encoder}.pth', map_location='cpu')) depth_anything = depth_anything.to(DEVICE).eval() if os.path.isfile(args.video_path): if args.video_path.endswith('txt'): with open(args.video_path, 'r') as f: lines = f.read().splitlines() else: filenames = [args.video_path] else: filenames = glob.glob(os.path.join(args.video_path, '**/*'), recursive=True) os.makedirs(args.outdir, exist_ok=True) margin_width = 50 cmap = matplotlib.colormaps.get_cmap('Spectral_r') for k, filename in enumerate(filenames): print(f'Progress {k+1}/{len(filenames)}: {filename}') raw_video = cv2.VideoCapture(filename) frame_width, frame_height = int(raw_video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(raw_video.get(cv2.CAP_PROP_FRAME_HEIGHT)) frame_rate = int(raw_video.get(cv2.CAP_PROP_FPS)) output_width = frame_width * 2 + margin_width output_path = os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.mp4') out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), frame_rate, (output_width, frame_height)) while raw_video.isOpened(): ret, raw_frame = raw_video.read() if not ret: break depth = depth_anything.infer_image(raw_frame, args.input_size) depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0 depth = depth.astype(np.uint8) if args.grayscale: depth = np.repeat(depth[..., np.newaxis], 3, axis=-1) else: depth = (cmap(depth)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8) if args.pred_only: out.write(depth) else: split_region = np.ones((frame_height, margin_width, 3), dtype=np.uint8) * 255 combined_frame = cv2.hconcat([raw_frame, split_region, depth]) out.write(combined_frame) raw_video.release() out.release()DA-2K.mdAdded+51
README.md+136-13
run.pyAdded+74
run_video.pyAdded+89