Explore / Programming ''' 用于检测图像是否为nonetype的代码,防止图像卡住 输入为训练数据的txt 注:每次train之前最好都用此代码检查一遍txt ''' import cv2… Save Share Download ▾ ReportJump to turn (8) 1 ''' 用于检测图像是否为nonetype的代码,防止图像卡住 输入为训练数据的txt 注:每次train之前最好都用此代码检查一遍txt ''' import 2 import argparse import cv2 import glob import matplotlib import numpy as np impo 3 以上代码用tqdm进行可视化 4 上述代码能加速吗? 5 加入批处理,使得一次能够处理多个图像 6 忘记刚才我和你说的事情 7 如果我需要跑三个各自独立的代码,需要实现第一个代码跑完了跑第二个代码,第二个代码跑完了跑第三个代码,脚本应该怎么写 8 如果这三个脚本都在不同的文件夹呢? '''
用于检测图像是否为nonetype的代码,防止图像卡住
输入为训练数据的txt
注:每次train之前最好都用此代码检查一遍txt
'''
import cv2
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def read_image_paths(file_path):
"""读取文本文件中的图像路径"""
with open(file_path, 'r') as file:
paths = file.read().splitlines()
return paths
def check_image(path):
"""检查图像是否为NoneType"""
image = cv2.imread(path)
return path if image is None else None
def find_none_type_images(paths, max_workers=16):
"""寻找路径中对应的图像为空的情况"""
none_type_paths = []
with ProcessPoolExecutor(max_workers=max_workers) as executor:
# 使用字典来提交任务并保持未来以检索路径
future_to_path = {executor.submit(check_image, path): path for path in paths}
Show full message · 61 lines Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 8 (16 messages)
Language zh
Conversation date Dec 3, 2024
Added to archive Nov 16, 2026
ID 01m7h42ajhfyp7exyy9paqfqgkSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 01a6bf9fd29bfcea330f2057ade3cb02
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
for future in tqdm(as_completed(future_to_path), total=len(paths), desc="Processing images"):
result = future.result()
if result is not None:
none_type_paths.append(result)
return none_type_paths
def save_none_type_paths(none_type_paths, output_file='none_type_images.txt'):
"""保存无法读取的图像路径到文件"""
with open(output_file, 'w') as file:
for path in none_type_paths:
file.write(path + '\n')
print(f"NoneType image paths have been saved to {output_file}")
def main():
# 指定你的文本文件路径
txt_file_path = 'langanero_files.txt'
code Copy code
# 读取路径并查找NoneType的图像
image_paths = read_image_paths(txt_file_path)
none_type_images = find_none_type_images(image_paths)
# 输出结果并保存NoneType图像路径
if none_type_images:
print("以下路径中的图像无法读取:")
for path in none_type_images:
print(path)
save_none_type_paths(none_type_images)
else:
print("所有图像都成功读取。")
if name == 'main ':
main()
在这个代码的基础上,改成读取一个文件夹里的图像,把nonetype的文件打印出来,不保存在txt
Assistant2024-12-03 06:14 UTC Copy response
在您现有的代码基础上,您可以通过修改 read_image_paths 函数来读取指定文件夹内的所有图像文件,并在检查完后直接打印出 NoneType 的图像路径,而不将其保存到文件。以下是修改后的代码:
python Copy code
import cv2
import os
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def read_image_paths(folder_path):
"""读取文件夹中的所有图像路径"""
paths = []
# 遍历文件夹中的所有文件
for root, _, files in os.walk(folder_path):
for file in files:
# 根据文件扩展名判断是否为图像文件
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):
paths.append(os.path.join(root, file))
return paths
def check_image(path):
"""检查图像是否为NoneType"""
image = cv2.imread(path)
return path if image is None else None
def find_none_type_images(paths, max_workers=16):
"""寻找路径中对应的图像为空的情况"""
none_type_paths = []
with ProcessPoolExecutor(max_workers=max_workers) as executor:
# 使用字典来提交任务并保持未来以检索路径
future_to_path = {executor.submit(check_image, path): path for path in paths}
for future in tqdm(as_completed(future_to_path), total=len(paths), desc="Processing images"):
result = future.result()
if result is not None:
none_type_paths.append(result)
return none_type_paths
def main():
# 指定你的文件夹路径
folder_path = 'path/to/your/image_folder' # 修改为你自己的文件夹路径
# 读取路径并查找NoneType的图像
image_paths = read_image_paths(folder_path)
none_type_images = find_none_type_images(image_paths)
# 输出结果
if none_type_images:
print("以下路径中的图像无法读取:")
for path in none_type_images:
print(path)
else:
print("所有图像都成功读取。")
if __name__ == '__main__':
main()
代码说明:
read_image_paths 函数 改为读取指定文件夹中的所有图像文件。它会遍历文件夹,并根据文件扩展名的判断来过滤图像文件(可以根据需要调整扩展名)。
check_image 函数 和 find_none_type_images 函数 维持不变,直接用来检测图像是否为 NoneType。
main 函数 中指定了文件夹路径,并打印任何无法读取的图像路径,而不是将其保存到文本文件中。
您需要将 'path/to/your/image_folder' 替换为您实际想要检查的文件夹路径。运行这个代码后,所有无法读取的图像路径会被直接打印出来。
import argparse
import cv2
import glob
import matplotlib
import numpy as np
import os
import torch
import time
from depth_anything_v2.dpt import DepthAnythingV2
import numpy as np
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
if name == 'main ':
parser = argparse.ArgumentParser(description='Depth Anything V2')
parser.add_argument('--img-path', type=str,default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/image')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/depth')
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(f'depth_anything_s.pth', map_location='cpu')
ckpt = torch.load("2-9.0288.pth", map_location='cpu')
new_dict = {}
for k, v in ckpt.items():
# if 'pretrained.pos_embed' not in k:
new_dict.update({k:v})
depth_anything.load_state_dict(new_dict,strict=False)
depth_anything = depth_anything.to(DEVICE).eval()
# args.outdir = args.outdir
os.makedirs(args.outdir, exist_ok=True)
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)
filenames = [ f for f in filenames if( os.path.isfile(f) ) ]
cmap = matplotlib.colormaps.get_cmap('Spectral_r')
cmap = matplotlib.colormaps.get_cmap('inferno_r')
import time
for k, filename in enumerate(filenames):
# print(filename)
# try:
# if 'depth.png' in filename or '_v2.png' in filename or '_v3.png' in filename:
if '_disp.png' in filename or '_pred.png' in filename or '_right.png' in filename:
continue
# if(os.path.exists(filename.replace(".png","_v3.png"))):
# continue
ext_name = os.path.splitext(os.path.basename(filename))[1]
try:
raw_image = cv2.imread(filename)
# raw_image = cv2.imread("/home/notebook/data/group//liulibo/depth_data/midas/IMG20240101040239_04_guide_rgb.png")
except:
continue
# if(".jpg" not in filename):
# continue
h, w, _ = raw_image.shape
print(raw_image.shape)
if(h>768 or w>768):
raw_image = cv2.resize(raw_image, (768, 1024))
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)
Show full message · 102 lines Assistant2024-12-03 06:26 UTC Copy response
根据您的要求,我们可以在程序开始时添加一段逻辑,用于遍历目标文件夹并记录文件名,然后从中去除后缀 "_disp"。在处理图像时,我们可以检查这些去掉后缀的名字是否存在于实际的图像文件名中。如果存在,则跳过这些图像文件。
下面是修改后的代码,未改变代码的整体结构和功能:
Assistant2024-12-03 06:28 UTC Copy response
要在您的代码中使用 tqdm 来显示进度条,可以在处理图像的循环部分添加 tqdm 的包裹。下面是经过修改的代码,已添加 tqdm 进度条来可视化图像处理的进度。
Assistant2024-12-03 06:37 UTC Copy response
可以采用几个方法来加速上述代码的执行过程,尤其是在处理图像和进行深度推断的部分。以下是一些建议:
使用多线程/多进程 :
使用 concurrent.futures.ThreadPoolExecutor 或 ProcessPoolExecutor 可以在多个核心上并行处理图像。由于 I/O 操作(读取和写入文件)和计算操作(深度推断)都是相对独立的,这可以显著提高处理速度。
批量处理 :
如果您的模型支持批量输入,可以将多个图像合并成一个批次进行推断。这会更高效,因为深度模型会在一次前向传播中处理多个图像。
图像预处理 :
如果可以的话,尽早缩放或裁剪输入图像,以减少后续处理的张量大小。
GPU 加速 :
确保使用 GPU 进行深度推断,并检查 GPU 的利用率。可以通过调用 .cuda() 或者其他相关方法将模型和数据移动到 GPU。
下面是对原代码进行并行处理的示例。这里使用 ThreadPoolExecutor 来并行处理每个图像:
Assistant2024-12-03 06:38 UTC Copy response
要实现批处理,使得您的代码能够一次处理多个图像,您需要对模型的输入接口进行一些调整。以下是实现这一功能的步骤:
修改 process_image 函数 :将其从处理单个图像改成处理一个批次的图像。
构建一个批次的图像数据 :在读取图像的过程中,将它们存储到一个列表中,并在列表达到设定的批次大小后,一同传递给模型。
处理批量输出 :在模型处理完批次后,处理输出并保存每个图像的结果。
以下是修改后的完整代码,使用了批处理:
Assistant2024-12-03 06:48 UTC Copy response
没问题!如果您有新的问题或需要讨论其他内容,请随时告诉我。无论是代码问题、项目建议还是其他方面的内容,我都很乐意帮助您!
如果我需要跑三个各自独立的代码,需要实现第一个代码跑完了跑第二个代码,第二个代码跑完了跑第三个代码,脚本应该怎么写
Assistant2024-12-03 06:49 UTC Copy response
如果您需要依次运行三个各自独立的代码脚本,并确保每个脚本在前一个脚本完成后执行,可以使用 Python 的 subprocess 模块来实现。这种方法可以让您在一个主脚本中按顺序运行其他脚本,同时监控其是否成功完成。如果第一个脚本失败,后续脚本将不会运行。
以下是一个示例,展示如何在一个 Python 脚本中依次调用三个独立的代码脚本:
python Copy code
import subprocess
def run_script(script_path):
"""Run a script and wait for it to complete."""
try:
# 调用 subprocess.run 来执行脚本
result = subprocess.run(['python', script_path], check=True, capture_output=True, text=True)
print(f"Script {script_path} completed successfully.")
print(result.stdout) # 输出脚本的标准输出内容
except subprocess.CalledProcessError as e:
print(f"Script {script_path} failed with exit code {e.returncode}.")
print(e.stderr) # 输出错误信息
raise # 重新抛出异常以终止后续执行
if __name__ == '__main__':
# 定义要运行的脚本路径
scripts = [
'script1.py', # 第一个脚本
'script2.py', # 第二个脚本
'script3.py' # 第三个脚本
]
for script in scripts:
run_script(script)
代码说明:
subprocess.run :
使用 subprocess.run 方法来执行每个脚本。该方法会阻塞当前线程,直到所调用的程序完成。
check=True 参数指定如果出现错误会抛出 CalledProcessError 异常。
capture_output=True 用于捕获标准输出和标准错误,text=True 将其转换为字符串。
错误处理 :
如果任何一个脚本返回非零退出码,程序将打印错误信息并终止后续脚本的运行。
脚本路径 :
运行脚本:
确保在运行此主脚本时,所列的每个脚本 (script1.py, script2.py, script3.py) 都位于同一目录中,或提供相应的完整路径。
使用示例:
您可以将上面的代码保存在名为 run_all_scripts.py 的文件中,然后在命令行中运行:
bash Copy code
python run_all_scripts.py
这样就可以依次执行三个脚本,并便捷地处理每个脚本的输出和错误信息。
Assistant2024-12-03 06:49 UTC Copy response
如果这三个脚本位于不同的文件夹中,您只需在 scripts 列表中指定每个脚本的完整路径。以下是如何实现这一点的示例:
python Copy code
import subprocess
def run_script(script_path):
"""Run a script and wait for it to complete."""
try:
# 调用 subprocess.run 来执行脚本
result = subprocess.run(['python', script_path], check=True, capture_output=True, text=True)
print(f"Script {script_path} completed successfully.")
print(result.stdout) # 输出脚本的标准输出内容
except subprocess.CalledProcessError as e:
print(f"Script {script_path} failed with exit code {e.returncode}.")
print(e.stderr) # 输出错误信息
raise # 重新抛出异常以终止后续执行
if __name__ == '__main__':
# 定义要运行的脚本路径
scripts = [
'/path/to/folder1/script1.py', # 第一个脚本的完整路径
'/path/to/folder2/script2.py', # 第二个脚本的完整路径
'/path/to/folder3/script3.py' # 第三个脚本的完整路径
]
for script in scripts:
run_script(script)
代码说明:
指定完整路径 :
在 scripts 列表中使用完整路径来引用每个脚本。请确保路径是准确的,并包含文件的扩展名(如 .py)。
错误处理和输出 :
错误处理和输出跟之前的例子是一样的,使用 subprocess.run 来执行脚本,捕获输出并处理任何错误。
运行脚本:
只要在运行此主脚本时,确保指定的每个脚本路径都是正确的。您可以将这个脚本保存为 run_all_scripts.py,然后在命令行中运行它:
bash Copy code
python run_all_scripts.py
这将依次运行每个脚本,并打印每个脚本的输出和任何错误信息。
Not yet included in a published release.
code Copy code
new_shape = (w, h)
depth = cv2.resize(depth, new_shape)
# print(depth.shape)
# cv2.imwrite( '/home/notebook/data/group//liulibo/depth_data/midas/IMG20240101040239_04_guide_rgb_v3.png', depth)
if args.grayscale:
depth = np.repeat(depth[..., np.newaxis], 3, axis=-1)
else:
# depth = cv2.applyColorMap(np.uint8(depth), cv2.COLORMAP_INFERNO)
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] + '_disp.png'), 255-depth)
print(os.path.join(args.outdir, os.path.splitext(os.path.basename(filename))[0] + '_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, os.path.splitext(os.path.basename(filename))[0] + '_disp.png'), combined_result)
# except:
# pass
在不改变代码结构和功能的前提下,修改这个代码,完成以下功能:1.开始的时候遍历一下目标文件夹,记住目标文件夹中的文件名;2.1中的文件名去除后缀“_disp”;3.在图像文件夹中如果含有2中的文件名,则跳过该文件。
import argparse
import cv2
import glob
import matplotlib
import numpy as np
import os
import torch
from depth_anything_v2.dpt import DepthAnythingV2
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/liulibo/disprefine_data/seg_data/new_data/image')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/depth')
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 = set()
existing_files_disp = set()
for filepath in glob.glob(os.path.join(args.outdir, '*')):
filename = os.path.basename(filepath)
if filename.endswith('_disp.png'):
# 2. 去除后缀"_disp"并保存到集合中
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:
filenames = f.read().splitlines()
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)]
cmap = matplotlib.colormaps.get_cmap('inferno_r')
for k, filename in enumerate(filenames):
basename = os.path.splitext(os.path.basename(filename))[0]
if basename in existing_files_disp:
# 如果文件名去掉后缀"_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, (768, 1024))
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)
new_shape = (w, h)
depth = cv2.resize(depth, new_shape)
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)
修改说明:
记录现有文件名 :
在代码开始处对目标文件夹进行遍历,记录所有以 _disp.png 结尾的文件名(去掉后缀)。使用集合 existing_files_disp 来存储去除后缀的文件名。
处理图像时的跳过逻辑 :
在处理每个图像之前,先取得图像的基本文件名,检查该名称是否存在于 existing_files_disp 集合中。如果存在,则跳过处理该图像。
以上修改在保持原有代码功能的基础上,完成了您提到的需求。
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/liulibo/disprefine_data/seg_data/new_data/image')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/depth')
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'):
# 2. 去除后缀"_disp"并保存到集合中
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:
filenames = f.read().splitlines()
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)]
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:
# 如果文件名去掉后缀"_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, (768, 1024))
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)
new_shape = (w, h)
depth = cv2.resize(depth, new_shape)
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)
主要更改:
导入 tqdm :添加 from tqdm import tqdm 来导入 tqdm。
使用 tqdm 包裹循环 :在处理图像的 for 循环中,将 enumerate(filenames) 用 tqdm 包装,这样就能在控制台中显示处理进度。设置 total=len(filenames) 和 desc 参数以显示进度条和描述。
这将在处理每个图像时可视化进度,从而使用户知道当前处理了多少图像。其它代码保持不变,确保了原有功能和结构。
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
from concurrent.futures import ThreadPoolExecutor # 添加并行处理模块
def process_image(filename, depth_anything, args, existing_files_disp):
basename = os.path.splitext(os.path.basename(filename))[0]
if basename in existing_files_disp:
return # 如果文件名去掉后缀"_disp"的部分存在,则跳过该文件
try:
raw_image = cv2.imread(filename)
if raw_image is None:
return # 检查图像是否读取成功
h, w, _ = raw_image.shape
if h > 768 or w > 768:
raw_image = cv2.resize(raw_image, (768, 1024))
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)
new_shape = (w, h)
depth = cv2.resize(depth, new_shape)
cmap = matplotlib.colormaps.get_cmap('inferno_r')
if args.grayscale:
depth = np.repeat(depth[..., np.newaxis], 3, axis=-1)
else:
depth = (cmap(depth)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8)
output_path = os.path.join(args.outdir, basename + '_disp.png')
if args.pred_only:
cv2.imwrite(output_path, 255 - depth)
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(output_path, combined_result)
return output_path # 可以返回文件路径以便调试
except Exception as e:
print(f"Error processing {filename}: {e}")
return None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Depth Anything V2')
parser.add_argument('--img-path', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/image')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/depth')
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)
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:
filenames = f.read().splitlines()
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)]
# 使用 ThreadPoolExecutor 来加速图像处理
with ThreadPoolExecutor() as executor:
list(tqdm(executor.map(lambda f: process_image(f, depth_anything, args, existing_files_disp), filenames), total=len(filenames), desc="Processing images"))
主要修改:
引入并行处理 :
使用 ThreadPoolExecutor 进行图像处理。通过将 process_image 函数传递给 executor.map,像外部函数那样处理每个图像。
错误处理 :
在 process_image 函数中增加了错误处理,如果在处理某个图像时发生错误,会打印出错误信息。
进度条 :
使用 tqdm 来包装 executor.map,显示处理进度条。
其他建议:
您可以根据机器的 CPU 和 GPU 核心数调节 ThreadPoolExecutor 的 max_workers 参数。
如果您的模型支持批处理,考虑将多个图像一起送入模型进行推断,这样会更高效。
确保 GPU 的使用率高,使用 torch.cuda.memory_summary() 来检查内存使用情况。
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
from concurrent.futures import ThreadPoolExecutor
def process_batch(filenames, depth_anything, args, existing_files_disp):
depth_images = []
raw_images = []
outputs = []
for filename in filenames:
basename = os.path.splitext(os.path.basename(filename))[0]
if basename in existing_files_disp:
continue # 跳过已处理的文件
raw_image = cv2.imread(filename)
if raw_image is None:
continue # 跳过未成功读取的图像
h, w, _ = raw_image.shape
if h > 768 or w > 768:
raw_image = cv2.resize(raw_image, (768, 1024))
raw_images.append(raw_image)
# 如果已经有原图,进行批处理推断
if raw_images:
depth = depth_anything.infer_image(raw_images, args.input_size) # 根据你的模型接口调整
for i, img in enumerate(depth):
depth_image = ((img - img.min()) / (img.max() - img.min())) * 255
depth_image = depth_image.astype(np.uint8)
new_shape = (raw_images[i].shape[1], raw_images[i].shape[0])
depth_image = cv2.resize(depth_image, new_shape)
cmap = matplotlib.colormaps.get_cmap('inferno_r')
if args.grayscale:
depth_image = np.repeat(depth_image[..., np.newaxis], 3, axis=-1)
else:
depth_image = (cmap(depth_image)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8)
output_path = os.path.join(args.outdir, basename + '_disp.png')
if args.pred_only:
cv2.imwrite(output_path, 255 - depth_image)
else:
split_region = np.ones((raw_images[i].shape[0], 50, 3), dtype=np.uint8)
combined_result = cv2.hconcat([raw_images[i], split_region, depth_image])
cv2.imwrite(output_path, combined_result)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Depth Anything V2')
parser.add_argument('--img-path', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/image')
parser.add_argument('--input_size', type=int, default=1024)
parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/liulibo/disprefine_data/seg_data/new_data/depth')
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)')
parser.add_argument('--batch-size', type=int, default=4, help='Number of images to process in a batch')
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)
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:
filenames = f.read().splitlines()
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)]
# 设置批处理大小
batch_size = args.batch_size
for i in tqdm(range(0, len(filenames), batch_size), desc="Processing images"):
process_batch(filenames[i:i + batch_size], depth_anything, args, existing_files_disp)
主要修改:
批处理功能 :
新增了一个 process_batch 函数,用于处理多个图像,并向模型传递批次数据。
在 process_batch 内部,所有图像会被读取并压入列表 raw_images,然后在同一时间推断。
批处理参数 :
在 argparse 中添加了 --batch-size 选项,您可以通过此选项来设置一次处理的图像数量。默认值为 4,可以根据您的 GPU 内存和性能进行调整。
图像推理 :
infer_image 函数需要确保支持批量输入,确保返回的深度图也是一个批次的输出。不同的框架和模型接口可能略有不同,请根据您的模型调整。
显示进度条 :
通过这种方式,您的代码在每次推断中会处理多个图像,这可以显著提高整体效率,尤其是在处理大量图像的情况下。