json轉yolo格式
視覺分割得一些標注文件是json格式,比如,舌頭將這個舌頭區域分割出來(用mask二值圖的形式),對舌頭的分割第一步是需要檢測出來,缺少數據集,可以使用分割出來的結果,將分割的結果轉化成可以用于目標檢測的數據集。
下面是將json文件轉化成一個yolov8的數據格式,首先看一下json的數據格式:
json的數據格式
我關注的就是"shapes"這個字段因為它是我舌頭區域的坐標點,其次關注的是 “imageHeight”: 圖片的高, “imageWidth”: 圖片的寬。這些在生成yolov8格式的檢測框的時候啥都有用。
{"version": "5.2.1","flags": {},"shapes": [{"fill_color": null,"line_color": null,"label": "tongue","points": [[700.361963190184,510.8926380368097],.......[573.9815950920246,515.1871165644171], ],"group_id": null,"description": null,"shape_type": "polygon","flags": {}}],"imagePath": "0000.jpg","imageData": "iVBORw0KGgoA.....................AAAAAElFTkSuQmCC","imageHeight": 777,"imageWidth": 1286,"fillColor": [255,0,0,128],"lineColor": [0,255,0,128]
}
yolo數據格式
對應的yolov8的數據格式就是yolo系列的標簽存儲形式
yolo系列對應的是[class x y w’ h’]。注意 class也就是label標簽, x y 就是(x, y)表示中心橫坐標與圖像寬度、高度的比值,w’ :檢測框box寬度與圖像寬度比值,h’:檢測框高度與圖像高度比值。
# 一個txt文件
0 0.507394403152401 0.5280297826310096 0.49941035598087944 0.33793653425555276
1 0.407394403152401 0.9280297826310096 0.19941035598087944 0.33793653425555276
2 0.37394403152401 0.5280297826310096 0.19941035598087944 0.13793653425555276
代碼
def json_to_yolov8(data):# 獲取原圖的寬和高image_width = data['imageWidth']image_height = data['imageHeight']for shape in data['shapes']:if shape['label'] == 'tongue':points = shape['points']x_min = min(point[0] for point in points)x_max = max(point[0] for point in points)y_min = min(point[1] for point in points)y_max = max(point[1] for point in points)x_center = (x_min + x_max) / 2y_center = (y_min + y_max) / 2w = x_max - x_minh = y_max - y_minx_center /= image_widthy_center /= image_heightw /= image_widthh /= image_heightyolov8_box = [0, x_center, y_center, w, h]return yolov8_box# Replace 'your_json_file.json' and 'your_image.jpg' with the actual paths
json_folder = "path/to/json" # 輸入json文件的路徑位置
yolov8_labels = 'path/to/txt' # 輸出的目標文件存放路徑
for json_file in os.listdir(json_folder):if json_file.endswith('.json'):json_name = os.path.basename(json_file).split('.')[0]output_file = os.path.join(yolov8_labels, f'{json_name}.txt')jsonfile = os.path.join(json_folder, f'{json_name}.json')with open(jsonfile, 'r') as file:data = json.load(file)yolov8_box = json_to_yolov8(data)with open(output_file, 'w') as f:result_str = ' '.join(str(data) for data in yolov8_box)f.write(result_str)
print("over!")