json2yolo.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import json
  2. import os
  3. import numpy as np
  4. from copy import deepcopy
  5. import cv2
  6. def allFilePath(rootPath,allFIleList):
  7. fileList = os.listdir(rootPath)
  8. for temp in fileList:
  9. if os.path.isfile(os.path.join(rootPath,temp)):
  10. allFIleList.append(os.path.join(rootPath,temp))
  11. else:
  12. allFilePath(os.path.join(rootPath,temp),allFIleList)
  13. def xywh2yolo(rect,landmarks_sort,img):
  14. h,w,c =img.shape
  15. rect[0] = max(0, rect[0])
  16. rect[1] = max(0, rect[1])
  17. rect[2] = min(w - 1, rect[2]-rect[0])
  18. rect[3] = min(h - 1, rect[3]-rect[1])
  19. annotation = np.zeros((1, 12))
  20. annotation[0, 0] = (rect[0] + rect[2] / 2) / w # cx
  21. annotation[0, 1] = (rect[1] + rect[3] / 2) / h # cy
  22. annotation[0, 2] = rect[2] / w # w
  23. annotation[0, 3] = rect[3] / h # h
  24. annotation[0, 4] = landmarks_sort[0][0] / w # l0_x
  25. annotation[0, 5] = landmarks_sort[0][1] / h # l0_y
  26. annotation[0, 6] = landmarks_sort[1][0] / w # l1_x
  27. annotation[0, 7] = landmarks_sort[1][1] / h # l1_y
  28. annotation[0, 8] = landmarks_sort[2][0] / w # l2_x
  29. annotation[0, 9] = landmarks_sort[2][1] / h # l2_y
  30. annotation[0, 10] = landmarks_sort[3][0] / w # l3_x
  31. annotation[0, 11] = landmarks_sort[3][1] / h # l3_y
  32. # annotation[0, 12] = (landmarks_sort[0][0]+landmarks_sort[1][0])/2 / w # l4_x
  33. # annotation[0, 13] = (landmarks_sort[0][1]+landmarks_sort[1][1])/2 / h # l4_y
  34. return annotation
  35. def order_points(pts):
  36. rect = np.zeros((4, 2), dtype = "float32")
  37. s = pts.sum(axis = 1)
  38. rect[0] = pts[np.argmin(s)]
  39. rect[2] = pts[np.argmax(s)]
  40. diff = np.diff(pts, axis = 1)
  41. rect[1] = pts[np.argmin(diff)]
  42. rect[3] = pts[np.argmax(diff)]
  43. # return the ordered coordinates
  44. return rect
  45. def four_point_transform(image, pts):
  46. rect = order_points(pts)
  47. (tl, tr, br, bl) = rect
  48. widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
  49. widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
  50. maxWidth = max(int(widthA), int(widthB))
  51. heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
  52. heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
  53. maxHeight = max(int(heightA), int(heightB))
  54. dst = np.array([
  55. [0, 0],
  56. [maxWidth - 1, 0],
  57. [maxWidth - 1, maxHeight - 1],
  58. [0, maxHeight - 1]], dtype = "float32")
  59. M = cv2.getPerspectiveTransform(rect, dst)
  60. warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
  61. # return the warped image
  62. return warped
  63. if __name__ == "__main__":
  64. pic_file_list = []
  65. pic_file = r"/mnt/Gpan/Mydata/pytorchPorject/datasets/ccpd/train_bisai/train_bisai"
  66. save_small_path = "small"
  67. label_file = ['0','1']
  68. allFilePath(pic_file,pic_file_list)
  69. count=0
  70. index = 0
  71. for pic_ in pic_file_list:
  72. if not pic_.endswith(".jpg"):
  73. continue
  74. count+=1
  75. img = cv2.imread(pic_)
  76. img_name = os.path.basename(pic_)
  77. txt_name = img_name.replace(".jpg",".txt")
  78. txt_path = os.path.join(pic_file,txt_name)
  79. json_file_ = pic_.replace(".jpg",".json")
  80. if not os.path.exists(json_file_):
  81. continue
  82. with open(json_file_, 'r',encoding='utf-8') as a:
  83. data_dict = json.load(a)
  84. # print(data_dict['shapes'])
  85. with open(txt_path,"w") as f:
  86. for data_message in data_dict['shapes']:
  87. index+=1
  88. label=data_message['label']
  89. points = data_message['points']
  90. pts = np.array(points)
  91. # pts=order_points(pts)
  92. # new_img = four_point_transform(img,pts)
  93. roi_img_name = label+"_"+str(index)+".jpg"
  94. save_path=os.path.join(save_small_path,roi_img_name)
  95. # cv2.imwrite(save_path,new_img)
  96. x_max,y_max = np.max(pts,axis=0)
  97. x_min,y_min = np.min(pts,axis=0)
  98. rect = [x_min,y_min,x_max,y_max]
  99. rect1=deepcopy(rect)
  100. annotation=xywh2yolo(rect1,pts,img)
  101. print(data_message)
  102. label = data_message['label']
  103. str_label = label_file.index(label)
  104. # str_label = "0 "
  105. str_label = str(str_label)+" "
  106. for i in range(len(annotation[0])):
  107. str_label = str_label + " " + str(annotation[0][i])
  108. str_label = str_label.replace('[', '').replace(']', '')
  109. str_label = str_label.replace(',', '') + '\n'
  110. f.write(str_label)
  111. print(count,img_name)
  112. # point=data_message[points]