-
Notifications
You must be signed in to change notification settings - Fork 0
/
masks_to_polygons.py
40 lines (32 loc) · 1.18 KB
/
masks_to_polygons.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import os
import cv2
input_dir = ''
output_dir = ''
for j in os.listdir(input_dir):
image_path = os.path.join(input_dir, j)
# load the binary mask and get its contours
mask = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
_, mask = cv2.threshold(mask, 1, 255, cv2.THRESH_BINARY)
H, W = mask.shape
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# convert the contours to polygons
polygons = []
for cnt in contours:
if cv2.contourArea(cnt) > 200:
polygon = []
for point in cnt:
x, y = point[0]
polygon.append(x / W)
polygon.append(y / H)
polygons.append(polygon)
# print the polygons
with open('{}.txt'.format(os.path.join(output_dir, j)[:-4]), 'w') as f:
for polygon in polygons:
for p_, p in enumerate(polygon):
if p_ == len(polygon) - 1:
f.write('{}\n'.format(p))
elif p_ == 0:
f.write('0 {} '.format(p))
else:
f.write('{} '.format(p))
f.close()