line_dataset.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. import cv2
  2. import imageio
  3. import numpy as np
  4. from skimage.draw import ellipse
  5. from torch.utils.data.dataset import T_co
  6. from libs.vision_libs.utils import draw_keypoints
  7. from models.base.base_dataset import BaseDataset
  8. import json
  9. import os
  10. import PIL
  11. import matplotlib as mpl
  12. from torchvision.utils import draw_bounding_boxes
  13. import torchvision.transforms.v2 as transforms
  14. import torch
  15. import matplotlib.pyplot as plt
  16. from models.base.transforms import get_transforms
  17. from utils.data_process.show_prams import print_params
  18. def validate_keypoints(keypoints, image_width, image_height):
  19. for kp in keypoints:
  20. x, y, v = kp
  21. if not (0 <= x < image_width and 0 <= y < image_height):
  22. raise ValueError(f"Key point ({x}, {y}) is out of bounds for image size ({image_width}, {image_height})")
  23. """
  24. 直接读取xanlabel标注的数据集json格式
  25. """
  26. class LineDataset(BaseDataset):
  27. def __init__(self, dataset_path, data_type, transforms=None, augmentation=False, dataset_type=None, img_type='rgb',
  28. target_type='pixel'):
  29. super().__init__(dataset_path)
  30. self.data_path = dataset_path
  31. self.data_type = data_type
  32. print(f'data_path:{dataset_path}')
  33. self.transforms = transforms
  34. self.img_path = os.path.join(dataset_path, "images/" + dataset_type)
  35. self.lbl_path = os.path.join(dataset_path, "labels/" + dataset_type)
  36. self.imgs = os.listdir(self.img_path)
  37. self.lbls = os.listdir(self.lbl_path)
  38. self.target_type = target_type
  39. self.img_type = img_type
  40. self.augmentation = augmentation
  41. print(f'augmentation:{augmentation}')
  42. # self.default_transform = DefaultTransform()
  43. def __getitem__(self, index) -> T_co:
  44. img_path = os.path.join(self.img_path, self.imgs[index])
  45. if self.data_type == 'tiff':
  46. lbl_path = os.path.join(self.lbl_path, self.imgs[index][:-4] + 'json')
  47. img = imageio.v3.imread(img_path)[:, :, 0]
  48. print(f'img shape:{img.shape}')
  49. w, h = img.shape[:2]
  50. img = img.reshape(w, h, 1)
  51. img_3channel = np.zeros((w, h, 3), dtype=img.dtype)
  52. img_3channel[:, :, 2] = img[:, :, 0]
  53. img = torch.from_numpy(img_3channel).permute(2, 1, 0)
  54. else:
  55. lbl_path = os.path.join(self.lbl_path, self.imgs[index][:-3] + 'json')
  56. img = PIL.Image.open(img_path).convert('RGB')
  57. w, h = img.size
  58. # wire_labels, target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  59. target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  60. self.transforms = get_transforms(augmention=self.augmentation)
  61. img, target = self.transforms(img, target)
  62. return img, target
  63. def __len__(self):
  64. return len(self.imgs)
  65. def read_target(self, item, lbl_path, shape, extra=None):
  66. # print(f'shape:{shape}')
  67. # print(f'lbl_path:{lbl_path}')
  68. with open(lbl_path, 'r') as file:
  69. lable_all = json.load(file)
  70. objs = lable_all["shapes"]
  71. point_pairs = objs[0]['points']
  72. # print(f'point_pairs:{point_pairs}')
  73. target = {}
  74. target["image_id"] = torch.tensor(item)
  75. #boxes, line_point_pairs, points, labels, mask_ends, mask_params
  76. boxes, lines, points, labels, arc_ends, arc_params = get_boxes_lines(objs, shape)
  77. # print_params(arc_ends, arc_params)
  78. if points is not None:
  79. target["points"] = points
  80. # if lines is not None:
  81. # a = torch.full((lines.shape[0],), 2).unsqueeze(1)
  82. # lines = torch.cat((lines, a), dim=1)
  83. # target["lines"] = lines.to(torch.float32).view(-1, 2, 3)
  84. if lines is not None:
  85. label_3d = labels.view(-1, 1, 1).expand(-1, 2, -1) # [N] -> [N,2,1]
  86. line1 = torch.cat([lines, label_3d], dim=-1) # [N,2,3]
  87. target["lines"] = line1.to(torch.float32)
  88. if arc_ends is not None:
  89. target['mask_ends'] = arc_ends
  90. if arc_params is not None:
  91. target['mask_params'] = arc_params
  92. arc_angles = compute_arc_angles(arc_ends, arc_params)
  93. # print_params(arc_angles)
  94. arc_masks = []
  95. for i in range(len(arc_params)):
  96. arc_param_i = arc_params[i].view(-1) # shape (5,)
  97. arc_angle_i = arc_angles[i].view(-1) # shape (2,)
  98. arc7 = torch.cat([arc_param_i, arc_angle_i], dim=0) # shape (7,)
  99. print_params(arc7)
  100. mask = arc_to_mask(arc7, shape, line_width=1)
  101. arc_masks.append(mask)
  102. # arc7=arc_params[i] + arc_angles[i].tolist()
  103. # arc_masks.append(arc_to_mask(arc7, shape, line_width=1))
  104. # print(f'circle_masks:{torch.stack(arc_masks, dim=0).shape}')
  105. target['circle_masks'] = torch.stack(arc_masks, dim=0)
  106. target["boxes"] = boxes
  107. target["labels"] = labels
  108. # target["boxes"], lines,target["points"], target["labels"] = get_boxes_lines(objs,shape)
  109. # print(f'lines:{lines}')
  110. # target["labels"] = torch.ones(len(target["boxes"]), dtype=torch.int64)
  111. # print(f'target points:{target["points"]}')
  112. # target["lines"] = lines.to(torch.float32).view(-1,2,3)
  113. # print(f'')
  114. # print(f'lines:{target["lines"].shape}')
  115. target["img_size"] = shape
  116. # validate_keypoints(lines, shape[0], shape[1])
  117. return target
  118. def show(self, idx, show_type='all'):
  119. image, target = self.__getitem__(idx)
  120. cmap = plt.get_cmap("jet")
  121. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  122. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  123. sm.set_array([])
  124. # img_path = os.path.join(self.img_path, self.imgs[idx])
  125. # print(f'boxes:{target["boxes"]}')
  126. img = image
  127. if show_type == 'arc_masks':
  128. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), target["boxes"],
  129. colors="yellow", width=1)
  130. # arc = target['arc']
  131. arc_mask = target['arc_masks']
  132. # print(f'taget circle:{arc.shape}')
  133. print(f'target circle_masks:{arc_mask.shape}')
  134. plt.imshow(arc_mask.squeeze(0))
  135. plt.show()
  136. if show_type == 'circle_masks':
  137. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), target["boxes"],
  138. colors="yellow", width=1)
  139. circle = target['circles']
  140. circle_mask = target['circle_masks']
  141. print(f'taget circle:{circle.shape}')
  142. print(f'target circle_masks:{circle_mask.shape}')
  143. plt.imshow(circle_mask.squeeze(0))
  144. keypoint_img = draw_keypoints(boxed_image, circle, colors='red', width=3)
  145. # plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  146. plt.show()
  147. # if show_type=='lines':
  148. # keypoint_img=draw_keypoints((img * 255).to(torch.uint8),target['lines'],colors='red',width=3)
  149. # plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  150. # plt.show()
  151. if show_type == 'points':
  152. # print(f'points:{target['points'].shape}')
  153. keypoint_img = draw_keypoints((img * 255).to(torch.uint8), target['points'].unsqueeze(1), colors='red',
  154. width=3)
  155. plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  156. plt.show()
  157. if show_type == 'boxes':
  158. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), target["boxes"],
  159. colors="yellow", width=1)
  160. plt.imshow(boxed_image.permute(1, 2, 0).numpy())
  161. plt.show()
  162. def show_img(self, img_path):
  163. pass
  164. def draw_el(all):
  165. # 解析椭圆参数
  166. if isinstance(all, torch.Tensor):
  167. all = all.cpu().numpy()
  168. x, y, a, b, q, q1, q2 = all
  169. theta = np.radians(q)
  170. phi1 = np.radians(q1) # 第一个点的参数角
  171. phi2 = np.radians(q2) # 第二个点的参数角
  172. # 生成椭圆上的点
  173. phi = np.linspace(0, 2 * np.pi, 500)
  174. x_ellipse = x + a * np.cos(phi) * np.cos(theta) - b * np.sin(phi) * np.sin(theta)
  175. y_ellipse = y + a * np.cos(phi) * np.sin(theta) + b * np.sin(phi) * np.cos(theta)
  176. # 计算两个指定点的坐标
  177. def param_to_point(phi, xc, yc, a, b, theta):
  178. x = xc + a * np.cos(phi) * np.cos(theta) - b * np.sin(phi) * np.sin(theta)
  179. y = yc + a * np.cos(phi) * np.sin(theta) + b * np.sin(phi) * np.cos(theta)
  180. return x, y
  181. P1 = param_to_point(phi1, x, y, a, b, theta)
  182. P2 = param_to_point(phi2, x, y, a, b, theta)
  183. # 创建画布并显示背景图片(使用传入的background_img,shape为[H, W, C])
  184. plt.figure(figsize=(10, 10))
  185. # plt.imshow(background_img) # 直接显示背景图
  186. # 绘制椭圆及相关元素
  187. plt.plot(x_ellipse, y_ellipse, 'b-', linewidth=2)
  188. plt.plot(x, y, 'ko', markersize=8)
  189. plt.plot(P1[0], P1[1], 'ro', markersize=10)
  190. plt.plot(P2[0], P2[1], 'go', markersize=10)
  191. plt.show()
  192. def arc_to_mask(arc7, shape, line_width=1):
  193. """
  194. Generate a binary mask of an elliptical arc.
  195. Args:
  196. xc, yc (float): 椭圆中心
  197. a, b (float): 长半轴、短半轴 (a >= b)
  198. theta (float): 椭圆旋转角度(**弧度**,逆时针,相对于 x 轴)
  199. phi1, phi2 (float): 起始和终止参数角(**弧度**,在 [0, 2π) 内)
  200. H, W (int): 输出 mask 的高度和宽度
  201. line_width (int): 弧线宽度(像素)
  202. Returns:
  203. mask (Tensor): [H, W], dtype=torch.uint8, 0/255
  204. """
  205. # print_params(arc7)
  206. # 确保 phi1 -> phi2 是正向(可处理跨 2π 的情况)
  207. if torch.all(torch.tensor(arc7) == 0):
  208. return torch.zeros(shape, dtype=torch.uint8)
  209. xc, yc, a, b, theta, phi1, phi2 = arc7
  210. H, W = shape
  211. if phi2 < phi1:
  212. phi2 += 2 * np.pi
  213. # 生成参数角(足够密集,避免断线)
  214. num_points = max(int(200 * abs(phi2 - phi1) / (2 * np.pi)), 10)
  215. phi = np.linspace(phi1, phi2, num_points)
  216. # 椭圆参数方程(先在未旋转坐标系下计算)
  217. x_local = a * np.cos(phi)
  218. y_local = b * np.sin(phi)
  219. # 应用旋转和平移
  220. cos_t = np.cos(theta)
  221. sin_t = np.sin(theta)
  222. x_rot = x_local * cos_t - y_local * sin_t + xc
  223. y_rot = x_local * cos_t + y_local * sin_t + yc
  224. # 转为整数坐标(OpenCV 需要 int32)
  225. points = np.stack([x_rot, y_rot], axis=1).astype(np.int32)
  226. # 创建空白图像
  227. img = np.zeros((H, W), dtype=np.uint8)
  228. # 绘制折线(antialias=False 更适合 mask)
  229. cv2.polylines(img, [points], isClosed=False, color=255, thickness=line_width, lineType=cv2.LINE_AA)
  230. return torch.from_numpy(img).float() # [H, W], values: 0 or 255
  231. def compute_arc_angles(gt_mask_ends, gt_mask_params):
  232. """
  233. 给定椭圆上的一个点,计算其对应的参数角 phi(弧度)。
  234. Parameters:
  235. point: tuple or array-like, (x, y)
  236. ellipse_param: tuple or array-like, (xc, yc, a, b, theta)
  237. Returns:
  238. phi: float, in [0, 2*pi)
  239. """
  240. # print_params(gt_mask_ends, gt_mask_params)
  241. results = []
  242. if not isinstance(gt_mask_params, torch.Tensor):
  243. gt_mask_params_tensor = torch.tensor(gt_mask_params, dtype=gt_mask_ends.dtype, device=gt_mask_ends.device)
  244. else:
  245. gt_mask_params_tensor = gt_mask_params.clone().detach().to(gt_mask_ends)
  246. for ends_img, params_img in zip(gt_mask_ends, gt_mask_params_tensor):
  247. # print(f'params_img:{params_img}')
  248. if torch.norm(params_img) < 1e-6: # L2 norm near zero
  249. results.append(torch.zeros(2, device=params_img.device, dtype=params_img.dtype))
  250. continue
  251. x, y = ends_img
  252. xc, yc, a, b, theta = params_img
  253. # 1. 平移到中心
  254. dx = x - xc
  255. dy = y - yc
  256. # 2. 逆旋转(旋转 -theta)
  257. cos_t = torch.cos(theta)
  258. sin_t = torch.sin(theta)
  259. X = dx * cos_t + dy * sin_t
  260. Y = -dx * sin_t + dy * cos_t
  261. # 3. 归一化到单位圆(除以 a, b)
  262. cos_phi = X / a
  263. sin_phi = Y / b
  264. # 4. 用 atan2 求角度(自动处理象限)
  265. phi = torch.atan2(sin_phi, cos_phi)
  266. # 5. 转换到 [0, 2π)
  267. phi = torch.where(phi < 0, phi + 2 * torch.pi, phi)
  268. results.append(phi)
  269. return results
  270. def points_to_ellipse(points):
  271. """
  272. 根据提供的四个点估计椭圆参数。
  273. :param points: Tensor of shape (4, 2) 表示椭圆上的四个点
  274. :return: 返回 (cx, cy, r1, r2, orientation) 其中 cx, cy 是中心坐标,r1, r2 分别是长轴和短轴半径,orientation 是椭圆的方向(弧度)
  275. """
  276. # 转换为numpy数组进行计算
  277. pts = points.numpy()
  278. pts = pts.reshape(-1, 2)
  279. center = np.mean(pts, axis=0)
  280. A = np.hstack(
  281. [pts[:, 0:1] ** 2, pts[:, 0:1] * pts[:, 1:2], pts[:, 1:2] ** 2, pts[:, :2], np.ones((pts.shape[0], 1))])
  282. b = np.ones(pts.shape[0])
  283. x = np.linalg.lstsq(A, b, rcond=None)[0]
  284. # 解析解参见 https://en.wikipedia.org/wiki/Ellipse#General_ellipse
  285. a, b, c, d, f, g = x.ravel()
  286. numerator = 2 * (a * f * f + c * d * d + g * b * b - 2 * b * d * f - a * c * g)
  287. denominator1 = (b * b - a * c) * ((c - a) * np.sqrt(1 + 4 * b * b / ((a - c) * (a - c))) - (c + a))
  288. denominator2 = (b * b - a * c) * ((a - c) * np.sqrt(1 + 4 * b * b / ((a - c) * (a - c))) - (c + a))
  289. major_axis = np.sqrt(numerator / denominator1)
  290. minor_axis = np.sqrt(numerator / denominator2)
  291. distances = np.linalg.norm(pts - center, axis=1)
  292. long_axis_length = np.max(distances) * 2
  293. short_axis_length = np.min(distances) * 2
  294. orientation = np.arctan2(pts[1, 1] - pts[0, 1], pts[1, 0] - pts[0, 0])
  295. return center[0], center[1], long_axis_length / 2, short_axis_length / 2, orientation
  296. def generate_ellipse_mask(shape, ellipse_params):
  297. """
  298. 在指定形状的图像上生成椭圆mask。
  299. :param shape: 输出mask的形状 (HxW)
  300. :param ellipse_params: 椭圆参数 (cx, cy, rx, ry, orientation)
  301. :return: 椭圆mask
  302. """
  303. cx, cy, rx, ry, orientation = ellipse_params
  304. img = np.zeros(shape, dtype=np.uint8)
  305. cx, cy, rx, ry = int(cx), int(cy), int(rx), int(ry)
  306. rr, cc = ellipse(cy, cx, ry, rx, shape)
  307. img[rr, cc] = 1
  308. return img
  309. def sort_points_clockwise(points):
  310. points = np.array(points)
  311. top_left_idx = np.lexsort((points[:, 0], points[:, 1]))[0]
  312. reference_point = points[top_left_idx]
  313. def angle_to_reference(point):
  314. return np.arctan2(point[1] - reference_point[1], point[0] - reference_point[0])
  315. angles = np.apply_along_axis(angle_to_reference, 1, points)
  316. angles[angles < 0] += 2 * np.pi
  317. sorted_indices = np.argsort(angles)
  318. sorted_points = points[sorted_indices]
  319. return sorted_points.tolist()
  320. def get_boxes_lines(objs, shape):
  321. boxes = []
  322. labels = []
  323. h, w = shape
  324. line_point_pairs = []
  325. points = []
  326. mask_ends = []
  327. mask_params = []
  328. for obj in objs:
  329. # plt.plot([a[1], b[1]], [a[0], b[0]], c="red", linewidth=1) # a[1], b[1]无明确大小
  330. # print(f"points:{obj['points']}")
  331. label = obj['label']
  332. if label == 'line' or label == 'dseam1':
  333. a, b = obj['points'][0], obj['points'][1]
  334. # line_point_pairs.append(a)
  335. # line_point_pairs.append(b)
  336. line_point_pairs.append([a, b])
  337. xmin = max(0, (min(a[0], b[0]) - 6))
  338. xmax = min(w, (max(a[0], b[0]) + 6))
  339. ymin = max(0, (min(a[1], b[1]) - 6))
  340. ymax = min(h, (max(a[1], b[1]) + 6))
  341. boxes.append([xmin, ymin, xmax, ymax])
  342. labels.append(torch.tensor(2))
  343. points.append(torch.tensor([0.0]))
  344. mask_ends.append([[0, 0], [0, 0]])
  345. mask_params.append([0, 0, 0, 0, 0])
  346. # circle_4points.append([[0, 0], [0, 0], [0, 0], [0, 0]])
  347. elif label == 'point':
  348. p = obj['points'][0]
  349. xmin = max(0, p[0] - 12)
  350. xmax = min(w, p[0] + 12)
  351. ymin = max(0, p[1] - 12)
  352. ymax = min(h, p[1] + 12)
  353. points.append(p)
  354. labels.append(torch.tensor(1))
  355. boxes.append([xmin, ymin, xmax, ymax])
  356. line_point_pairs.append([[0, 0], [0, 0]])
  357. mask_ends.append([[0, 0], [0, 0]])
  358. mask_params.append([0, 0, 0, 0, 0])
  359. # circle_4points.append([[0, 0], [0, 0], [0, 0], [0, 0]])
  360. # elif label == 'arc':
  361. # arc_points = obj['points']
  362. # arc_params = obj['params']
  363. # arc_ends = obj['ends']
  364. # line_mask.append(arc_points)
  365. # mask_ends.append(arc_ends)
  366. # mask_params.append(arc_params)
  367. #
  368. # xs = [p[0] for p in arc_points]
  369. # ys = [p[1] for p in arc_points]
  370. # xmin, xmax = min(xs), max(xs)
  371. # ymin, ymax = min(ys), max(ys)
  372. #
  373. # boxes.append([xmin, ymin, xmax, ymax])
  374. # labels.append(torch.tensor(3))
  375. #
  376. # points.append(torch.tensor([0.0]))
  377. # line_point_pairs.append([[0, 0], [0, 0]])
  378. # circle_4points.append([[0, 0], [0, 0], [0, 0], [0, 0]])
  379. elif label == 'arc':
  380. arc_params = obj['params']
  381. arc_ends = obj['ends']
  382. mask_ends.append(arc_ends)
  383. mask_params.append(arc_params)
  384. arc3points = obj['points']
  385. xs = [p[0] for p in arc3points]
  386. ys = [p[1] for p in arc3points]
  387. xmin_raw = min(xs)
  388. xmax_raw = max(xs)
  389. ymin_raw = min(ys)
  390. ymax_raw = max(ys)
  391. xmin = max(xmin_raw - 40, 0)
  392. xmax = min(xmax_raw + 40, w)
  393. ymin = max(ymin_raw - 40, 0)
  394. ymax = min(ymax_raw + 40, h)
  395. boxes.append([xmin, ymin, xmax, ymax])
  396. labels.append(torch.tensor(4))
  397. points.append(torch.tensor([0.0]))
  398. line_point_pairs.append([[0, 0], [0, 0]])
  399. boxes = torch.tensor(boxes, dtype=torch.float32)
  400. print(f'boxes:{boxes.shape}')
  401. labels = torch.tensor(labels)
  402. if points:
  403. points = torch.tensor(points, dtype=torch.float32)
  404. else:
  405. points = None
  406. if line_point_pairs:
  407. line_point_pairs = torch.tensor(line_point_pairs, dtype=torch.float32)
  408. else:
  409. line_point_pairs = None
  410. if mask_ends:
  411. mask_ends = torch.tensor(mask_ends, dtype=torch.float32)
  412. else:
  413. mask_ends = None
  414. if mask_params:
  415. mask_params = torch.tensor(mask_params, dtype=torch.float32)
  416. else:
  417. mask_params = None
  418. return boxes, line_point_pairs, points, labels, mask_ends, mask_params
  419. if __name__ == '__main__':
  420. path = r'\\192.168.50.222/share/lm/1112/a_dataset'
  421. dataset = LineDataset(dataset_path=path, dataset_type='train', augmentation=False, data_type='jpg')
  422. dataset.show(9, show_type='arc_masks')