修改代码以使其从 .txt 文件中只读取以 .jpg 结尾的路径。可以对 .txt 文件的内容按行操作,然后根据空格分割,取出图像路径(即第一部分)并忽略其他内容。
以下是更新后的代码片段(我只修改了相关处理 .txt 文件部分的逻辑):
# 处理输入图像路径
if os.path.isfile(args.img_path):
if args.img_path.endswith('txt'):
with open(args.img_path, 'r') as f:
lines = f.read().splitlines()
# 从每行提取出 .jpg 路径(第一部分,按空格分隔)
filenames = [line.split(' ')[0] for line in lines if line.split(' ')[0].endswith('.jpg')]
else:
filenames = [args.img_path]
else:
filenames = glob.glob(os.path.join(args.img_path, '**/*'), recursive=True)
# 过滤掉无关文件,例如 _combine_mask.png
filenames = [f for f in filenames if os.path.isfile(f) and not f.endswith('_combine_mask.png')]
修改点解释
-
按行读取 .txt 文件:
如果 args.img_path 是一个文本文件,读取文件内容后使用 splitlines() 方法将各行单独存储在列表 lines 中。
-
按空格分割每行内容:
由于每行的图像路径与掩码路径通过空格分隔,因此可以使用 .split(' ')[0] 提取出每行的第一部分(即图片路径)。
-
过滤只保留 .jpg 文件:
通过 if line.split(' ')[0].endswith('.jpg') 判断,仅保留以 .jpg 结尾的路径。
-
处理非 .txt 情况:
如果传入的 args.img_path 不是 .txt,保留原有逻辑不变。
-
递归读取其他可能的图像路径:
如果输入路径是文件夹,则使用 glob 模块递归读取其文件,保持灵活性。
文件读取示例(example.txt 内容):
/home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/image/IMG20240102013511.jpg /home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/mask/IMG20240102013511_1_mask.png
/home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/image/IMG20240102004608.jpg /home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/mask/IMG20240102004608_1_mask.png
/home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/image/IMG20240107020724.jpg /home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/mask/IMG20240107020724_1_mask.png
/home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/image/IMG20240103014712.jpg /home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/mask/IMG20240103014712_1_mask.png
通过以上代码,只需要这些以 .jpg 结尾的路径(如 /home/notebook/data/group/hzp/oppseg_v7/data/psrd/org4k/train/image/IMG20240102013511.jpg)将被提取并形成列表。
修正后完整代码
完整代码维护了你原有的逻辑,只调整了从 .txt 文件中读取和过滤路径的部分:
import argparse
import cv2
import glob
import matplotlib
import numpy as np
import os
import torch
from depth_anything_v2.dpt import DepthAnythingV2
from tqdm import tqdm # 导入 tqdm
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Depth Anything V2')
parser.add_argument('--img-path', type=str, default='/home/notebook/data/group/Ruby/langan_datasets/shoushi')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/Ruby/langan_datasets/shoushi_fintune')
parser.add_argument('--encoder', type=str, default='vitl', choices=['vits', 'vitb', 'vitl', 'vitg'])
parser.add_argument('--pred-only', dest='pred_only', default=True, action='store_true', help='only display the prediction')
parser.add_argument('--grayscale', dest='grayscale', default=True, action='store_true', help='do not apply colorful palette')
parser.add_argument('--human_filt', default=False, action='store_true', help='apply depth human filt(flatten)')
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])
ckpt = torch.load("2-9.0288.pth", map_location='cpu')
new_dict = {k: v for k, v in ckpt.items()}
depth_anything.load_state_dict(new_dict, strict=False)
depth_anything = depth_anything.to(DEVICE).eval()
os.makedirs(args.outdir, exist_ok=True)
# 1. 遍历目标文件夹,记住目标文件夹中的文件名
existing_files_disp = set()
for filepath in glob.glob(os.path.join(args.outdir, '*')):
filename = os.path.basename(filepath)
if filename.endswith('_disp.png'):
base_filename = filename[:-9] # 去掉'_disp.png'
existing_files_disp.add(base_filename)
# 处理输入图像路径
if os.path.isfile(args.img_path):
if args.img_path.endswith('txt'):
with open(args.img_path, 'r') as f:
lines = f.read().splitlines()
filenames = [line.split(' ')[0] for line in lines if line.split(' ')[0].endswith('.jpg')]
else:
filenames = [args.img_path]
else:
filenames = glob.glob(os.path.join(args.img_path, '**/*'), recursive=True)
filenames = [f for f in filenames if os.path.isfile(f) and not f.endswith('_combine_mask.png')]
cmap = matplotlib.colormaps.get_cmap('inferno_r')
# 使用 tqdm 显示进度条
for k, filename in tqdm(enumerate(filenames), total=len(filenames), desc="Processing images"):
basename = os.path.splitext(os.path.basename(filename))[0]
if basename in existing_files_disp:
continue
ext_name = os.path.splitext(basename)[1]
try:
raw_image = cv2.imread(filename)
except:
continue
h, w, _ = raw_image.shape
if h > 768 or w > 768:
raw_image = cv2.resize(raw_image, (1024, 768))
depth = depth_anything.infer_image(raw_image, args.input_size)
depth = ((depth - depth.min()) / (depth.max() - depth.min()))
depth = depth * 255
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, basename + '_disp.png'), 255 - depth)
print(os.path.join(args.outdir, basename + '_disp.png'))
else:
split_region = np.ones((raw_image.shape[0], 50, 3), dtype=np.uint8)
combined_result = cv2.hconcat([raw_image, split_region, depth])
cv2.imwrite(os.path.join(args.outdir, basename + '_disp.png'), combined_result)
你可以直接运行这个代码,它只会处理 .txt 文件中以 .jpg 结尾的路径。