车位角点检测代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

148 lines
6.1KB

  1. """Perform data augmentation and preprocessing."""
  2. import argparse
  3. import json
  4. import math
  5. import os
  6. import random
  7. import cv2 as cv
  8. import numpy as np
  9. def get_parser():
  10. """Return argument parser for generating dataset."""
  11. parser = argparse.ArgumentParser()
  12. parser.add_argument('--dataset', required=True,
  13. choices=['trainval', 'test'],
  14. help="Generate trainval or test dataset.")
  15. parser.add_argument('--val_prop', type=float, default=0.1,
  16. help="The proportion of val sample in trainval.")
  17. parser.add_argument('--label_directory', required=True,
  18. help="The location of label directory.")
  19. parser.add_argument('--image_directory', required=True,
  20. help="The location of image directory.")
  21. parser.add_argument('--output_directory', required=True,
  22. help="The location of output directory.")
  23. return parser
  24. def boundary_check(centralied_marks):
  25. """Check situation that marking point appears too near to border."""
  26. for mark in centralied_marks:
  27. if mark[0] < -260 or mark[0] > 260 or mark[1] < -260 or mark[1] > 260:
  28. return False
  29. return True
  30. def overlap_check(centralied_marks):
  31. """Check situation that multiple marking points appear in same cell."""
  32. for i in range(len(centralied_marks) - 1):
  33. i_x = centralied_marks[i, 0]
  34. i_y = centralied_marks[i, 1]
  35. for j in range(i + 1, len(centralied_marks)):
  36. j_x = centralied_marks[j, 0]
  37. j_y = centralied_marks[j, 1]
  38. if abs(j_x - i_x) < 600 / 16 and abs(j_y - i_y) < 600 / 16:
  39. return False
  40. return True
  41. def generalize_marks(centralied_marks):
  42. """Convert coordinate to [0, 1] and calculate direction label."""
  43. generalized_marks = []
  44. for mark in centralied_marks:
  45. xval = (mark[0] + 300) / 600
  46. yval = (mark[1] + 300) / 600
  47. direction = math.atan2(mark[3] - mark[1], mark[2] - mark[0])
  48. generalized_marks.append([xval, yval, direction, mark[4]])
  49. return generalized_marks
  50. def write_image_and_label(name, image, centralied_marks, name_list):
  51. """Write image and label with given name."""
  52. name_list.append(os.path.basename(name))
  53. print("Processing NO.%d samples: %s..." % (len(name_list), name_list[-1]))
  54. image = cv.resize(image, (512, 512))
  55. cv.imwrite(name + '.jpg', image, [int(cv.IMWRITE_JPEG_QUALITY), 100])
  56. with open(name + '.json', 'w') as file:
  57. json.dump(generalize_marks(centralied_marks), file)
  58. def rotate_vector(vector, angle_degree):
  59. """Rotate a vector with given angle in degree."""
  60. angle_rad = math.pi * angle_degree / 180
  61. xval = vector[0]*math.cos(angle_rad) + vector[1]*math.sin(angle_rad)
  62. yval = -vector[0]*math.sin(angle_rad) + vector[1]*math.cos(angle_rad)
  63. return xval, yval
  64. def rotate_centralized_marks(centralied_marks, angle_degree):
  65. """Rotate centralized marks with given angle in degree."""
  66. rotated_marks = centralied_marks.copy()
  67. for i in range(centralied_marks.shape[0]):
  68. mark = centralied_marks[i]
  69. rotated_marks[i, 0:2] = rotate_vector(mark[0:2], angle_degree)
  70. rotated_marks[i, 2:4] = rotate_vector(mark[2:4], angle_degree)
  71. return rotated_marks
  72. def rotate_image(image, angle_degree):
  73. """Rotate image with given angle in degree."""
  74. rows, cols, _ = image.shape
  75. rotation_matrix = cv.getRotationMatrix2D((rows/2, cols/2), angle_degree, 1)
  76. return cv.warpAffine(image, rotation_matrix, (rows, cols))
  77. def generate_dataset(args):
  78. """Generate dataset according to arguments."""
  79. if args.dataset == 'trainval':
  80. val_directory = os.path.join(args.output_directory, 'val')
  81. args.output_directory = os.path.join(args.output_directory, 'train')
  82. elif args.dataset == 'test':
  83. args.output_directory = os.path.join(args.output_directory, 'test')
  84. os.makedirs(args.output_directory, exist_ok=True)
  85. name_list = []
  86. for label_file in os.listdir(args.label_directory):
  87. name = os.path.splitext(label_file)[0]
  88. image = cv.imread(os.path.join(args.image_directory, name + '.jpg'))
  89. with open(os.path.join(args.label_directory, label_file), 'r') as file:
  90. label = json.load(file)
  91. centralied_marks = np.array(label['marks'])
  92. if len(centralied_marks.shape) < 2:
  93. centralied_marks = np.expand_dims(centralied_marks, axis=0)
  94. centralied_marks[:, 0:4] -= 300.5
  95. if boundary_check(centralied_marks) or args.dataset == 'test':
  96. output_name = os.path.join(args.output_directory, name)
  97. write_image_and_label(output_name, image,
  98. centralied_marks, name_list)
  99. if args.dataset == 'test':
  100. continue
  101. for angle in range(5, 360, 5):
  102. rotated_marks = rotate_centralized_marks(centralied_marks, angle)
  103. if boundary_check(rotated_marks) and overlap_check(rotated_marks):
  104. rotated_image = rotate_image(image, angle)
  105. output_name = os.path.join(
  106. args.output_directory, name + '_' + str(angle))
  107. write_image_and_label(
  108. output_name, rotated_image, rotated_marks, name_list)
  109. if args.dataset == 'trainval':
  110. print("Dividing training set and validation set...")
  111. val_idx = random.sample(list(range(len(name_list))),
  112. int(round(len(name_list)*args.val_prop)))
  113. val_samples = [name_list[idx] for idx in val_idx]
  114. os.makedirs(val_directory, exist_ok=True)
  115. for val_sample in val_samples:
  116. train_directory = args.output_directory
  117. image_src = os.path.join(train_directory, val_sample + '.jpg')
  118. label_src = os.path.join(train_directory, val_sample + '.json')
  119. image_dst = os.path.join(val_directory, val_sample + '.jpg')
  120. label_dst = os.path.join(val_directory, val_sample + '.json')
  121. os.rename(image_src, image_dst)
  122. os.rename(label_src, label_dst)
  123. print("Done.")
  124. if __name__ == '__main__':
  125. generate_dataset(get_parser().parse_args())