Skip to content

Commit 035d103

Browse files
committed
Add pre-commit and add TODO
1 parent d1cb809 commit 035d103

File tree

6 files changed

+395
-349
lines changed

6 files changed

+395
-349
lines changed

coco_2_labelImg.py

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -10,83 +10,85 @@
1010
from tqdm import tqdm
1111

1212

13-
class COCO2labelImg():
13+
class COCO2labelImg:
1414
def __init__(self, data_dir: str = None):
1515
# coco dir
1616
self.data_dir = Path(data_dir)
1717
self.verify_exists(self.data_dir)
1818

19-
anno_dir = self.data_dir / 'annotations'
19+
anno_dir = self.data_dir / "annotations"
2020
self.verify_exists(anno_dir)
2121

22-
self.train_json = anno_dir / 'instances_train2017.json'
23-
self.val_json = anno_dir / 'instances_val2017.json'
22+
self.train_json = anno_dir / "instances_train2017.json"
23+
self.val_json = anno_dir / "instances_val2017.json"
2424
self.verify_exists(self.train_json)
2525
self.verify_exists(self.val_json)
2626

27-
self.train2017_dir = self.data_dir / 'train2017'
28-
self.val2017_dir = self.data_dir / 'val2017'
27+
self.train2017_dir = self.data_dir / "train2017"
28+
self.val2017_dir = self.data_dir / "val2017"
2929
self.verify_exists(self.train2017_dir)
3030
self.verify_exists(self.val2017_dir)
3131

3232
# save dir
33-
self.save_dir = self.data_dir.parent / 'COCO_labelImg_format'
33+
self.save_dir = self.data_dir.parent / "COCO_labelImg_format"
3434
self.mkdir(self.save_dir)
3535

36-
self.save_train_dir = self.save_dir / 'train'
36+
self.save_train_dir = self.save_dir / "train"
3737
self.mkdir(self.save_train_dir)
3838

39-
self.save_val_dir = self.save_dir / 'val'
39+
self.save_val_dir = self.save_dir / "val"
4040
self.mkdir(self.save_val_dir)
4141

42-
def __call__(self, ):
42+
def __call__(
43+
self,
44+
):
4345
train_list = [self.train_json, self.save_train_dir, self.train2017_dir]
4446
self.convert(train_list)
4547

4648
val_list = [self.val_json, self.save_val_dir, self.val2017_dir]
4749
self.convert(val_list)
4850

49-
print(f'Successfully convert, detail in {self.save_dir}')
51+
print(f"Successfully convert, detail in {self.save_dir}")
5052

5153
def convert(self, info_list: list):
5254
json_path, save_dir, img_dir = info_list
5355

5456
data = self.read_json(str(json_path))
55-
self.gen_classes_txt(save_dir, data.get('categories'))
57+
self.gen_classes_txt(save_dir, data.get("categories"))
5658

57-
id_img_dict = {v['id']: v for v in data.get('images')}
58-
all_annotaions = data.get('annotations')
59+
id_img_dict = {v["id"]: v for v in data.get("images")}
60+
all_annotaions = data.get("annotations")
5961
for one_anno in tqdm(all_annotaions):
60-
image_info = id_img_dict.get(one_anno['image_id'])
61-
img_name = image_info.get('file_name')
62-
img_height = image_info.get('height')
63-
img_width = image_info.get('width')
62+
image_info = id_img_dict.get(one_anno["image_id"])
63+
img_name = image_info.get("file_name")
64+
img_height = image_info.get("height")
65+
img_width = image_info.get("width")
6466

65-
seg_info = one_anno.get('segmentation')
67+
seg_info = one_anno.get("segmentation")
6668
if seg_info:
6769
bbox = self.get_bbox(seg_info)
6870
xywh = self.xyxy_to_xywh(bbox, img_width, img_height)
69-
category_id = int(one_anno.get('category_id')) - 1
70-
xywh_str = ' '.join([str(v) for v in xywh])
71-
label_str = f'{category_id} {xywh_str}'
71+
category_id = int(one_anno.get("category_id")) - 1
72+
xywh_str = " ".join([str(v) for v in xywh])
73+
label_str = f"{category_id} {xywh_str}"
7274

7375
# 写入标注的txt文件
74-
txt_full_path = save_dir / f'{Path(img_name).stem}.txt'
75-
self.write_txt(txt_full_path, label_str, mode='a')
76+
txt_full_path = save_dir / f"{Path(img_name).stem}.txt"
77+
self.write_txt(txt_full_path, label_str, mode="a")
7678

7779
# 复制图像到转换后目录
7880
img_full_path = img_dir / img_name
7981
shutil.copy2(img_full_path, save_dir)
8082

8183
@staticmethod
8284
def read_json(json_path):
83-
with open(json_path, 'r', encoding='utf-8') as f:
85+
with open(json_path, "r", encoding="utf-8") as f:
8486
data = json.load(f)
8587
return data
8688

8789
def gen_classes_txt(self, save_dir, categories_dict):
88-
class_info = [value['name'] for value in categories_dict]
89-
self.write_txt(save_dir / 'classes.txt', class_info)
90+
class_info = [value["name"] for value in categories_dict]
91+
self.write_txt(save_dir / "classes.txt", class_info)
9092

9193
def get_bbox(self, seg_info):
9294
seg_info = np.array(seg_info[0]).reshape(4, 2)
@@ -96,20 +98,20 @@ def get_bbox(self, seg_info):
9698
return bbox
9799

98100
@staticmethod
99-
def write_txt(save_path: str, content: list, mode='w'):
101+
def write_txt(save_path: str, content: list, mode="w"):
100102
if not isinstance(save_path, str):
101103
save_path = str(save_path)
102104

103105
if isinstance(content, str):
104106
content = [content]
105-
with open(save_path, mode, encoding='utf-8') as f:
107+
with open(save_path, mode, encoding="utf-8") as f:
106108
for value in content:
107-
f.write(f'{value}\n')
109+
f.write(f"{value}\n")
108110

109111
@staticmethod
110-
def xyxy_to_xywh(xyxy: list,
111-
img_width: int,
112-
img_height: int) -> tuple([float, float, float, float]):
112+
def xyxy_to_xywh(
113+
xyxy: list, img_width: int, img_height: int
114+
) -> tuple([float, float, float, float]):
113115
"""
114116
xyxy: (list), [x1, y1, x2, y2]
115117
"""
@@ -127,18 +129,21 @@ def xyxy_to_xywh(xyxy: list,
127129
def verify_exists(file_path):
128130
file_path = Path(file_path)
129131
if not file_path.exists():
130-
raise FileNotFoundError(f'The {file_path} is not exists!!!')
132+
raise FileNotFoundError(f"The {file_path} is not exists!!!")
131133

132134
@staticmethod
133135
def mkdir(dir_path):
134136
Path(dir_path).mkdir(parents=True, exist_ok=True)
135137

136138

137-
if __name__ == '__main__':
138-
parser = argparse.ArgumentParser('Datasets convert from COCO to labelImg')
139-
parser.add_argument('--data_dir', type=str,
140-
default='dataset/YOLOV5_COCO_format',
141-
help='Dataset root path')
139+
if __name__ == "__main__":
140+
parser = argparse.ArgumentParser("Datasets convert from COCO to labelImg")
141+
parser.add_argument(
142+
"--data_dir",
143+
type=str,
144+
default="dataset/YOLOV5_COCO_format",
145+
help="Dataset root path",
146+
)
142147
args = parser.parse_args()
143148

144149
converter = COCO2labelImg(args.data_dir)

coco_visual.py

Lines changed: 46 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,68 +10,80 @@
1010

1111

1212
def visualization_bbox(num_image, json_path, img_path):
13-
with open(json_path, 'r', encoding='utf-8') as annos:
13+
with open(json_path, "r", encoding="utf-8") as annos:
1414
annotation_json = json.load(annos)
15-
print('The annotation_json num_key is:', len(annotation_json))
16-
print('The annotation_json key is:', annotation_json.keys())
17-
print('The annotation_json num_images is:', len(annotation_json['images']))
15+
print("The annotation_json num_key is:", len(annotation_json))
16+
print("The annotation_json key is:", annotation_json.keys())
17+
print("The annotation_json num_images is:", len(annotation_json["images"]))
1818

19-
categories = annotation_json['categories']
20-
categories_dict = {c['id']: c['name'] for c in categories}
19+
categories = annotation_json["categories"]
20+
categories_dict = {c["id"]: c["name"] for c in categories}
2121
class_nums = len(categories_dict.keys())
22-
color = [(random.randint(0, 255), random.randint(0, 255),
23-
random.randint(0, 255)) for _ in range(class_nums)]
22+
color = [
23+
(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
24+
for _ in range(class_nums)
25+
]
2426

25-
image_name = annotation_json['images'][num_image - 1]['file_name']
26-
img_id = annotation_json['images'][num_image - 1]['id']
27+
image_name = annotation_json["images"][num_image - 1]["file_name"]
28+
img_id = annotation_json["images"][num_image - 1]["id"]
2729
image_path = os.path.join(img_path, str(image_name).zfill(5))
2830
image = cv2.imread(image_path, 1)
2931

30-
annotations = annotation_json['annotations']
32+
annotations = annotation_json["annotations"]
3133
num_bbox = 0
3234
for anno in annotations:
33-
if anno['image_id'] == img_id:
35+
if anno["image_id"] == img_id:
3436
num_bbox = num_bbox + 1
3537

36-
class_id = anno['category_id']
38+
class_id = anno["category_id"]
3739
class_name = categories_dict[class_id]
38-
class_color = color[class_id-1]
40+
class_color = color[class_id - 1]
3941

40-
x, y, w, h = list(map(int, anno['bbox']))
41-
cv2.rectangle(image, (int(x), int(y)),
42-
(int(x + w), int(y + h)),
43-
class_color, 2)
42+
x, y, w, h = list(map(int, anno["bbox"]))
43+
cv2.rectangle(
44+
image, (int(x), int(y)), (int(x + w), int(y + h)), class_color, 2
45+
)
4446

4547
font_size = 0.7
46-
txt_size = cv2.getTextSize(class_name, cv2.FONT_HERSHEY_SIMPLEX,
47-
font_size, 1)[0]
48-
cv2.rectangle(image, (x, y + 1),
49-
(x + txt_size[0] + 10, y - int(2 * txt_size[1])),
50-
class_color, -1)
51-
cv2.putText(image, class_name, (x + 5, y - 5),
52-
cv2.FONT_HERSHEY_SIMPLEX,
53-
font_size, (255, 255, 255), 1)
48+
txt_size = cv2.getTextSize(
49+
class_name, cv2.FONT_HERSHEY_SIMPLEX, font_size, 1
50+
)[0]
51+
cv2.rectangle(
52+
image,
53+
(x, y + 1),
54+
(x + txt_size[0] + 10, y - int(2 * txt_size[1])),
55+
class_color,
56+
-1,
57+
)
58+
cv2.putText(
59+
image,
60+
class_name,
61+
(x + 5, y - 5),
62+
cv2.FONT_HERSHEY_SIMPLEX,
63+
font_size,
64+
(255, 255, 255),
65+
1,
66+
)
5467

55-
print('The unm_bbox of the display image is:', num_bbox)
68+
print("The unm_bbox of the display image is:", num_bbox)
5669

5770
cur_os = platform.system()
58-
if cur_os == 'Windows':
71+
if cur_os == "Windows":
5972
cv2.namedWindow(image_name, 0)
6073
cv2.resizeWindow(image_name, 1000, 1000)
6174
cv2.imshow(image_name, image)
6275
cv2.waitKey(0)
6376
else:
64-
save_path = f'visul_{num_image}.jpg'
77+
save_path = f"visul_{num_image}.jpg"
6578
cv2.imwrite(save_path, image)
66-
print(f'The {save_path} has been saved the current director.')
79+
print(f"The {save_path} has been saved the current director.")
6780

6881

6982
if __name__ == "__main__":
7083
parser = argparse.ArgumentParser()
71-
parser.add_argument('--vis_num', type=int, default=1,
72-
help="visual which one")
73-
parser.add_argument('--json_path', type=str, required=True)
74-
parser.add_argument('--img_dir', type=str, required=True)
84+
parser.add_argument("--vis_num", type=int, default=1, help="visual which one")
85+
parser.add_argument("--json_path", type=str, required=True)
86+
parser.add_argument("--img_dir", type=str, required=True)
7587
args = parser.parse_args()
7688

7789
visualization_bbox(args.vis_num, args.json_path, args.img_dir)

0 commit comments

Comments
 (0)