| import numpy as np
|
| import cv2
|
| import os
|
| from scipy.sparse import csc_matrix
|
| from include.singlephoton import SinglePhotonImaging
|
|
|
|
|
|
|
| def fcn_PoissonRV(lambda_, ni=None, nj=None):
|
| """
|
| 生成泊松分布随机数矩阵 (向量化实现)
|
|
|
| 参数:
|
| lambda_ (float/array): 泊松分布参数λ(标量或二维数组)
|
| ni (int): 输出矩阵的行数(当lambda为标量时必填)
|
| nj (int): 输出矩阵的列数(当lambda为标量时必填)
|
|
|
| 返回:
|
| np.ndarray: 生成的泊松随机数矩阵[ni, nj]
|
|
|
| 异常:
|
| ValueError: 输入参数不符合要求时抛出
|
| """
|
|
|
|
|
| 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
|
|
|
|
|
| elif ni is not None and nj is not None:
|
|
|
| if np.isscalar(lambda_):
|
| lambda_ = np.full((ni, nj), lambda_)
|
|
|
| elif isinstance(lambda_, np.ndarray) and lambda_.shape != (ni, nj):
|
| raise ValueError(f"lambda形状{lambda_.shape}与({ni},{nj})不匹配!")
|
|
|
|
|
| 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
|
|
|
|
|
| tof = tof.T
|
| data = tof.reshape(h * w)
|
|
|
|
|
| spad = np.zeros((h * w, int(binnum)), dtype=float)
|
|
|
|
|
| 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序列)
|
| """
|
|
|
|
|
|
|
|
|
| pulseRMS = 270 / 8
|
|
|
|
|
| ttd = 3e8 * binDuration / 2
|
| tBinMax = int(round(zMax / ttd))
|
| pulseSTD = pulseRMS / 2
|
|
|
|
|
|
|
|
|
|
|
| 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]
|
| 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数据生成的深度图,是三通道的,所以在处理前需要先将其转换为单通道的
|
| 为了保证数据兼容性,所以统一提取第一个通道作为深度数据
|
| """
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Z_true = np.load(depth_path, allow_pickle=True).astype(np.float64)
|
| if Z_true.ndim == 3:
|
| Z_true = Z_true[:, :, 0]
|
|
|
|
|
| threshold = 1e-10
|
| Z_affine_safe = np.clip(Z_true, threshold, None)
|
|
|
|
|
| Z_scaled = 1 / Z_affine_safe
|
| max_value = np.max(Z_scaled)
|
| min_value = np.min(Z_scaled)
|
|
|
|
|
|
|
|
|
|
|
|
|
| Z_normalized = (Z_scaled - min_value) / (max_value - min_value)
|
|
|
|
|
| Z_depth = (1 - Z_normalized)*max_value
|
|
|
|
|
| zMax = int(np.max(Z_true)*1.5)
|
| binDuration = zMax / 2e11
|
|
|
|
|
| ttd = 3e8 * binDuration / 2
|
| tBinMax = int(round(zMax / ttd))
|
| print(f"tBinMax: {tBinMax}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| )
|
|
|
|
|
| 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
|
| )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
| np.savez_compressed(save_path, **dic_data) |