line_dataset.py 7.9 KB

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