File size: 14,288 Bytes
85a0c66 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | # 处理data文件夹数据生成仿真数据的脚本
import include.simsp as simsp
import numpy as np
import cv2
import argparse
import os
import torch
from tqdm import tqdm
import re
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
import time
def get_matching_files(images_dir, depth_dir):
"""
获取匹配的图像和深度文件对
Args:
images_dir (str): 图像文件夹路径
depth_dir (str): 深度图文件夹路径
Returns:
list: 匹配的文件对列表 [(image_path, depth_path, base_name), ...]
"""
# 检查文件夹是否存在
if not os.path.exists(images_dir):
raise FileNotFoundError(f"图像文件夹不存在: {images_dir}")
if not os.path.exists(depth_dir):
raise FileNotFoundError(f"深度文件夹不存在: {depth_dir}")
# 获取所有图像文件
image_files = []
for ext in ['*.jpg', '*.jpeg', '*.JPG', '*.JPEG']:
image_files.extend(Path(images_dir).glob(ext))
# 获取所有深度文件
depth_files = []
for ext in ['*.png', '*.PNG']:
depth_files.extend(Path(depth_dir).glob(ext))
# 创建文件名到路径的映射
image_dict = {}
depth_dict = {}
for img_path in image_files:
# 提取基础文件名(不含扩展名)
base_name = img_path.stem
image_dict[base_name] = str(img_path)
for depth_path in depth_files:
# 提取基础文件名(不含扩展名)
base_name = depth_path.stem
depth_dict[base_name] = str(depth_path)
# 找到匹配的文件对
matched_pairs = []
for base_name in image_dict.keys():
if base_name in depth_dict:
matched_pairs.append((
image_dict[base_name],
depth_dict[base_name],
base_name
))
print(f"找到 {len(matched_pairs)} 对匹配的文件")
return matched_pairs
def png_to_npy_depth(png_path, output_path=None):
"""
将PNG深度图转换为numpy数组格式
Args:
png_path (str): PNG深度图路径
output_path (str): 输出npy文件路径(可选)
Returns:
np.ndarray: 深度数组
"""
# 读取PNG深度图
depth_img = cv2.imread(png_path, cv2.IMREAD_UNCHANGED)
if depth_img is None:
raise ValueError(f"无法读取深度图: {png_path}")
# 如果是3通道图像,转换为单通道
if len(depth_img.shape) == 3:
depth_img = cv2.cvtColor(depth_img, cv2.COLOR_BGR2GRAY)
# 转换为浮点数并归一化
depth_array = depth_img.astype(np.float64)
# 根据深度图的编码方式进行处理
# 假设PNG深度图使用16位编码,需要转换为实际深度值(米)
# 这里可能需要根据具体的深度图编码方式调整
if depth_array.max() > 1.0:
# 如果最大值大于1,假设是16位编码,转换为0-1范围
depth_array = depth_array / 65535.0
# 转换为实际深度值(假设最大深度为15米)
max_depth = 15.0
depth_array = depth_array * max_depth
# 保存为npy文件(如果指定了输出路径)
if output_path:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
np.save(output_path, depth_array)
return depth_array
def generate_sim_data_from_png(image_path, depth_png_path, SBR=0.2, meanSigDetect=4, save_path=None):
"""
从PNG深度图和JPG图像生成仿真数据
Args:
image_path (str): RGB图像文件路径
depth_png_path (str): PNG深度图文件路径
SBR (float): 信号背景比 (默认0.2)
meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4)
save_path (str): 数据保存路径 (.npz文件)
Returns:
tuple: (Z_true, depth_ssp, tBinMax, binDuration)
"""
# 转换PNG深度图为numpy数组
Z_true = png_to_npy_depth(depth_png_path)
# 读取并处理RGB图像
rgb_img = cv2.imread(image_path)
if rgb_img is None:
raise ValueError(f"无法读取图像: {image_path}")
Alpha_true = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY).astype(np.float64)
# 确保两个图像尺寸一致
if Z_true.shape != Alpha_true.shape:
# 将Alpha_true调整为与Z_true相同的尺寸
Alpha_true = cv2.resize(Alpha_true, (Z_true.shape[1], Z_true.shape[0]),
interpolation=cv2.INTER_AREA)
# 动态计算参数
zMax = int(np.max(Z_true) * 1.5) if np.max(Z_true) > 0 else 15
binDuration = zMax / 2e11
# 计算目标尺寸(保持长宽比,缩放到64像素)
target_size = 64
height, width = Z_true.shape
scale = target_size / min(height, width)
new_width = int(width * scale)
new_height = int(height * scale)
# 缩放图像
Z_true = cv2.resize(Z_true, (new_width, new_height), interpolation=cv2.INTER_AREA)
Alpha_true = cv2.resize(Alpha_true, (new_width, new_height), interpolation=cv2.INTER_AREA)
# 生成仿真数据
tBinMax, sigDetect, spad = simsp.generate_simdata(
Z_true, Alpha_true, SBR, meanSigDetect, save_path, zMax, binDuration
)
# 使用SSP算法进行深度估计
from include.singlephoton import SinglePhotonImaging
lr, lc = Z_true.shape
sp = SinglePhotonImaging(lr, lc, binDuration)
# depth_ssp = sp.ssp(spad)
# 保存结果
if save_path:
os.makedirs(os.path.dirname(save_path), exist_ok=True)
dic_data = {
# "depth_ssp": depth_ssp,
"Alpha_true": Alpha_true,
"Z_true": Z_true,
"tBinMax": tBinMax,
"binDuration": binDuration,
"spad_data": spad.data,
"spad_indices": spad.indices,
"spad_indptr": spad.indptr,
"spad_shape": spad.shape,
"sigDetect_data": sigDetect,
}
np.savez_compressed(save_path, **dic_data)
# return Z_true, depth_ssp, tBinMax, binDuration
return Z_true, Alpha_true, tBinMax, binDuration
def process_single_file(args_tuple):
"""
处理单个文件的线程安全函数
Args:
args_tuple: (image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, thread_id)
Returns:
tuple: (success, base_name, error_msg)
"""
image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, thread_id = args_tuple
try:
output_path = os.path.join(output_dir, f"{base_name}.npz")
# 跳过已存在的文件
if os.path.exists(output_path):
return True, base_name, f"文件已存在,跳过: {base_name}"
# 生成仿真数据
generate_sim_data_from_png(
image_path, depth_path,
sbr, meanSigDetect,
output_path
)
return True, base_name, None
except Exception as e:
# 清理GPU内存(如果使用了GPU)
if torch.cuda.is_available():
torch.cuda.empty_cache()
return False, base_name, str(e)
def process_files_multithread(matched_files, output_dir, sbr, meanSigDetect, max_workers=4):
"""
多线程处理文件
Args:
matched_files: 匹配的文件对列表
output_dir: 输出目录
sbr: 信噪比
meanSigDetect: 平均检测信号强度
max_workers: 最大线程数
Returns:
tuple: (success_count, error_count, error_files)
"""
success_count = 0
error_count = 0
error_files = []
# 准备任务参数
tasks = []
for i, (image_path, depth_path, base_name) in enumerate(matched_files):
task_args = (image_path, depth_path, base_name, output_dir, sbr, meanSigDetect, i)
tasks.append(task_args)
# 使用线程池执行任务
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# 提交所有任务
future_to_task = {executor.submit(process_single_file, task): task for task in tasks}
# 使用tqdm显示进度
with tqdm(total=len(tasks), desc="多线程处理进度") as pbar:
for future in as_completed(future_to_task):
task = future_to_task[future]
try:
success, base_name, error_msg = future.result()
if success:
success_count += 1
if error_msg: # 跳过的文件
pbar.set_postfix_str(f"跳过: {base_name}")
else:
error_count += 1
error_files.append((base_name, error_msg))
pbar.set_postfix_str(f"错误: {base_name}")
print(f"\n处理 {base_name} 时发生错误: {error_msg}")
except Exception as e:
error_count += 1
base_name = task[2]
error_files.append((base_name, str(e)))
pbar.set_postfix_str(f"异常: {base_name}")
print(f"\n处理 {base_name} 时发生异常: {str(e)}")
pbar.update(1)
return success_count, error_count, error_files
def main():
parser = argparse.ArgumentParser(description='处理data文件夹生成仿真数据')
parser.add_argument('--sbr', type=float, default=0.5,
help='信噪比 (默认: 0.5)')
parser.add_argument('--meanSigDetect', type=float, default=2,
help='平均检测信号强度 (默认: 2)')
parser.add_argument('--data_dir', type=str, default='./data',
help='数据文件夹路径 (默认: ./data)')
parser.add_argument('--output_dir', type=str, default='./output_data',
help='输出文件夹路径 (默认: ./output_data)')
parser.add_argument('--max_files', type=int, default=None,
help='最大处理文件数量 (默认: 处理所有文件)')
parser.add_argument('--threads', type=int, default=16,
help='线程数量 (默认: 4)')
parser.add_argument('--single_thread', action='store_true',
help='使用单线程模式 (默认: 使用多线程)')
args = parser.parse_args()
# 设置路径
images_dir = os.path.join(args.data_dir, 'images')
depth_dir = os.path.join(args.data_dir, 'depthpng')
output_dir = os.path.join(args.output_dir, f"{args.sbr}_{args.meanSigDetect}")
print(f"图像目录: {images_dir}")
print(f"深度目录: {depth_dir}")
print(f"输出目录: {output_dir}")
# 验证线程数设置
if args.threads < 1:
print("错误: 线程数必须大于0")
return
# 显示处理模式
if args.single_thread:
print("使用单线程模式")
max_workers = 1
else:
max_workers = args.threads
print(f"使用多线程模式,线程数: {max_workers}")
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
# 获取匹配的文件对
try:
matched_files = get_matching_files(images_dir, depth_dir)
except FileNotFoundError as e:
print(f"错误: {e}")
return
if not matched_files:
print("未找到匹配的文件对")
return
# 限制处理文件数量
if args.max_files:
matched_files = matched_files[:args.max_files]
print(f"限制处理文件数量为: {args.max_files}")
# 记录开始时间
start_time = time.time()
# 选择处理模式
if args.single_thread or max_workers == 1:
# 单线程模式(原始逻辑)
success_count = 0
error_count = 0
error_files = []
for image_path, depth_path, base_name in tqdm(matched_files, desc="单线程处理进度"):
output_path = os.path.join(output_dir, f"{base_name}.npz")
# 跳过已存在的文件
if os.path.exists(output_path):
print(f"跳过已存在的文件: {base_name}")
continue
try:
generate_sim_data_from_png(
image_path, depth_path,
args.sbr, args.meanSigDetect,
output_path
)
success_count += 1
except Exception as e:
print(f"处理 {base_name} 时发生错误: {str(e)}")
error_count += 1
error_files.append((base_name, str(e)))
torch.cuda.empty_cache() # 清理GPU内存
else:
# 多线程模式
success_count, error_count, error_files = process_files_multithread(
matched_files, output_dir, args.sbr, args.meanSigDetect, max_workers
)
# 计算处理时间
end_time = time.time()
total_time = end_time - start_time
print(f"\n处理完成!")
print(f"成功处理: {success_count} 个文件")
print(f"处理失败: {error_count} 个文件")
print(f"总处理时间: {total_time:.2f} 秒")
print(f"平均每文件: {total_time/len(matched_files):.2f} 秒")
print(f"输出目录: {output_dir}")
# 显示错误文件详情
if error_files:
print(f"\n错误文件详情:")
for base_name, error_msg in error_files[:10]: # 只显示前10个错误
print(f" {base_name}: {error_msg}")
if len(error_files) > 10:
print(f" ... 还有 {len(error_files) - 10} 个错误文件")
if __name__ == "__main__":
main()
|