labelme_path = 'xxxx' # json文件夹路径
saved_path = 'xxxxx' #保存路径
txt_path = saved_path + '/trainval1/annfiles'
if not os.path.exists(txt_path):
os.makedirs(txt_path)
files = glob(labelme_path + "*.json")
files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]
print(files)
def find_topLeftPopint(dict):
dict_keys = sorted(dict.keys()) # y值
temp = [dict[dict_keys[0]], dict[dict_keys[1]]]
minx = min(temp)
if minx == temp[0]:
miny = dict_keys[0]
else:
miny = dict_keys[1]
return [minx, miny]
for json_file_ in files:
json_filename = labelme_path + json_file_ + ".json"
json_file = json.load(open(json_filename, "r", encoding="utf-8"))
img = cv2.imread(json_filename.replace('json', 'jpg'))
txtname = json_filename.split('/')[-1].replace('json', 'txt')
txt_file = os.path.join(txt_path, txtname)
with open(txt_file, "w+", encoding='UTF-8') as out_file:
for multi in json_file["shapes"]:
points = np.array(np.float32(multi["points"]))
labelName = multi["label"]
rect = cv2.minAreaRect(points)
box = cv2.boxPoints(rect)
box = np.int0(box)
dict = {box[0][1]: box[0][0], box[1][1]: box[1][0], box[2][1]: box[2][0], box[3][1]: box[3][0]}
list = find_topLeftPopint(dict)
if list[0] == box[0][0]:
list_xy = [box[0][0], box[0][1], box[1][0], box[1][1], box[2][0], box[2][1], box[3][0], box[3][1]]
elif list[0] == box[1][0]:
list_xy = [box[1][0], box[1][1], box[2][0], box[2][1], box[3][0], box[3][1], box[0][0], box[0][1]]
elif list[0] == box[2][0]:
list_xy = [box[2][0], box[2][1], box[3][0], box[3][1], box[0][0], box[0][1], box[1][0], box[1][1]]
else:
list_xy = [box[3][0], box[3][1], box[0][0], box[0][1], box[1][0], box[1][1], box[2][0], box[2][1]]
# 在原图上画矩形 看是否转换正确
cv2.line(img, (int(list_xy[0]), int(list_xy[1])), (int(list_xy[2]), int(list_xy[3])), color=(255, 0, 0), thickness=3)
cv2.line(img, (int(list_xy[2]), int(list_xy[3])), (int(list_xy[4]), int(list_xy[5])),color=(0, 255, 0), thickness=3)
cv2.line(img, (int(list_xy[4]), int(list_xy[5])), (int(list_xy[6]), int(list_xy[7])), color=(0, 0, 255), thickness=2)
cv2.line(img, (int(list_xy[6]), int(list_xy[7])), (int(list_xy[0]), int(list_xy[1])), color=(255, 255, 0), thickness=2)
data = str(list_xy[0]) + " " + str(list_xy[1]) + " " + str(list_xy[2]) + " " + str(list_xy[3]) + " " + str(list_xy[4]) + " " + str(list_xy[5]) + " " + str(list_xy[6]) + " " + str(list_xy[7]) + " "
data = data + labelName + " " + "0" + "\n"
out_file.write(data)
cv2.imwrite(os.path.join(saved_path, 'txt', json_filename.split('/')[-1].replace('json', 'png')), img)
labelme 标注的json文件转为旋转框检测的DOTA格式