forked from nka77/DAHiTra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_polygons.py
72 lines (61 loc) · 2.64 KB
/
generate_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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import json
import os
import argparse
from functools import partial
from multiprocessing.pool import Pool
from os import cpu_count
import cv2
from cv2 import fillPoly
from shapely import wkt
import numpy as np
from shapely.geometry import mapping
from tqdm import tqdm
def generate_localization_polygon(json_path, out_dir):
with open(json_path, "r") as f:
annotations = json.load(f)
h = annotations["metadata"]["height"]
w = annotations["metadata"]["width"]
mask_img = np.zeros((h, w), np.uint8)
out_filename = os.path.splitext(os.path.basename(json_path))[0] + "_target.png"
for feat in annotations['features']['xy']:
feat_shape = wkt.loads(feat['wkt'])
coords = list(mapping(feat_shape)['coordinates'][0])
fillPoly(mask_img, [np.array(coords, np.int32)], (255))
cv2.imwrite(os.path.join(out_dir, out_filename), mask_img)
def generate_damage_polygon(json_path, out_dir):
with open(json_path, "r") as f:
annotations = json.load(f)
h = annotations["metadata"]["height"]
w = annotations["metadata"]["width"]
mask_img = np.zeros((h, w), np.uint8)
damage_dict = {
"no-damage": 1,
"minor-damage": 2,
"major-damage": 3,
"destroyed": 4,
# "un-classified": 255
"un-classified": 1 # FIXME: go back to the unclassified
}
out_filename = os.path.splitext(os.path.basename(json_path))[0] + "_target.png"
for feat in annotations['features']['xy']:
feat_shape = wkt.loads(feat['wkt'])
coords = list(mapping(feat_shape)['coordinates'][0])
fillPoly(mask_img, [np.array(coords, np.int32)], damage_dict[feat['properties']['subtype']])
cv2.imwrite(os.path.join(out_dir, out_filename), mask_img)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input',
default="data/xBD_png/tier3",
help='Path to parent dataset directory "xBD"')
args = parser.parse_args()
out_dir = os.path.join(args.input, "targets")
in_dir = os.path.join(args.input, "labels")
pre_images = [os.path.join(in_dir, f) for f in os.listdir(in_dir) if '_pre_' in f]
post_images = [os.path.join(in_dir, f) for f in os.listdir(in_dir) if '_post_' in f]
pool = Pool(cpu_count())
with tqdm(total=len(pre_images)) as pbar:
for i, v in enumerate(pool.imap_unordered(partial(generate_localization_polygon, out_dir=out_dir), pre_images)):
pbar.update()
with tqdm(total=len(post_images)) as pbar:
for i, v in enumerate(pool.imap_unordered(partial(generate_damage_polygon, out_dir=out_dir), post_images)):
pbar.update()