CoolFace
Apppublic

hololens/stable-diffusion-webui-depthmap-script

sourceHugging Faceupdated 2y agoView on Hugging Face
1likes
1import argparse
2import cv2
3import glob
4import matplotlib
5import numpy as np
6import os
7import torch
8
9from depth_anything_v2.dpt import DepthAnythingV2
10
11
12if __name__ == '__main__':
13    parser = argparse.ArgumentParser(description='Depth Anything V2')
14    
15    parser.add_argument('--img-path', type=str)
16    parser.add_argument('--input-size', type=int, default=518)
17    parser.add_argument('--outdir', type=str, default='./vis_depth')
18    
19    parser.add_argument('--encoder', type=str, default='vitl', choices=['vits', 'vitb', 'vitl', 'vitg'])
20    
21    parser.add_argument('--pred-only', dest='pred_only', action='store_true', help='only display the prediction')
22    parser.add_argument('--grayscale', dest='grayscale', action='store_true', help='do not apply colorful palette')
23    
24    args = parser.parse_args()
25    
26    DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
27    
28    model_configs = {
29        'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
30        'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
31        'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
32        'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
33    }
34    
35    depth_anything = DepthAnythingV2(**model_configs[args.encoder])
36    depth_anything.load_state_dict(torch.load(f'checkpoints/depth_anything_v2_{args.encoder}.pth', map_location='cpu'))
37    depth_anything = depth_anything.to(DEVICE).eval()
38    
39    if os.path.isfile(args.img_path):
40        if args.img_path.endswith('txt'):
41            with open(args.img_path, 'r') as f:
42                filenames = f.read().splitlines()
43        else:
44            filenames = [args.img_path]
45    else:
46        filenames = glob.glob(os.path.join(args.img_path, '**/*'), recursive=True)
47    
48    os.makedirs(args.outdir, exist_ok=True)
49    
50    cmap = matplotlib.colormaps.get_cmap('Spectral_r')
51    
52    for k, filename in enumerate(filenames):
53        print(f'Progress {k+1}/{len(filenames)}: {filename}')
54        
55        raw_image = cv2.imread(filename)
56        
57        depth = depth_anything.infer_image(raw_image, args.input_size)
58        
59        depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0
60        depth = depth.astype(np.uint8)
61        
62        if args.grayscale:
63            depth = np.repeat(depth[..., np.newaxis], 3, axis=-1)
64        else:
65            depth = (cmap(depth)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8)
66        
67        if args.pred_only:
68            cv2.imwrite(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), depth)
69        else:
70            split_region = np.ones((raw_image.shape[0], 50, 3), dtype=np.uint8) * 255
71            combined_result = cv2.hconcat([raw_image, split_region, depth])
72            
73            cv2.imwrite(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), combined_result)