line_dataset.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 json
  5. import os
  6. import PIL
  7. import matplotlib as mpl
  8. from torchvision.utils import draw_bounding_boxes
  9. import torchvision.transforms.v2 as transforms
  10. import torch
  11. import matplotlib.pyplot as plt
  12. from models.base.transforms import get_transforms
  13. def validate_keypoints(keypoints, image_width, image_height):
  14. for kp in keypoints:
  15. x, y, v = kp
  16. if not (0 <= x < image_width and 0 <= y < image_height):
  17. raise ValueError(f"Key point ({x}, {y}) is out of bounds for image size ({image_width}, {image_height})")
  18. """
  19. 直接读取xanlabel标注的数据集json格式
  20. """
  21. class LineDataset(BaseDataset):
  22. def __init__(self, dataset_path, data_type, transforms=None,augmentation=False, dataset_type=None,img_type='rgb', target_type='pixel'):
  23. super().__init__(dataset_path)
  24. self.data_path = dataset_path
  25. self.data_type = data_type
  26. print(f'data_path:{dataset_path}')
  27. self.transforms = transforms
  28. self.img_path = os.path.join(dataset_path, "images/" + dataset_type)
  29. self.lbl_path = os.path.join(dataset_path, "labels/" + dataset_type)
  30. self.imgs = os.listdir(self.img_path)
  31. self.lbls = os.listdir(self.lbl_path)
  32. self.target_type = target_type
  33. self.img_type=img_type
  34. self.augmentation=augmentation
  35. print(f'augmentation:{augmentation}')
  36. # self.default_transform = DefaultTransform()
  37. def __getitem__(self, index) -> T_co:
  38. img_path = os.path.join(self.img_path, self.imgs[index])
  39. lbl_path = os.path.join(self.lbl_path, self.imgs[index][:-3] + 'json')
  40. img = PIL.Image.open(img_path).convert('RGB')
  41. w, h = img.size
  42. # wire_labels, target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  43. target = self.read_target(item=index, lbl_path=lbl_path, shape=(h, w))
  44. self.transforms=get_transforms(augmention=self.augmentation)
  45. img, target = self.transforms(img, target)
  46. return img, target
  47. def __len__(self):
  48. return len(self.imgs)
  49. def read_target(self, item, lbl_path, shape, extra=None):
  50. # print(f'shape:{shape}')
  51. # print(f'lbl_path:{lbl_path}')
  52. with open(lbl_path, 'r') as file:
  53. lable_all = json.load(file)
  54. objs = lable_all["shapes"]
  55. point_pairs=objs[0]['points']
  56. # print(f'point_pairs:{point_pairs}')
  57. target = {}
  58. target["image_id"] = torch.tensor(item)
  59. target["boxes"], lines,target["points"], target["labels"] = get_boxes_lines(objs,shape)
  60. # print(f'lines:{lines}')
  61. # target["labels"] = torch.ones(len(target["boxes"]), dtype=torch.int64)
  62. # print(f'target points:{target["points"]}')
  63. a = torch.full((lines.shape[0],), 2).unsqueeze(1)
  64. lines = torch.cat((lines, a), dim=1)
  65. target["lines"] = lines.to(torch.float32).view(-1,2,3)
  66. print(f'lines:{target["lines"].shape}')
  67. target["img_size"]=shape
  68. validate_keypoints(lines, shape[0], shape[1])
  69. return target
  70. def show(self, idx,show_type='all'):
  71. image, target = self.__getitem__(idx)
  72. cmap = plt.get_cmap("jet")
  73. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  74. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  75. sm.set_array([])
  76. # img_path = os.path.join(self.img_path, self.imgs[idx])
  77. img = image
  78. if show_type=='all':
  79. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), target["boxes"],
  80. colors="yellow", width=1)
  81. keypoint_img=draw_keypoints(boxed_image,target['lines'],colors='red',width=3)
  82. plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  83. plt.show()
  84. if show_type=='lines':
  85. keypoint_img=draw_keypoints((img * 255).to(torch.uint8),target['lines'],colors='red',width=3)
  86. plt.imshow(keypoint_img.permute(1, 2, 0).numpy())
  87. plt.show()
  88. if show_type=='boxes':
  89. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), target["boxes"],
  90. colors="yellow", width=1)
  91. plt.imshow(boxed_image.permute(1, 2, 0).numpy())
  92. plt.show()
  93. def show_img(self, img_path):
  94. pass
  95. def get_boxes_lines(objs,shape):
  96. boxes = []
  97. labels=[]
  98. h,w=shape
  99. line_point_pairs = []
  100. points=[]
  101. for obj in objs:
  102. # plt.plot([a[1], b[1]], [a[0], b[0]], c="red", linewidth=1) # a[1], b[1]无明确大小
  103. # print(f"points:{obj['points']}")
  104. label=obj['label']
  105. if label =='line':
  106. a,b=obj['points'][0],obj['points'][1]
  107. line_point_pairs.append(a)
  108. line_point_pairs.append(b)
  109. xmin = max(0, (min(a[0], b[0]) - 6))
  110. xmax = min(w, (max(a[0], b[0]) + 6))
  111. ymin = max(0, (min(a[1], b[1]) - 6))
  112. ymax = min(h, (max(a[1], b[1]) + 6))
  113. boxes.append([ xmin,ymin, xmax,ymax])
  114. labels.append(torch.tensor(2))
  115. elif label =='point':
  116. p= obj['points'][0]
  117. xmin=max(0,p[0]-6)
  118. xmax = min(w, p[0] +6)
  119. ymin=max(0,p[1]-6)
  120. ymax = max(h, p[1] + 6)
  121. points.append(p)
  122. labels.append(torch.tensor(1))
  123. boxes.append([xmin, ymin, xmax, ymax])
  124. elif label =='arc':
  125. labels.append(torch.tensor(3))
  126. boxes=torch.tensor(boxes)
  127. labels=torch.tensor(labels)
  128. points=torch.tensor(points)
  129. # print(f'read labels:{labels}')
  130. # print(f'read points:{points}')
  131. line_point_pairs=torch.tensor(line_point_pairs)
  132. # print(f'boxes:{boxes.shape},line_point_pairs:{line_point_pairs.shape}')
  133. return boxes,line_point_pairs,points,labels
  134. if __name__ == '__main__':
  135. path=r"\\192.168.50.222/share/rlq/datasets/0706_"
  136. dataset= LineDataset(dataset_path=path, dataset_type='train',augmentation=True, data_type='jpg')
  137. dataset.show(1,show_type='all')