|
|
| 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: 深度数组
|
| """
|
|
|
| depth_img = cv2.imread(png_path, cv2.IMREAD_UNCHANGED)
|
|
|
| if depth_img is None:
|
| raise ValueError(f"无法读取深度图: {png_path}")
|
|
|
|
|
| if len(depth_img.shape) == 3:
|
| depth_img = cv2.cvtColor(depth_img, cv2.COLOR_BGR2GRAY)
|
|
|
|
|
| depth_array = depth_img.astype(np.float64)
|
|
|
|
|
|
|
|
|
| if depth_array.max() > 1.0:
|
|
|
| depth_array = depth_array / 65535.0
|
|
|
|
|
| max_depth = 15.0
|
| depth_array = depth_array * max_depth
|
|
|
|
|
| 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)
|
| """
|
|
|
| Z_true = png_to_npy_depth(depth_png_path)
|
|
|
|
|
| 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 = 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
|
|
|
|
|
| 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
|
| )
|
|
|
|
|
| from include.singlephoton import SinglePhotonImaging
|
| lr, lc = Z_true.shape
|
| sp = SinglePhotonImaging(lr, lc, binDuration)
|
|
|
|
|
|
|
| if save_path:
|
| os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
| dic_data = {
|
|
|
| "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, 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:
|
|
|
| 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}
|
|
|
|
|
| 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()
|
| 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]:
|
| print(f" {base_name}: {error_msg}")
|
| if len(error_files) > 10:
|
| print(f" ... 还有 {len(error_files) - 10} 个错误文件")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|