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
| """用于从gazebo生成的仿真图像中获取GT信息 """
import numpy as np import cv2 import os import tqdm from math import cos, pi, radians, sin import argparse
LABEL_BYTES = 984003 BYTES_PER_PIXEL = 2 LINES = 61440 LINE_SAMPLES = 184320 LATITUDE_RANGE = 120 LONGITUDE_RANGE = 360 X_PIXEL_RANGE = 61440 Y_PIXEL_RANGE = 184320 scale_factor = 0.1 MOON_RADIUS = 1737.4 radius = MOON_RADIUS * 1000 / 59 * scale_factor BASE_BATCH = 960
def arg_parse(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument( "-c", "--collect_dir", type=str, help="The directory of the collected data", ) arg_parser.add_argument( "-l", "--label_dir", type=str, default="/home/docker/.ros/Data", help="The directory of the label data", ) return arg_parser.parse_args()
def sphere2xyz(lat, lon, dr): """ Warning ! The unit of latitude and longitude is degree. Arguments: lat (float) : latitude, from -90 to 90 lon (float) : longitude, from 0 to 360 """ lat = lat / 180 * pi lon = lon / 180 * pi x = (radius + dr) * np.cos(lat) * np.cos(lon) y = (radius + dr) * np.cos(lat) * np.sin(lon) z = (radius + dr) * np.sin(lat) return x, y, z
def plane2sphere(x, y): """ Return: lat (float) : latitude in degree, from -60 to 60 lon (float) : longitude in degree, from 0 to 360 """ lat = 60 - x * LATITUDE_RANGE / X_PIXEL_RANGE lon = y * LONGITUDE_RANGE / Y_PIXEL_RANGE return lat, lon
def distortCircle(lat, d): """ Arguments: lat (float) : latitude in degree, from -60 to 60 d (float) : diameter in meter """ D_x = d / MOON_RADIUS * X_PIXEL_RANGE / radians(LATITUDE_RANGE) D_y = d / MOON_RADIUS * Y_PIXEL_RANGE / radians(LONGITUDE_RANGE) / cos(radians(lat)) return D_x, D_y
class GTGen: def __init__( self, label_dir, row: range, col: range, origin_point: tuple, K: tuple, size: tuple, ): dem = np.zeros((BASE_BATCH * len(row), BASE_BATCH * len(col)), dtype=np.int16) data = np.zeros((0, 5), dtype=np.float32) for row_ in row: for col_ in col: dem_, data_ = self._load(label_dir, row_, col_) dem[ row_ * BASE_BATCH : (row_ + 1) * BASE_BATCH, col_ * BASE_BATCH : (col_ + 1) * BASE_BATCH, ] = dem_ data = np.vstack((data, data_)) self.dem_ = dem self.origin_point = np.array(origin_point) self.K = np.array(K).reshape(3, 4) self.size = size self.points_ = self.findCraters(self.dem_, data)
@property def dem(self): return self.dem_
@property def points(self): return self.points_
def findCraters(self, dem, data): """ 从DEM中找到所有的陨石坑的边缘三维点,并将其坐标转为直角坐标 """ points = [] for x, y, lat, lon, r in tqdm.tqdm(data, desc="Preparing for crater points"): D_x, D_y = distortCircle(lat, r) mask = np.zeros_like(dem, dtype=np.int16) cv2.ellipse( mask, (int(y), int(x)), (int(D_y / 2), int(D_x / 2)), 0, 0, 360, 1, 2, ) img = mask * dem dr = img[mask != 0] / scale_factor coor = cv2.findNonZero(mask).squeeze() lat, lon = plane2sphere(coor[:, 1], coor[:, 0]) points.append(sphere2xyz(lat, lon, dr)) points_ = np.concatenate(points, axis=1) origin_point = self.origin_point * pi / 180 R = self.Rotate([0, pi / 2 - origin_point[0], origin_point[1]]) T = sphere2xyz(self.origin_point[0], self.origin_point[1], 0) T = -R @ np.array(T) points_ = np.pad(points_, ((0, 1), (0, 0)), "constant", constant_values=1) H = np.hstack((R, T[:, None])) H = np.vstack((H, np.array([0, 0, 0, 1]))) cali_points = H @ points_ return cali_points
def __call__(self, t, pose, ori, output_dir, img=None): """ 输入的是相机在世界坐标系下的位置和姿态,需要输出的是当前位姿条件下陨石坑在图像坐标系下各点位置 Arguments: t (str|float) : 时间戳 pose (list) : Gazebo仿真输出的位置 ori (list) : Gazebo仿真输出的欧拉角姿态,按照Z-Y-X顺序,pitch-yaw-roll顺序排列结果 img (np.ndarray) : 用于显示的图像, optional """ output_dir = os.path.join(output_dir, "gt_images") if not os.path.exists(output_dir): os.makedirs(output_dir) if img is None: img = np.zeros(self.size, dtype=np.uint8) p = self.world2camera(pose, ori) p = np.int32(p) p = self.clip(p) img[p[1], p[0], ...] = 255 cv2.imwrite(f"{output_dir}/{t}.png", img)
@staticmethod def _load(label_dir, row_, col_): with open( os.path.join( label_dir, f"labels/circle/{row_}/lbl_{row_}_{col_}_{BASE_BATCH}.txt" ), "r", ) as reader: dem = np.load( os.path.join( label_dir, f"dem_int16/{row_}/dem_{row_}_{col_}_{BASE_BATCH}.npz" ) )["arr_0"] data = np.array( list( map( lambda x: [ float(x[0]) + row_ * BASE_BATCH, float(x[1]) + col_ * BASE_BATCH, float(x[5]), float(x[6]), float(x[7]), ], map(lambda line: line.strip().split(","), reader), ) ) ) return dem, data
def Rotate(self, ori): """ 三轴转角 """ x, y, z = ori R_x = np.array( [ [1, 0, 0], [0, cos(x), sin(x)], [0, -sin(x), cos(x)], ] ) R_y = np.array( [ [cos(y), 0, -sin(y)], [0, 1, 0], [sin(y), 0, cos(y)], ] ) R_z = np.array( [ [cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1], ] )
return R_x @ R_y @ R_z
def world2camera(self, pose, ori): R = self.Rotate(ori) R_ = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) T = -R @ np.array(pose) H = np.hstack((R, T[:, None])) H = np.vstack((H, np.array([0, 0, 0, 1]))) homo_points = self.K @ R_ @ H @ self.points p = homo_points[:2] / homo_points[-1] return p
def clip(self, points): x = points[0] y = points[1] ind = (x < self.size[0]) & (x >= 0) & (y < self.size[1]) & (y >= 0) return points[:, ind]
if __name__ == "__main__": args = arg_parse() sub_dir = args.label_dir collected_dir = args.collect_dir
num_batches = LINES // BASE_BATCH num_samples = LINE_SAMPLES // BASE_BATCH row = list(range(0, 3)) col = list(range(0, 5))
delta_theta = 120 / num_batches delta_phi = 360 / num_samples origin_point = ( 60 - delta_theta * row[len(row) // 2], 0, ) K = ( 101.574547, 0.0, 128.5, -0.0, 0.0, 101.574547, 128.5, 0.0, 0.0, 0.0, 1.0, 0.0, ) gt_gen = GTGen(sub_dir, row, col, origin_point, K, (256, 256)) image_names = list( map( lambda x: x.removesuffix(".png"), os.listdir(f"{collected_dir}/images"), ) ) with open(f"{collected_dir}/pose.csv", "r") as f: for line in f: data = line.split(",") time = data[0] if time not in image_names: continue if float(time) < 60: continue pose = list(float(x) for x in data[1:4]) ori = [float(data[6]), float(data[4]), float(data[5])] img = cv2.imread(f"{collected_dir}/images/{time}.png") gt_gen(time, pose, ori, collected_dir, img)
|