# 转换json为txt,并按规则计算坐标
import os
import json
import pandas as pd
def find_annotations(annotations,image_id):
# d = {k: v for k, v in annotations.items() if v > 0}
result=[]
for annotation in annotations:
if annotation['image_id']==image_id:
result.append(annotation)
return result
def jsontotxt(json_path):
txt_path = './txts/'
imginfo = json.load(open(json_path))
for image in imginfo['images']:
image_id=image['id']
image_width=image['width']
image_height=image['height']
image_name=image['file_name']
annotations=find_annotations(imginfo['annotations'],image_id)
fn = txt_path + image_name.replace('.jpg', '.txt')
file = open(fn, 'a')
for ap in annotations: # 将坐标换算成yolov5的需求格式:相对坐标
center_x=ap['bbox'][0]
center_y=ap['bbox'][1]
w=ap['bbox'][2]
h=ap['bbox'][3]
x = center_x / image_width
y = center_y / image_height
w = w / image_width
h = h / image_height
x = round(x, 8)
y = round(y, 8)
w = round(w, 8)
h = round(h, 8)
file.write(str(ap['category_id']-1) + ' ')
file.write(str(x) + ' ')
file.write(str(y) + ' ')
file.write(str(w) + ' ')
file.write(str(h) + '\n')
file.close()
if __name__ == "__main__":
json_path='coco.json'
jsontotxt(json_path)
检测结果
import os
import numpy as np
import cv2 as cv
if __name__ == '__main__':
image_paths='I:/ShenZhenSF/images/train2017'
label_paths='I:/ShenZhenSF/labels/train2017'
img_name=os.listdir(image_paths)
for image_name in img_name:
img_path = os.path.join(image_paths,image_name)
img = np.array(cv.imread(img_path))
H, W, C = img.shape
label_path = os.path.join(label_paths,image_name.replace('jpg','txt'))
boxes = np.loadtxt(label_path, dtype=np.float).reshape(-1, 5)
boxesc=boxes.copy()
# xywh to xyxy
boxes[:, 1] = (boxesc[:, 1] - boxesc[:, 3] / 2) * W
boxes[:, 2] = (boxesc[:, 2] - boxesc[:, 4] / 2) * H
boxes[:, 3] = (boxesc[:, 1] + boxesc[:, 3] / 2) * W
boxes[:, 4] = (boxesc[:, 2] + boxesc[:, 4] / 2) * H
for box in boxes:
ptLeftTop = (int(box[1]), int(box[2])) # (左上角x, 左上角y)
ptRightBottom = (int(box[3]),int( box[4])) # (右下角x, 右下角y)
point_color = (0, 0, 255) # RGB框的颜色,自定
thickness = 1
lineType = 4
cv.rectangle(img, ptLeftTop, ptRightBottom, point_color, thickness, lineType)
cv.imshow('img',img)
cv.waitKey(800)