Files
2026-05-20 12:25:12 +08:00

116 lines
4.7 KiB
Python

import argparse
import cv2
import glob
import matplotlib
import numpy as np
import os
import torch
from depth_anything_v2.dpt import DepthAnythingV2
def read_image_safe(path):
"""
[解决中文路径问题] 读取图片
使用 numpy 读取字节流再解码,绕过 cv2.imread 的路径编码 bug
"""
try:
# np.fromfile 读取文件内容到内存
img_array = np.fromfile(path, dtype=np.uint8)
# cv2.imdecode 解码内存数据
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
return img
except Exception as e:
print(f"Error reading image {path}: {e}")
return None
def write_image_safe(path, img):
"""
[解决中文路径问题] 保存图片
使用 cv2.imencode 编码再用 numpy 保存,绕过 cv2.imwrite 的路径编码 bug
"""
try:
# 获取文件扩展名 (例如 .png)
ext = os.path.splitext(path)[1]
if not ext:
ext = ".png"
# cv2.imencode 编码图片
success, img_array = cv2.imencode(ext, img)
if success:
# tofile 保存到文件
img_array.tofile(path)
return True
else:
print(f"Error encoding image for {path}")
return False
except Exception as e:
print(f"Error writing image {path}: {e}")
return False
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'
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 = read_image_safe(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:
if write_image_safe(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), depth):
print(f"Saved: {os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png')}")
else:
print(f"Failed to save: {os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png')}")
else:
split_region = np.ones((raw_image.shape[0], 50, 3), dtype=np.uint8) * 255
combined_result = cv2.hconcat([raw_image, split_region, depth])
if write_image_safe(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png'), combined_result):
print(f"Saved: {os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png')}")
else:
print(f"Failed to save: {os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '.png')}")