File size: 10,942 Bytes
b004d6f | 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 | 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) |