# 处理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()