line_dataset.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. from torch.utils.data.dataset import T_co
  2. from libs.vision_libs.utils import draw_keypoints
  3. from models.base.base_dataset import BaseDataset
  4. import glob
  5. import json
  6. import math
  7. import os
  8. import random
  9. import cv2
  10. import PIL
  11. import matplotlib.pyplot as plt
  12. import matplotlib as mpl
  13. from torchvision.utils import draw_bounding_boxes
  14. import numpy as np
  15. import numpy.linalg as LA
  16. import torch
  17. from skimage import io
  18. from torch.utils.data import Dataset
  19. from torch.utils.data.dataloader import default_collate
  20. import matplotlib.pyplot as plt
  21. from models.dataset_tool import read_masks_from_txt_wire, read_masks_from_pixels_wire, adjacency_matrix
  22. def validate_keypoints(keypoints, image_width, image_height):
  23. for kp in keypoints:
  24. x, y, v = kp
  25. if not (0 <= x < image_width and 0 <= y < image_height):
  26. raise ValueError(f"Key point ({x}, {y}) is out of bounds for image size ({image_width}, {image_height})")
  27. class LineDataset(BaseDataset):
  28. def __init__(self, dataset_path, transforms=None, dataset_type=None, target_type='pixel'):
  29. super().__init__(dataset_path)
  30. self.data_path = dataset_path
  31. print(f'data_path:{dataset_path}')
  32. self.transforms = transforms
  33. self.img_path = os.path.join(dataset_path, "images/" + dataset_type)
  34. self.lbl_path = os.path.join(dataset_path, "labels/" + dataset_type)
  35. self.imgs = os.listdir(self.img_path)
  36. self.lbls = os.listdir(self.lbl_path)
  37. self.target_type = target_type
  38. # self.default_transform = DefaultTransform()
  39. def __getitem__(self, index) -> T_co:
  40. img_path = os.path.join(self.img_path, self.imgs[index])
  41. lbl_path = os.path.join(self.lbl_path, self.imgs[index][:-3] + 'json')
  42. img = PIL.Image.open(img_path).convert('RGB')
  43. w, h = img.size
  44. # wire_labels, target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  45. target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  46. if self.transforms:
  47. img, target = self.transforms(img, target)
  48. else:
  49. img = self.default_transform(img)
  50. # print(f'img:{img}')
  51. return img, target
  52. def __len__(self):
  53. return len(self.imgs)
  54. def read_target(self, item, lbl_path, shape, extra=None):
  55. # print(f'shape:{shape}')
  56. # print(f'lbl_path:{lbl_path}')
  57. with open(lbl_path, 'r') as file:
  58. lable_all = json.load(file)
  59. n_stc_posl = 300
  60. n_stc_negl = 40
  61. use_cood = 0
  62. use_slop = 0
  63. wire = lable_all["wires"][0] # 字典
  64. line_pos_coords = np.random.permutation(wire["line_pos_coords"]["content"])[: n_stc_posl] # 不足,有多少取多少
  65. line_neg_coords = np.random.permutation(wire["line_neg_coords"]["content"])[: n_stc_negl]
  66. npos, nneg = len(line_pos_coords), len(line_neg_coords)
  67. lpre = np.concatenate([line_pos_coords, line_neg_coords], 0) # 正负样本坐标合在一起
  68. for i in range(len(lpre)):
  69. if random.random() > 0.5:
  70. lpre[i] = lpre[i, ::-1]
  71. ldir = lpre[:, 0, :2] - lpre[:, 1, :2]
  72. ldir /= np.clip(LA.norm(ldir, axis=1, keepdims=True), 1e-6, None)
  73. feat = [
  74. lpre[:, :, :2].reshape(-1, 4) / 128 * use_cood,
  75. ldir * use_slop,
  76. lpre[:, :, 2],
  77. ]
  78. feat = np.concatenate(feat, 1)
  79. wire_labels = {
  80. "junc_coords": torch.tensor(wire["junc_coords"]["content"]),
  81. "jtyp": torch.tensor(wire["junc_coords"]["content"])[:, 2].byte(),
  82. "line_pos_idx": adjacency_matrix(len(wire["junc_coords"]["content"]), wire["line_pos_idx"]["content"]),
  83. # 真实存在线条的邻接矩阵
  84. "line_neg_idx": adjacency_matrix(len(wire["junc_coords"]["content"]), wire["line_neg_idx"]["content"]),
  85. "lpre": torch.tensor(lpre)[:, :, :2],
  86. "lpre_label": torch.cat([torch.ones(npos), torch.zeros(nneg)]), # 样本对应标签 1,0
  87. "lpre_feat": torch.from_numpy(feat),
  88. "junc_map": torch.tensor(wire['junc_map']["content"]),
  89. "junc_offset": torch.tensor(wire['junc_offset']["content"]),
  90. "line_map": torch.tensor(wire['line_map']["content"]),
  91. }
  92. labels = []
  93. if self.target_type == 'polygon':
  94. labels, masks = read_masks_from_txt_wire(lbl_path, shape)
  95. elif self.target_type == 'pixel':
  96. labels = read_masks_from_pixels_wire(lbl_path, shape)
  97. # print(torch.stack(masks).shape) # [线段数, 512, 512]
  98. target = {}
  99. target["image_id"] = torch.tensor(item)
  100. # return wire_labels, target
  101. target["wires"] = wire_labels
  102. # target["labels"] = torch.stack(labels)
  103. # print(f'labels:{target["labels"]}')
  104. # target["boxes"] = line_boxes(target)
  105. target["boxes"], keypoints = line_boxes(target)
  106. target["labels"] = torch.ones(len(target["boxes"]), dtype=torch.int64)
  107. # keypoints=keypoints/512
  108. # visibility_flags = torch.ones((wire_labels["junc_coords"].shape[0], 1))
  109. # keypoints= wire_labels["junc_coords"]
  110. a = torch.full((keypoints.shape[0],), 2).unsqueeze(1)
  111. keypoints = torch.cat((keypoints, a), dim=1)
  112. target["keypoints"] = keypoints.to(torch.float32).view(-1,2,3)
  113. # print(f'boxes:{target["boxes"].shape}')
  114. # 在 __getitem__ 方法中调用此函数
  115. validate_keypoints(keypoints, shape[0], shape[1])
  116. # print(f'keypoints:{target["keypoints"].shape}')
  117. # print(f'target:{target}')
  118. return target
  119. def show(self, idx):
  120. image, target = self.__getitem__(idx)
  121. cmap = plt.get_cmap("jet")
  122. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  123. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  124. sm.set_array([])
  125. img_path = os.path.join(self.img_path, self.imgs[idx])
  126. img = PIL.Image.open(img_path).convert('RGB')
  127. boxed_image = draw_bounding_boxes((self.default_transform(img) * 255).to(torch.uint8), target["boxes"],
  128. colors="yellow", width=1)
  129. keypoint_img=draw_keypoints(boxed_image,target['keypoints'],colors='red',width=3)
  130. plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  131. plt.show()
  132. def show_img(self, img_path):
  133. pass
  134. def line_boxes(target):
  135. boxs = []
  136. lpre = target['wires']["lpre"].cpu().numpy()
  137. vecl_target = target['wires']["lpre_label"].cpu().numpy()
  138. lpre = lpre[vecl_target == 1]
  139. lines = lpre
  140. sline = np.ones(lpre.shape[0])
  141. keypoints = []
  142. if len(lines) > 0 and not (lines[0] == 0).all():
  143. for i, ((a, b), s) in enumerate(zip(lines, sline)):
  144. if i > 0 and (lines[i] == lines[0]).all():
  145. break
  146. # plt.plot([a[1], b[1]], [a[0], b[0]], c="red", linewidth=1) # a[1], b[1]无明确大小
  147. keypoints.append([a[1], a[0]])
  148. keypoints.append([b[1], b[0]])
  149. if a[1] > b[1]:
  150. ymax = a[1] + 1
  151. ymin = b[1] - 1
  152. else:
  153. ymin = a[1] - 1
  154. ymax = b[1] + 1
  155. if a[0] > b[0]:
  156. xmax = a[0] + 1
  157. xmin = b[0] - 1
  158. else:
  159. xmin = a[0] - 1
  160. xmax = b[0] + 1
  161. boxs.append([ymin, xmin, ymax, xmax])
  162. return torch.tensor(boxs), torch.tensor(keypoints)
  163. if __name__ == '__main__':
  164. path=r"\\192.168.50.222/share/lm/Dataset_all"
  165. dataset= LineDataset(dataset_path=path, dataset_type='train')
  166. dataset.show(10)