keypoint_dataset.py 7.7 KB

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