Datasets:
Download codes/simulator/include/simsp.py from shuinb/SP-TransientBench: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/shuinb/SP-TransientBench/resolve/b004d6f6872f37ccfac1d2cc1fa2f0c0ea57c819/codes/simulator/include/simsp.py
- Command line
-
hf download hf://datasets/shuinb/SP-TransientBench@b004d6f6872f37ccfac1d2cc1fa2f0c0ea57c819/codes/simulator/include/simsp.py
-
curl -L -o simsp.py https://huggingface.co/datasets/shuinb/SP-TransientBench/resolve/b004d6f6872f37ccfac1d2cc1fa2f0c0ea57c819/codes/simulator/include/simsp.py
10.9 kB
| import numpy as np | |
| import cv2 | |
| import os | |
| from scipy.sparse import csc_matrix | |
| from include.singlephoton import SinglePhotonImaging | |
| # import os | |
| def fcn_PoissonRV(lambda_, ni=None, nj=None): | |
| """ | |
| 生成泊松分布随机数矩阵 (向量化实现) | |
| 参数: | |
| lambda_ (float/array): 泊松分布参数λ(标量或二维数组) | |
| ni (int): 输出矩阵的行数(当lambda为标量时必填) | |
| nj (int): 输出矩阵的列数(当lambda为标量时必填) | |
| 返回: | |
| np.ndarray: 生成的泊松随机数矩阵[ni, nj] | |
| 异常: | |
| ValueError: 输入参数不符合要求时抛出 | |
| """ | |
| # ========================= 参数验证 ========================= | |
| # 情况1:未指定ni/nj时,lambda必须是二维数组 | |
| if ni is None and nj is None: | |
| if not isinstance(lambda_, np.ndarray) or lambda_.ndim != 2: | |
| raise ValueError("当未指定ni/nj时,lambda必须是二维数组!") | |
| ni, nj = lambda_.shape | |
| # 情况2:指定了ni/nj | |
| elif ni is not None and nj is not None: | |
| # 如果lambda是标量,扩展为指定大小的矩阵 | |
| if np.isscalar(lambda_): | |
| lambda_ = np.full((ni, nj), lambda_) | |
| # 如果lambda是数组,验证形状是否匹配 | |
| elif isinstance(lambda_, np.ndarray) and lambda_.shape != (ni, nj): | |
| raise ValueError(f"lambda形状{lambda_.shape}与({ni},{nj})不匹配!") | |
| # 情况3:参数不完整 | |
| else: | |
| raise ValueError("必须同时指定ni和nj,或都不指定!") | |
| # ========================= 初始化 ========================= | |
| ks1 = np.zeros((ni, nj), dtype=int) # 结果矩阵 | |
| ks2 = np.ones((ni, nj), dtype=int) # 比较矩阵 | |
| produ = np.ones((ni, nj)) # 乘积累加器 | |
| # ========================= 主循环 ========================= | |
| while np.any(ks1 != ks2): | |
| # 更新乘积(向量化操作) | |
| produ *= np.random.rand(ni, nj) | |
| # 保存当前状态 | |
| ks2 = ks1.copy() | |
| # 找出需要增加计数的位置(向量化掩码操作) | |
| mask = produ >= np.exp(-lambda_) | |
| ks1[mask] += 1 | |
| return ks1 | |
| def tof2spad(tof, binnum): | |
| h, w = tof.shape | |
| # 将 data_processed 重塑为列向量 | |
| tof = tof.T | |
| data = tof.reshape(h * w) | |
| # 创建一个大小为 h * w 行,10000 列的零矩阵 | |
| spad = np.zeros((h * w, int(binnum)), dtype=float) | |
| # 遍历 data | |
| for i in range(h * w): | |
| d = data[i] | |
| for j in range(len(d)): | |
| if int(d[j] - 1) < binnum: | |
| spad[i, int(d[j] - 1)] += 1 | |
| spad = csc_matrix(spad) | |
| return spad | |
| def generate_simdata( | |
| Z_true, | |
| Alpha_true, | |
| SBR=0.2, | |
| meanSigDetect=2, | |
| save_path=None, | |
| zMax=15, | |
| binDuration=8e-12, | |
| ): | |
| """ | |
| 生成单光子数据集仿真数据(Python版本) | |
| 参数: | |
| Z_true (array): 深度真值 | |
| Alpha_true (array): 反射率真值 | |
| SBR (float): 信号背景比 (默认0.2) | |
| meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4) | |
| save_path (str): 数据保存路径 (.mat文件) | |
| 返回: | |
| tuple: (tBinMax, binDuration, sigDetect, totDetect) | |
| tBinMax (int): 最大时间bin数 | |
| binDuration (float): 单个时间bin持续时间 (秒) | |
| sigDetect (np.ndarray): 信号光子 | |
| totDetect (np.ndarray): 检测事件对象数组 [H,W] (每个元素包含时间bin序列) | |
| """ | |
| # 第一阶段: 物理参数配置 | |
| # 场景参数 | |
| # zMax = 15.0 # 最大探测距离(米) | |
| # binDuration = 8e-12 # 单个时间bin持续时间(秒) | |
| pulseRMS = 270 / 8 # 脉冲RMS宽度(时间bin数) | |
| # 计算衍生参数 | |
| ttd = 3e8 * binDuration / 2 # 时间到距离转换因子 (米/bin) | |
| tBinMax = int(round(zMax / ttd)) # 最大时间bin数 | |
| pulseSTD = pulseRMS / 2 # 高斯脉冲标准差 | |
| # print("tBinMax:",tBinMax) | |
| # 第二阶段: 信号光子生成 | |
| # 计算时间维度真实值 | |
| T_true = np.floor(Z_true / ttd).astype(int) | |
| # 计算总帧数 | |
| numFrames = int(meanSigDetect * 500) | |
| # 标准化反射率参数 | |
| Lr, Lc = Alpha_true.shape | |
| Alpha_true = meanSigDetect * Alpha_true / np.mean(Alpha_true) / numFrames | |
| # 生成信号光子数(泊松分布) | |
| numSigDetect = fcn_PoissonRV(numFrames * Alpha_true) | |
| actual_mean = np.mean(numSigDetect) | |
| sigDetect = np.empty((Lr, Lc), dtype=object) | |
| sampMean = np.zeros((Lr, Lc)) | |
| # 遍历每个像素生成时间分布 | |
| for i in range(Lr): | |
| for j in range(Lc): | |
| mu = T_true[i, j] | |
| n = numSigDetect[i, j] | |
| # 生成高斯分布时间偏移 | |
| tempVect = np.round(mu + pulseSTD * np.random.randn(n)).astype(int) | |
| sampMean[i, j] = np.mean(tempVect) if n > 0 else 0 | |
| sigDetect[i, j] = tempVect | |
| # 第三阶段: 背景噪声生成 | |
| # 计算背景光子率 | |
| bgndRate = actual_mean / numFrames / SBR | |
| # 生成背景光子数 | |
| numBgndDetect = fcn_PoissonRV(numFrames * bgndRate, Lr, Lc) | |
| bgndDetect = np.empty((Lr, Lc), dtype=object) | |
| # 生成均匀分布时间 | |
| for i in range(Lr): | |
| for j in range(Lc): | |
| n = numBgndDetect[i, j] | |
| bgndDetect[i, j] = np.random.randint(0, tBinMax, n) | |
| # 第四阶段: 数据合并与后处理 | |
| totDetect = np.empty((Lr, Lc), dtype=object) | |
| for i in range(Lr): | |
| for j in range(Lc): | |
| combined = np.concatenate((sigDetect[i, j], bgndDetect[i, j])) | |
| combined = np.sort(combined) | |
| combined = combined[combined > 0] # 移除非法时间bin | |
| totDetect[i, j] = combined | |
| spad = tof2spad(totDetect, tBinMax) | |
| sigDetect = tof2spad(sigDetect, tBinMax) | |
| return tBinMax, sigDetect, spad | |
| # 补充泊松生成函数(原型实现) | |
| def fcn_PoissonRV(lamda, *shape): | |
| if not shape: | |
| return np.random.poisson(lamda) | |
| else: | |
| return np.random.poisson(lamda, shape) | |
| import cv2 | |
| import numpy as np | |
| import os | |
| from scipy.io import savemat | |
| from pathlib import Path | |
| def generate_sim_imageNet( | |
| depth_path, rgb_path, SBR=0.2, meanSigDetect=4, save_path=None | |
| ): | |
| """ | |
| 生成cityscapes数据集仿真数据(Python版本) | |
| 参数: | |
| depth_path (str): 深度图文件路径 (npz) | |
| rgb_path (str): RGB图像文件路径 | |
| SBR (float): 信号背景比 (默认0.2) | |
| meanSigDetect (int): 每像素平均信号光子数 (推荐值2/3/4) | |
| save_path (str): 数据保存路径 (.npz文件) | |
| 返回: | |
| tuple: (Z_true, totDetect, tBinMax, binDuration) | |
| Z_true (np.ndarray): 真实深度图矩阵 [H,W] (单位:米) | |
| totDetect (np.ndarray): 检测事件对象数组 [H,W] (每个元素包含时间bin序列) | |
| tBinMax (int): 最大时间bin数 | |
| binDuration (float): 单个时间bin持续时间 (秒) | |
| PS: | |
| 由于使用DepthAnything数据生成的深度图,是三通道的,所以在处理前需要先将其转换为单通道的 | |
| 为了保证数据兼容性,所以统一提取第一个通道作为深度数据 | |
| """ | |
| # 第一阶段: 基础数据加载与参数初始化 | |
| # 读取深度图并转换为米单位 | |
| # 读取深度图的最大深度 | |
| # binDuration = 4e-10 | |
| # zMax = 15 | |
| # binDuration = zMax/1.5e11 | |
| # 读取深度数据 | |
| Z_true = np.load(depth_path, allow_pickle=True).astype(np.float64) | |
| if Z_true.ndim == 3: | |
| Z_true = Z_true[:, :, 0] | |
| # 1. 避免除零和过小值 | |
| threshold = 1e-10 | |
| Z_affine_safe = np.clip(Z_true, threshold, None) | |
| # 2. 取倒数得到缩放深度 | |
| Z_scaled = 1 / Z_affine_safe | |
| max_value = np.max(Z_scaled) | |
| min_value = np.min(Z_scaled) | |
| # # 3. 截断离群值(可选) | |
| # lower, upper = np.percentile(Z_scaled, [1, 99]) | |
| # Z_clipped = np.clip(Z_scaled, lower, upper) | |
| # 4. 归一化到[0,1] | |
| Z_normalized = (Z_scaled - min_value) / (max_value - min_value) | |
| # 5. 反转方向:近处亮,远处暗 | |
| Z_depth = (1 - Z_normalized)*max_value | |
| # zMax = np.max(Z_true) | |
| zMax = int(np.max(Z_true)*1.5) | |
| binDuration = zMax / 2e11 | |
| # 验证时间箱数量 | |
| ttd = 3e8 * binDuration / 2 # 时间到距离转换因子 (米/bin) | |
| tBinMax = int(round(zMax / ttd)) # 最大时间bin数 | |
| print(f"tBinMax: {tBinMax}") | |
| # 计算深度范围 (必须在缩放前获取原始深度最大值) | |
| # zMax = int(np.max(Z_true) + 1) | |
| # zMax = 15 | |
| # binDuration = 10e-11 | |
| # 计算目标尺寸(保持长宽比) | |
| target_size = 64 | |
| height, width = Z_true.shape | |
| scale = target_size / min(height, width) | |
| new_width = int(width * scale) | |
| new_height = int(height * scale) | |
| # 缩放深度图(使用INTER_AREA保持精度) | |
| Z_true = cv2.resize( | |
| Z_true, | |
| (new_width, new_height), | |
| interpolation=cv2.INTER_AREA | |
| ) | |
| # 读取并处理RGB图像 | |
| rgb_img = cv2.imread(rgb_path) | |
| Alpha_true = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY).astype(np.float64) | |
| # 以相同比例缩放灰度图 | |
| Alpha_true = cv2.resize( | |
| Alpha_true, | |
| (new_width, new_height), | |
| interpolation=cv2.INTER_AREA | |
| ) | |
| # # 输出最终尺寸信息 | |
| # print(f"深度图最终尺寸: {Z_true.shape}") | |
| # print(f"反射率图最终尺寸: {Alpha_true.shape}") | |
| # # 动态计算zMax(忽略深度为0的无效点) | |
| # valid_depths = Z_true[Z_true > 0] # 筛选有效深度点(>0) | |
| # if valid_depths.size > 0: | |
| # zMax = np.max(valid_depths) * 2 # 取最大值并增加10%余量 | |
| # else: | |
| # zMax = 15 # 默认值(无有效点时使用) | |
| tBinMax, sigDetect, spad = generate_simdata( | |
| Z_true, Alpha_true, SBR, meanSigDetect, save_path, zMax, binDuration | |
| ) | |
| lr, lc = Z_true.shape | |
| sp = SinglePhotonImaging(lr, lc, binDuration) | |
| depth = sp.ssp(spad) | |
| if save_path: | |
| # 创建保存目录(如果不存在) | |
| os.makedirs(os.path.dirname(save_path), exist_ok=True) | |
| dic_data = {} | |
| dic_data["depth_ssp"] = depth | |
| dic_data["Z_true"] = Z_true | |
| dic_data["tBinMax"] = tBinMax | |
| dic_data["binDuration"] = binDuration | |
| dic_data["spad_data"] = spad.data | |
| dic_data["spad_indices"] = spad.indices | |
| dic_data["spad_indptr"] = spad.indptr | |
| dic_data["spad_shape"] = spad.shape | |
| dic_data["sigDetect_data"] = sigDetect | |
| # scipy.io.savemat(save_path, dic_data) | |
| np.savez_compressed(save_path, **dic_data) |