1+ import cv2 as cv
2+ import numpy as np
3+ import json
4+
5+ def to_categorical (y , num_classes = None ):
6+ y = np .array (y , dtype = 'int' ).ravel ()
7+ if not num_classes :
8+ num_classes = np .max (y ) + 1
9+ n = y .shape [0 ]
10+ categorical = np .zeros ((n , num_classes ))
11+ categorical [np .arange (n ), y ] = 1
12+ return categorical
13+
14+ img = cv .imread ("images_test/Abbey_Road_watershed_mask.png" )
15+ gray = cv .cvtColor (img , cv .COLOR_BGR2GRAY )
16+ config = json .load (open ("config.json" ))['labels' ]
17+
18+ shape = (gray .shape [0 ],gray .shape [1 ],1 )
19+ gray = gray .reshape (shape )
20+ images = to_categorical (gray ).reshape ((gray .shape [0 ],gray .shape [1 ],- 1 ))
21+
22+ out = open ('images_test/Abbey_Road.json' ,'w' )
23+ data = {}
24+ data ["version" ] = "3.6.16"
25+ data ["flags" ] = {}
26+ data ["shapes" ] = []
27+ data ["lineColor" ]= [0 ,255 ,0 ,128 ]
28+ data ["fillColor" ]= [255 ,0 ,0 ,128 ]
29+ data ["imagePath" ]= "Abbey_Road.jpg"
30+ data ["imageData" ]= None
31+ data ["imageHeight" ] = img .shape [0 ]
32+ data ["imageWidth" ] = img .shape [1 ]
33+
34+ for label in config :
35+ person = images [:,:,config [label ]['id' ]]
36+ person [person > 0 ] = 255
37+
38+ person = person .astype ('uint8' )
39+ im , contour , hierarchy = cv .findContours (person , cv .RETR_EXTERNAL , cv .CHAIN_APPROX_SIMPLE )
40+
41+ for i ,c in enumerate (contour ) :
42+ contour [i ] = cv .approxPolyDP (c ,1.5 ,True )
43+ d = {}
44+ d ['label' ] = label
45+ d ["line_color" ] = None
46+ d ["fill_color" ] = None
47+ if contour [i ].shape [0 ] < 3 :
48+ continue
49+ d ["points" ] = contour [i ].reshape (contour [i ].shape [0 ],contour [i ].shape [2 ]).tolist ()
50+ d ["shape_type" ] = "polygon"
51+ data ["shapes" ].append (d )
52+
53+ # color = config[label]['color']
54+ # cv.drawContours(img, contour, -1, color, 1)
55+
56+ # cv.imshow("person",img)
57+ # cv.waitKey(0)
58+
59+ json .dump (data ,out ,indent = 2 )
0 commit comments