akhaliq3 commited on
Commit
9c212e5
1 Parent(s): d43f090

spaces demo

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021-present NAVER Corp.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import cv2
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from utils import pred_lines, pred_squares
6
+ import gradio as gr
7
+ from urllib.request import urlretrieve
8
+
9
+
10
+ # Load MLSD 512 Large FP32 tflite
11
+ model_name = 'tflite_models/M-LSD_512_large_fp32.tflite'
12
+ interpreter = tf.lite.Interpreter(model_path=model_name)
13
+
14
+ interpreter.allocate_tensors()
15
+ input_details = interpreter.get_input_details()
16
+ output_details = interpreter.get_output_details()
17
+
18
+ def gradio_wrapper_for_LSD(img_input, score_thr, dist_thr):
19
+ lines = pred_lines(img_input, interpreter, input_details, output_details, input_shape=[512, 512], score_thr=score_thr, dist_thr=dist_thr)
20
+ img_output = img_input.copy()
21
+
22
+ # draw lines
23
+ for line in lines:
24
+ x_start, y_start, x_end, y_end = [int(val) for val in line]
25
+ cv2.line(img_output, (x_start, y_start), (x_end, y_end), [0,255,255], 2)
26
+
27
+ return img_output
28
+
29
+ urlretrieve("https://www.digsdigs.com/photos/2015/05/a-bold-minimalist-living-room-with-dark-stained-wood-geometric-touches-a-sectional-sofa-and-built-in-lights-for-a-futuristic-feel.jpg","example1.jpg")
30
+ urlretrieve("https://specials-images.forbesimg.com/imageserve/5dfe2e6925ab5d0007cefda5/960x0.jpg","example2.jpg")
31
+ urlretrieve("https://images.livspace-cdn.com/w:768/h:651/plain/https://jumanji.livspace-cdn.com/magazine/wp-content/uploads/2015/11/27170345/atr-1-a-e1577187047515.jpeg","example3.jpg")
32
+ sample_images = [["example1.jpg", 0.2, 10.0], ["example2.jpg", 0.2, 10.0], ["example3.jpg", 0.2, 10.0]]
33
+
34
+
35
+
36
+ iface = gr.Interface(gradio_wrapper_for_LSD,
37
+ ["image",
38
+ gr.inputs.Number(default=0.2, label='score_thr (0.0 ~ 1.0)'),
39
+ gr.inputs.Number(default=10.0, label='dist_thr (0.0 ~ 20.0)')
40
+ ],
41
+ "image",
42
+ title="Line segment detection with Mobile LSD (M-LSD)",
43
+ description="M-LSD is a light-weight and real-time deep line segment detector, which can run on GPU, CPU, and even on Mobile devices. Try it by uploading an image or clicking on an example. Read more at the links below",
44
+ article="<p style='text-align: center'><a href='https://arxiv.org/abs/2106.00186'>Towards Real-time and Light-weight Line Segment Detection</a> | <a href='https://github.com/navervision/mlsd'>Github Repo</a></p>",
45
+ examples=sample_images,
46
+ allow_screenshot=True)
47
+
48
+ iface.launch()
demo_MLSD.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ M-LSD
3
+ Copyright 2021-present NAVER Corp.
4
+ Apache License v2.0
5
+ '''
6
+ # for demo
7
+ import os
8
+ from flask import Flask, request, session, json, Response, render_template, abort, send_from_directory
9
+ import requests
10
+ from urllib.request import urlopen
11
+ from io import BytesIO
12
+ import uuid
13
+ import cv2
14
+ import time
15
+ import argparse
16
+
17
+ # for tflite
18
+ import numpy as np
19
+ from PIL import Image
20
+ import tensorflow as tf
21
+
22
+ # for square detector
23
+ from utils import pred_squares
24
+
25
+ os.environ['CUDA_VISIBLE_DEVICES'] = '' # CPU mode
26
+
27
+ # flask
28
+ app = Flask(__name__)
29
+ logger = app.logger
30
+ logger.info('init demo app')
31
+
32
+ # config
33
+ parser = argparse.ArgumentParser()
34
+
35
+ ## model parameters
36
+ parser.add_argument('--tflite_path', default='./tflite_models/M-LSD_512_large_fp16.tflite', type=str)
37
+ parser.add_argument('--input_size', default=512, type=int,
38
+ help='The size of input images.')
39
+
40
+ ## LSD parameter
41
+ parser.add_argument('--score_thr', default=0.10, type=float,
42
+ help='Discard center points when the score < score_thr.')
43
+
44
+ ## intersection point parameters
45
+ parser.add_argument('--outside_ratio', default=0.10, type=float,
46
+ help='''Discard an intersection point
47
+ when it is located outside a line segment farther than line_length * outside_ratio.''')
48
+ parser.add_argument('--inside_ratio', default=0.50, type=float,
49
+ help='''Discard an intersection point
50
+ when it is located inside a line segment farther than line_length * inside_ratio.''')
51
+
52
+ ## ranking boxes parameters
53
+ parser.add_argument('--w_overlap', default=0.0, type=float,
54
+ help='''When increasing w_overlap, the final box tends to overlap with
55
+ the detected line segments as much as possible.''')
56
+ parser.add_argument('--w_degree', default=1.14, type=float,
57
+ help='''When increasing w_degree, the final box tends to be
58
+ a parallel quadrilateral with reference to the angle of the box.''')
59
+ parser.add_argument('--w_length', default=0.03, type=float,
60
+ help='''When increasing w_length, the final box tends to be
61
+ a parallel quadrilateral with reference to the length of the box.''')
62
+ parser.add_argument('--w_area', default=1.84, type=float,
63
+ help='When increasing w_area, the final box tends to be the largest one out of candidates.')
64
+ parser.add_argument('--w_center', default=1.46, type=float,
65
+ help='When increasing w_center, the final box tends to be located in the center of input image.')
66
+
67
+ ## flask demo parameter
68
+ parser.add_argument('--port', default=5000, type=int,
69
+ help='flask demo will be running on http://0.0.0.0:port/')
70
+
71
+
72
+ class model_graph:
73
+ def __init__(self, args):
74
+ self.interpreter, self.input_details, self.output_details = self.load_tflite(args.tflite_path)
75
+ self.params = {'score': args.score_thr,'outside_ratio': args.outside_ratio,'inside_ratio': args.inside_ratio,
76
+ 'w_overlap': args.w_overlap,'w_degree': args.w_degree,'w_length': args.w_length,
77
+ 'w_area': args.w_area,'w_center': args.w_center}
78
+ self.args = args
79
+
80
+
81
+ def load_tflite(self, tflite_path):
82
+ interpreter = tf.lite.Interpreter(model_path=tflite_path)
83
+ interpreter.allocate_tensors()
84
+ input_details = interpreter.get_input_details()
85
+ output_details = interpreter.get_output_details()
86
+
87
+ return interpreter, input_details, output_details
88
+
89
+
90
+ def pred_tflite(self, image):
91
+ segments, squares, score_array, inter_points = pred_squares(image, self.interpreter, self.input_details, self.output_details, [self.args.input_size, self.args.input_size], params=self.params)
92
+
93
+ output = {}
94
+ output['segments'] = segments
95
+ output['squares'] = squares
96
+ output['scores'] = score_array
97
+ output['inter_points'] = inter_points
98
+
99
+ return output
100
+
101
+
102
+ def read_image(self, image_url):
103
+ response = requests.get(image_url, stream=True)
104
+ image = np.asarray(Image.open(BytesIO(response.content)).convert('RGB'))
105
+
106
+ max_len = 1024
107
+ h, w, _ = image.shape
108
+ org_shape = [h, w]
109
+ max_idx = np.argmax(org_shape)
110
+
111
+ max_val = org_shape[max_idx]
112
+ if max_val > max_len:
113
+ min_idx = (max_idx + 1) % 2
114
+ ratio = max_len / max_val
115
+ new_min = org_shape[min_idx] * ratio
116
+ new_shape = [0, 0]
117
+ new_shape[max_idx] = 1024
118
+ new_shape[min_idx] = new_min
119
+
120
+ image = cv2.resize(image, (int(new_shape[1]), int(new_shape[0])), interpolation=cv2.INTER_AREA)
121
+
122
+ return image
123
+
124
+
125
+ def init_resize_image(self, im, maximum_size=1024):
126
+ h, w, _ = im.shape
127
+ size = [h, w]
128
+ max_arg = np.argmax(size)
129
+ max_len = size[max_arg]
130
+ min_arg = max_arg - 1
131
+ min_len = size[min_arg]
132
+ if max_len < maximum_size:
133
+ return im
134
+ else:
135
+ ratio = maximum_size / max_len
136
+ max_len = max_len * ratio
137
+ min_len = min_len * ratio
138
+ size[max_arg] = int(max_len)
139
+ size[min_arg] = int(min_len)
140
+
141
+ im = cv2.resize(im, (size[1], size[0]), interpolation = cv2.INTER_AREA)
142
+
143
+ return im
144
+
145
+
146
+ def decode_image(self, session_id, rawimg):
147
+ dirpath = os.path.join('static/results', session_id)
148
+
149
+ if not os.path.exists(dirpath):
150
+ os.makedirs(dirpath)
151
+ save_path = os.path.join(dirpath, 'input.png')
152
+ input_image_url = os.path.join(dirpath, 'input.png')
153
+
154
+ img = cv2.imdecode(np.frombuffer(rawimg, dtype='uint8'), 1)[:,:,::-1]
155
+ img = self.init_resize_image(img)
156
+ cv2.imwrite(save_path, img[:,:,::-1])
157
+
158
+ return img, input_image_url
159
+
160
+
161
+ def draw_output(self, image, output, save_path='test.png'):
162
+ color_dict = {'red': [255, 0, 0],
163
+ 'green': [0, 255, 0],
164
+ 'blue': [0, 0, 255],
165
+ 'cyan': [0, 255, 255],
166
+ 'black': [0, 0, 0],
167
+ 'yellow': [255, 255, 0],
168
+ 'dark_yellow': [200, 200, 0]}
169
+
170
+ line_image = image.copy()
171
+ square_image = image.copy()
172
+ square_candidate_image = image.copy()
173
+
174
+ line_thick = 5
175
+
176
+ # output > line array
177
+ for line in output['segments']:
178
+ x_start, y_start, x_end, y_end = [int(val) for val in line]
179
+ cv2.line(line_image, (x_start, y_start), (x_end, y_end), color_dict['red'], line_thick)
180
+
181
+ inter_image = line_image.copy()
182
+
183
+ for pt in output['inter_points']:
184
+ x, y = [int(val) for val in pt]
185
+ cv2.circle(inter_image, (x, y), 10, color_dict['blue'], -1)
186
+
187
+ for square in output['squares']:
188
+ cv2.polylines(square_candidate_image, [square.reshape([-1, 1, 2])], True, color_dict['dark_yellow'], line_thick)
189
+
190
+ for square in output['squares'][0:1]:
191
+ cv2.polylines(square_image, [square.reshape([-1, 1, 2])], True, color_dict['yellow'], line_thick)
192
+ for pt in square:
193
+ cv2.circle(square_image, (int(pt[0]), int(pt[1])), 10, color_dict['cyan'], -1)
194
+
195
+ '''
196
+ square image | square candidates image
197
+ inter image | line image
198
+ '''
199
+ output_image = self.init_resize_image(square_image, 512)
200
+ output_image = np.concatenate([output_image, self.init_resize_image(square_candidate_image, 512)], axis=1)
201
+ output_image_tmp = np.concatenate([self.init_resize_image(inter_image, 512), self.init_resize_image(line_image, 512)], axis=1)
202
+ output_image = np.concatenate([output_image, output_image_tmp], axis=0)
203
+
204
+ cv2.imwrite(save_path, output_image[:,:,::-1])
205
+
206
+ return output_image
207
+
208
+
209
+ def save_output(self, session_id, input_image_url, image, output):
210
+ dirpath = os.path.join('static/results', session_id)
211
+
212
+ if not os.path.exists(dirpath):
213
+ os.makedirs(dirpath)
214
+
215
+ save_path = os.path.join(dirpath, 'output.png')
216
+ self.draw_output(image, output, save_path=save_path)
217
+
218
+ output_image_url = os.path.join(dirpath, 'output.png')
219
+
220
+ rst = {}
221
+ rst['input_image_url'] = input_image_url
222
+ rst['session_id'] = session_id
223
+ rst['output_image_url'] = output_image_url
224
+
225
+ with open(os.path.join(dirpath, 'results.json'), 'w') as f:
226
+ json.dump(rst, f)
227
+
228
+
229
+ def init_worker(args):
230
+ global model
231
+
232
+ model = model_graph(args)
233
+
234
+
235
+ @app.route('/')
236
+ def index():
237
+ return render_template('index_scan.html', session_id='dummy_session_id')
238
+
239
+
240
+ @app.route('/', methods=['POST'])
241
+ def index_post():
242
+ request_start = time.time()
243
+ configs = request.form
244
+
245
+ session_id = str(uuid.uuid1())
246
+
247
+ image_url = configs['image_url'] # image_url
248
+
249
+ if len(image_url) == 0:
250
+ bio = BytesIO()
251
+ request.files['image'].save(bio)
252
+ rawimg = bio.getvalue()
253
+ image, image_url = model.decode_image(session_id, rawimg)
254
+ else:
255
+ image = model.read_image(image_url)
256
+
257
+ output = model.pred_tflite(image)
258
+
259
+ model.save_output(session_id, image_url, image, output)
260
+
261
+ return render_template('index_scan.html', session_id=session_id)
262
+
263
+
264
+ @app.route('/favicon.ico')
265
+ def favicon():
266
+ return send_from_directory(os.path.join(app.root_path, 'static'),
267
+ 'favicon.ico', mimetype='image/vnd.microsoft.icon')
268
+
269
+
270
+ if __name__ == '__main__':
271
+ args = parser.parse_args()
272
+
273
+ init_worker(args)
274
+
275
+ app.run(host='0.0.0.0', port=args.port)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
1
+ numpy
2
+ opencv-python
3
+ pillow
4
+ tensorflow-gpu
5
+ Flask
6
+ gradio
static/css/app.css ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #app {
2
+ padding: 20px;
3
+ }
4
+
5
+ #result .item {
6
+ padding-bottom: 20px;
7
+ }
8
+
9
+ .form-content-container {
10
+ padding-left: 20px;
11
+ }
static/favicon.ico ADDED
templates/index_scan.html ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype! html>
2
+ <!--
3
+ M-LSD
4
+ Copyright 2021-present NAVER Corp.
5
+ Apache License v2.0
6
+ -->
7
+ <html>
8
+ <head>
9
+ <title>MLSD demo</title>
10
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
11
+ <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" type="text/css">
12
+ <link rel="stylesheet" href="/static/css/app.css" type="text/css">
13
+
14
+ <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
15
+ <script src="https://cdn.staticfile.org/tether/1.4.0/js/tether.min.js"></script>
16
+ <script src="https://cdn.staticfile.org/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
17
+ <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
18
+ <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
19
+ </head>
20
+ <style>
21
+ .container {
22
+ width: 1000em;
23
+ overflow-x: auto;
24
+ white-space: nowrap;
25
+ }
26
+ .image {
27
+ position: relative;
28
+ }
29
+
30
+ h2 {
31
+ position: absolute;
32
+ top: 200px;
33
+ left: 10px;
34
+ width: 100px;
35
+ color: white;
36
+ background: rgb(0, 0, 0);
37
+ background: rgba(0, 0, 0, 0.7);
38
+ }
39
+ </style>
40
+ <body>
41
+ <div id="app">
42
+ <div>
43
+ <form id="upload-form" method="post" enctype="multipart/form-data">
44
+ <h5>MLSD demo</h5>
45
+ <div class="form-content-container">
46
+ image_url: <input id="upload_url" type="text" name="image_url" /><br>
47
+ image_data: <input id="upload_image" type="file" name="image" /><br>
48
+ <input id="upload_button" type="submit" value="Submit" />
49
+ </div>
50
+ </form>
51
+ </div>
52
+ <hr>
53
+ <div id="result" v-if="show">
54
+ <div class="item">
55
+ <div><h5>Output_image</h5>
56
+ <ul>
57
+ <img id="output_image" :src="output_image_url" style="float:left;margin:10px;">
58
+ </ul>
59
+ <br style="clear:both">
60
+
61
+ <div><h5>Input_image</h5></div>
62
+ <ul>
63
+ <img id="input_image" :src="input_image_url" height="224" style="float:left;margin:10px;">
64
+ </ul>
65
+ <br style="clear:both" />
66
+ </div>
67
+ </div>
68
+ <hr>
69
+ <footer>
70
+ Github url: <a href="https://github.com/navervision/mlsd">https://github.com/navervision/mlsd</a>
71
+ </footer>
72
+ </div>
73
+
74
+ <script>
75
+ $(function() {
76
+ function getQueryStrings() {
77
+ var vars = [], hash, hashes;
78
+ if (window.location.href.indexOf('#') === -1) {
79
+ hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
80
+ } else {
81
+ hashes = window.location.href.slice(window.location.href.indexOf('?') + 1, window.location.href.indexOf('#')).split('&');
82
+ }
83
+ for(var i = 0; i < hashes.length; i++) {
84
+ hash = hashes[i].split('=');
85
+ vars.push(hash[0]);
86
+ vars[hash[0]] = hash[1];
87
+ }
88
+ return vars;
89
+ }
90
+
91
+ var session_id = '{{session_id}}';
92
+
93
+ var app = new Vue({
94
+ el: '#app',
95
+ data: {
96
+ session_id: session_id,
97
+ show: false,
98
+ },
99
+ });
100
+
101
+ var render = function(session_id) {
102
+ app.session_id = session_id;
103
+ app.server_info = ['loading'];
104
+ $.get('/static/results/' + session_id + '/results.json', function(data) {
105
+ if (typeof data == 'string') {
106
+ data = JSON.parse(data);
107
+ }
108
+ app.input_image_url = data.input_image_url;
109
+ app.session_id = data.session_id;
110
+ app.output_image_url = data.output_image_url;
111
+ app.show = true
112
+ });
113
+ }
114
+
115
+ if (session_id != 'dummy_session_id') {
116
+ window.history.pushState({},"", '/?r=' + session_id);
117
+ render(session_id);
118
+ } else {
119
+ var queryStrings = getQueryStrings();
120
+ var rid = queryStrings['r'];
121
+ if (rid) {
122
+ render(rid);
123
+ }
124
+ }
125
+ })
126
+ </script>
127
+ </body>
128
+ </html>
tflite_models/M-LSD_320_large_fp16.tflite ADDED
Binary file (3.12 MB). View file
tflite_models/M-LSD_320_large_fp32.tflite ADDED
Binary file (6.14 MB). View file
tflite_models/M-LSD_320_tiny_fp16.tflite ADDED
Binary file (1.28 MB). View file
tflite_models/M-LSD_320_tiny_fp32.tflite ADDED
Binary file (2.49 MB). View file
tflite_models/M-LSD_512_large_fp16.tflite ADDED
Binary file (3.12 MB). View file
tflite_models/M-LSD_512_large_fp32.tflite ADDED
Binary file (6.14 MB). View file
tflite_models/M-LSD_512_tiny_fp16.tflite ADDED
Binary file (1.28 MB). View file
tflite_models/M-LSD_512_tiny_fp32.tflite ADDED
Binary file (2.49 MB). View file
utils.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ M-LSD
3
+ Copyright 2021-present NAVER Corp.
4
+ Apache License v2.0
5
+ '''
6
+ import os
7
+ import numpy as np
8
+ import cv2
9
+ import tensorflow as tf
10
+
11
+
12
+ def pred_lines(image, interpreter, input_details, output_details, input_shape=[512, 512], score_thr=0.10, dist_thr=20.0):
13
+ h, w, _ = image.shape
14
+ h_ratio, w_ratio = [h / input_shape[0], w / input_shape[1]]
15
+
16
+ resized_image = np.concatenate([cv2.resize(image, (input_shape[0], input_shape[1]), interpolation=cv2.INTER_AREA), np.ones([input_shape[0], input_shape[1], 1])], axis=-1)
17
+ batch_image = np.expand_dims(resized_image, axis=0).astype('float32')
18
+ interpreter.set_tensor(input_details[0]['index'], batch_image)
19
+ interpreter.invoke()
20
+
21
+ pts = interpreter.get_tensor(output_details[0]['index'])[0]
22
+ pts_score = interpreter.get_tensor(output_details[1]['index'])[0]
23
+ vmap = interpreter.get_tensor(output_details[2]['index'])[0]
24
+
25
+ start = vmap[:,:,:2]
26
+ end = vmap[:,:,2:]
27
+ dist_map = np.sqrt(np.sum((start - end) ** 2, axis=-1))
28
+
29
+ segments_list = []
30
+ for center, score in zip(pts, pts_score):
31
+ y, x = center
32
+ distance = dist_map[y, x]
33
+ if score > score_thr and distance > dist_thr:
34
+ disp_x_start, disp_y_start, disp_x_end, disp_y_end = vmap[y, x, :]
35
+ x_start = x + disp_x_start
36
+ y_start = y + disp_y_start
37
+ x_end = x + disp_x_end
38
+ y_end = y + disp_y_end
39
+ segments_list.append([x_start, y_start, x_end, y_end])
40
+
41
+ lines = 2 * np.array(segments_list) # 256 > 512
42
+ lines[:,0] = lines[:,0] * w_ratio
43
+ lines[:,1] = lines[:,1] * h_ratio
44
+ lines[:,2] = lines[:,2] * w_ratio
45
+ lines[:,3] = lines[:,3] * h_ratio
46
+
47
+ return lines
48
+
49
+
50
+ def pred_squares(image,
51
+ interpreter,
52
+ input_details,
53
+ output_details,
54
+ input_shape=[512, 512],
55
+ params={'score': 0.06,
56
+ 'outside_ratio': 0.28,
57
+ 'inside_ratio': 0.45,
58
+ 'w_overlap': 0.0,
59
+ 'w_degree': 1.95,
60
+ 'w_length': 0.0,
61
+ 'w_area': 1.86,
62
+ 'w_center': 0.14}):
63
+ h, w, _ = image.shape
64
+ original_shape = [h, w]
65
+
66
+ resized_image = np.concatenate([cv2.resize(image, (input_shape[0], input_shape[1]), interpolation=cv2.INTER_AREA), np.ones([input_shape[0], input_shape[1], 1])], axis=-1)
67
+ batch_image = np.expand_dims(resized_image, axis=0).astype('float32')
68
+ interpreter.set_tensor(input_details[0]['index'], batch_image)
69
+ interpreter.invoke()
70
+
71
+ pts = interpreter.get_tensor(output_details[0]['index'])[0]
72
+ pts_score = interpreter.get_tensor(output_details[1]['index'])[0]
73
+ vmap = interpreter.get_tensor(output_details[2]['index'])[0]
74
+
75
+ start = vmap[:,:,:2] # (x, y)
76
+ end = vmap[:,:,2:] # (x, y)
77
+ dist_map = np.sqrt(np.sum((start - end) ** 2, axis=-1))
78
+
79
+ junc_list = []
80
+ segments_list = []
81
+ for junc, score in zip(pts, pts_score):
82
+ y, x = junc
83
+ distance = dist_map[y, x]
84
+ if score > params['score'] and distance > 20.0:
85
+ junc_list.append([x, y])
86
+ disp_x_start, disp_y_start, disp_x_end, disp_y_end = vmap[y, x, :]
87
+ d_arrow = 1.0
88
+ x_start = x + d_arrow * disp_x_start
89
+ y_start = y + d_arrow * disp_y_start
90
+ x_end = x + d_arrow * disp_x_end
91
+ y_end = y + d_arrow * disp_y_end
92
+ segments_list.append([x_start, y_start, x_end, y_end])
93
+
94
+ segments = np.array(segments_list)
95
+
96
+ ####### post processing for squares
97
+ # 1. get unique lines
98
+ point = np.array([[0, 0]])
99
+ point = point[0]
100
+ start = segments[:,:2]
101
+ end = segments[:,2:]
102
+ diff = start - end
103
+ a = diff[:, 1]
104
+ b = -diff[:, 0]
105
+ c = a * start[:,0] + b * start[:,1]
106
+
107
+ d = np.abs(a * point[0] + b * point[1] - c) / np.sqrt(a ** 2 + b ** 2 + 1e-10)
108
+ theta = np.arctan2(diff[:,0], diff[:,1]) * 180 / np.pi
109
+ theta[theta < 0.0] += 180
110
+ hough = np.concatenate([d[:,None], theta[:,None]], axis=-1)
111
+
112
+ d_quant = 1
113
+ theta_quant = 2
114
+ hough[:,0] //= d_quant
115
+ hough[:,1] //= theta_quant
116
+ _, indices, counts = np.unique(hough, axis=0, return_index=True, return_counts=True)
117
+
118
+ acc_map = np.zeros([512 // d_quant + 1, 360 // theta_quant + 1], dtype='float32')
119
+ idx_map = np.zeros([512 // d_quant + 1, 360 // theta_quant + 1], dtype='int32') - 1
120
+ yx_indices = hough[indices,:].astype('int32')
121
+ acc_map[yx_indices[:,0], yx_indices[:,1]] = counts
122
+ idx_map[yx_indices[:,0], yx_indices[:,1]] = indices
123
+
124
+ acc_map_np = acc_map
125
+ acc_map = acc_map[None,:,:,None]
126
+
127
+ ### fast suppression using tensorflow op
128
+ acc_map = tf.constant(acc_map, dtype=tf.float32)
129
+ max_acc_map = tf.keras.layers.MaxPool2D(pool_size=(5,5), strides=1, padding='same')(acc_map)
130
+ acc_map = acc_map * tf.cast(tf.math.equal(acc_map, max_acc_map), tf.float32)
131
+ flatten_acc_map = tf.reshape(acc_map, [1, -1])
132
+ topk_values, topk_indices = tf.math.top_k(flatten_acc_map, k=len(pts))
133
+ _, h, w, _ = acc_map.shape
134
+ y = tf.expand_dims(topk_indices // w, axis=-1)
135
+ x = tf.expand_dims(topk_indices % w, axis=-1)
136
+ yx = tf.concat([y, x], axis=-1)
137
+ ###
138
+
139
+ yx = yx[0].numpy()
140
+ indices = idx_map[yx[:,0], yx[:,1]]
141
+ topk_values = topk_values.numpy()[0]
142
+ basis = 5 // 2
143
+
144
+ merged_segments = []
145
+ for yx_pt, max_indice, value in zip(yx, indices, topk_values):
146
+ y, x = yx_pt
147
+ if max_indice == -1 or value == 0:
148
+ continue
149
+ segment_list = []
150
+ for y_offset in range(-basis, basis+1):
151
+ for x_offset in range(-basis, basis+1):
152
+ indice = idx_map[y+y_offset,x+x_offset]
153
+ cnt = int(acc_map_np[y+y_offset,x+x_offset])
154
+ if indice != -1:
155
+ segment_list.append(segments[indice])
156
+ if cnt > 1:
157
+ check_cnt = 1
158
+ current_hough = hough[indice]
159
+ for new_indice, new_hough in enumerate(hough):
160
+ if (current_hough == new_hough).all() and indice != new_indice:
161
+ segment_list.append(segments[new_indice])
162
+ check_cnt += 1
163
+ if check_cnt == cnt:
164
+ break
165
+ group_segments = np.array(segment_list).reshape([-1, 2])
166
+ sorted_group_segments = np.sort(group_segments, axis=0)
167
+ x_min, y_min = sorted_group_segments[0,:]
168
+ x_max, y_max = sorted_group_segments[-1,:]
169
+
170
+ deg = theta[max_indice]
171
+ if deg >= 90:
172
+ merged_segments.append([x_min, y_max, x_max, y_min])
173
+ else:
174
+ merged_segments.append([x_min, y_min, x_max, y_max])
175
+
176
+ # 2. get intersections
177
+ new_segments = np.array(merged_segments) # (x1, y1, x2, y2)
178
+ start = new_segments[:,:2] # (x1, y1)
179
+ end = new_segments[:,2:] # (x2, y2)
180
+ new_centers = (start + end) / 2.0
181
+ diff = start - end
182
+ dist_segments = np.sqrt(np.sum(diff ** 2, axis=-1))
183
+
184
+ # ax + by = c
185
+ a = diff[:,1]
186
+ b = -diff[:,0]
187
+ c = a * start[:,0] + b * start[:,1]
188
+ pre_det = a[:,None] * b[None,:]
189
+ det = pre_det - np.transpose(pre_det)
190
+
191
+ pre_inter_y = a[:,None] * c[None,:]
192
+ inter_y = (pre_inter_y - np.transpose(pre_inter_y)) / (det + 1e-10)
193
+ pre_inter_x = c[:,None] * b[None,:]
194
+ inter_x = (pre_inter_x - np.transpose(pre_inter_x)) / (det + 1e-10)
195
+ inter_pts = np.concatenate([inter_x[:,:,None], inter_y[:,:,None]], axis=-1).astype('int32')
196
+
197
+ # 3. get corner information
198
+ # 3.1 get distance
199
+ '''
200
+ dist_segments:
201
+ | dist(0), dist(1), dist(2), ...|
202
+ dist_inter_to_segment1:
203
+ | dist(inter,0), dist(inter,0), dist(inter,0), ... |
204
+ | dist(inter,1), dist(inter,1), dist(inter,1), ... |
205
+ ...
206
+ dist_inter_to_semgnet2:
207
+ | dist(inter,0), dist(inter,1), dist(inter,2), ... |
208
+ | dist(inter,0), dist(inter,1), dist(inter,2), ... |
209
+ ...
210
+ '''
211
+
212
+ dist_inter_to_segment1_start = np.sqrt(np.sum(((inter_pts - start[:,None,:]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
213
+ dist_inter_to_segment1_end = np.sqrt(np.sum(((inter_pts - end[:,None,:]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
214
+ dist_inter_to_segment2_start = np.sqrt(np.sum(((inter_pts - start[None,:,:]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
215
+ dist_inter_to_segment2_end = np.sqrt(np.sum(((inter_pts - end[None,:,:]) ** 2), axis=-1, keepdims=True)) # [n_batch, n_batch, 1]
216
+
217
+ # sort ascending
218
+ dist_inter_to_segment1 = np.sort(np.concatenate([dist_inter_to_segment1_start, dist_inter_to_segment1_end], axis=-1), axis=-1) # [n_batch, n_batch, 2]
219
+ dist_inter_to_segment2 = np.sort(np.concatenate([dist_inter_to_segment2_start, dist_inter_to_segment2_end], axis=-1), axis=-1) # [n_batch, n_batch, 2]
220
+
221
+ # 3.2 get degree
222
+ inter_to_start = new_centers[:,None,:] - inter_pts
223
+ deg_inter_to_start = np.arctan2(inter_to_start[:,:,1], inter_to_start[:,:,0]) * 180 / np.pi
224
+ deg_inter_to_start[deg_inter_to_start < 0.0] += 360
225
+ inter_to_end = new_centers[None,:,:] - inter_pts
226
+ deg_inter_to_end = np.arctan2(inter_to_end[:,:,1], inter_to_end[:,:,0]) * 180 / np.pi
227
+ deg_inter_to_end[deg_inter_to_end < 0.0] += 360
228
+
229
+ '''
230
+ 0 -- 1
231
+ | |
232
+ 3 -- 2
233
+ '''
234
+ # rename variables
235
+ deg1_map, deg2_map = deg_inter_to_start, deg_inter_to_end
236
+ # sort deg ascending
237
+ deg_sort = np.sort(np.concatenate([deg1_map[:,:,None], deg2_map[:,:,None]], axis=-1), axis=-1)
238
+
239
+ deg_diff_map = np.abs(deg1_map - deg2_map)
240
+ # we only consider the smallest degree of intersect
241
+ deg_diff_map[deg_diff_map > 180] = 360 - deg_diff_map[deg_diff_map > 180]
242
+
243
+ # define available degree range
244
+ deg_range = [60, 120]
245
+
246
+ corner_dict = {corner_info: [] for corner_info in range(4)}
247
+ inter_points = []
248
+ for i in range(inter_pts.shape[0]):
249
+ for j in range(i + 1, inter_pts.shape[1]):
250
+ # i, j > line index, always i < j
251
+ x, y = inter_pts[i, j, :]
252
+ deg1, deg2 = deg_sort[i, j, :]
253
+ deg_diff = deg_diff_map[i, j]
254
+
255
+ check_degree = deg_diff > deg_range[0] and deg_diff < deg_range[1]
256
+
257
+ outside_ratio = params['outside_ratio'] # over ratio >>> drop it!
258
+ inside_ratio = params['inside_ratio'] # over ratio >>> drop it!
259
+ check_distance = ((dist_inter_to_segment1[i,j,1] >= dist_segments[i] and \
260
+ dist_inter_to_segment1[i,j,0] <= dist_segments[i] * outside_ratio) or \
261
+ (dist_inter_to_segment1[i,j,1] <= dist_segments[i] and \
262
+ dist_inter_to_segment1[i,j,0] <= dist_segments[i] * inside_ratio)) and \
263
+ ((dist_inter_to_segment2[i,j,1] >= dist_segments[j] and \
264
+ dist_inter_to_segment2[i,j,0] <= dist_segments[j] * outside_ratio) or \
265
+ (dist_inter_to_segment2[i,j,1] <= dist_segments[j] and \
266
+ dist_inter_to_segment2[i,j,0] <= dist_segments[j] * inside_ratio))
267
+
268
+ if check_degree and check_distance:
269
+ corner_info = None
270
+
271
+ if (deg1 >= 0 and deg1 <= 45 and deg2 >=45 and deg2 <= 120) or \
272
+ (deg2 >= 315 and deg1 >= 45 and deg1 <= 120):
273
+ corner_info, color_info = 0, 'blue'
274
+ elif (deg1 >= 45 and deg1 <= 125 and deg2 >= 125 and deg2 <= 225):
275
+ corner_info, color_info = 1, 'green'
276
+ elif (deg1 >= 125 and deg1 <= 225 and deg2 >= 225 and deg2 <= 315):
277
+ corner_info, color_info = 2, 'black'
278
+ elif (deg1 >= 0 and deg1 <= 45 and deg2 >= 225 and deg2 <= 315) or \
279
+ (deg2 >= 315 and deg1 >= 225 and deg1 <= 315):
280
+ corner_info, color_info = 3, 'cyan'
281
+ else:
282
+ corner_info, color_info = 4, 'red' # we don't use it
283
+ continue
284
+
285
+ corner_dict[corner_info].append([x, y, i, j])
286
+ inter_points.append([x, y])
287
+
288
+ square_list = []
289
+ connect_list = []
290
+ segments_list = []
291
+ for corner0 in corner_dict[0]:
292
+ for corner1 in corner_dict[1]:
293
+ connect01 = False
294
+ for corner0_line in corner0[2:]:
295
+ if corner0_line in corner1[2:]:
296
+ connect01 = True
297
+ break
298
+ if connect01:
299
+ for corner2 in corner_dict[2]:
300
+ connect12 = False
301
+ for corner1_line in corner1[2:]:
302
+ if corner1_line in corner2[2:]:
303
+ connect12 = True
304
+ break
305
+ if connect12:
306
+ for corner3 in corner_dict[3]:
307
+ connect23 = False
308
+ for corner2_line in corner2[2:]:
309
+ if corner2_line in corner3[2:]:
310
+ connect23 = True
311
+ break
312
+ if connect23:
313
+ for corner3_line in corner3[2:]:
314
+ if corner3_line in corner0[2:]:
315
+ # SQUARE!!!
316
+ '''
317
+ 0 -- 1
318
+ | |
319
+ 3 -- 2
320
+ square_list:
321
+ order: 0 > 1 > 2 > 3
322
+ | x0, y0, x1, y1, x2, y2, x3, y3 |
323
+ | x0, y0, x1, y1, x2, y2, x3, y3 |
324
+ ...
325
+ connect_list:
326
+ order: 01 > 12 > 23 > 30
327
+ | line_idx01, line_idx12, line_idx23, line_idx30 |
328
+ | line_idx01, line_idx12, line_idx23, line_idx30 |
329
+ ...
330
+ segments_list:
331
+ order: 0 > 1 > 2 > 3
332
+ | line_idx0_i, line_idx0_j, line_idx1_i, line_idx1_j, line_idx2_i, line_idx2_j, line_idx3_i, line_idx3_j |
333
+ | line_idx0_i, line_idx0_j, line_idx1_i, line_idx1_j, line_idx2_i, line_idx2_j, line_idx3_i, line_idx3_j |
334
+ ...
335
+ '''
336
+ square_list.append(corner0[:2] + corner1[:2] + corner2[:2] + corner3[:2])
337
+ connect_list.append([corner0_line, corner1_line, corner2_line, corner3_line])
338
+ segments_list.append(corner0[2:] + corner1[2:] + corner2[2:] + corner3[2:])
339
+
340
+ def check_outside_inside(segments_info, connect_idx):
341
+ # return 'outside or inside', min distance, cover_param, peri_param
342
+ if connect_idx == segments_info[0]:
343
+ check_dist_mat = dist_inter_to_segment1
344
+ else:
345
+ check_dist_mat = dist_inter_to_segment2
346
+
347
+ i, j = segments_info
348
+ min_dist, max_dist = check_dist_mat[i, j, :]
349
+ connect_dist = dist_segments[connect_idx]
350
+ if max_dist > connect_dist:
351
+ return 'outside', min_dist, 0, 1
352
+ else:
353
+ return 'inside', min_dist, -1, -1
354
+
355
+
356
+ top_square = None
357
+
358
+ try:
359
+ map_size = input_shape[0] / 2
360
+ squares = np.array(square_list).reshape([-1,4,2])
361
+ score_array = []
362
+ connect_array = np.array(connect_list)
363
+ segments_array = np.array(segments_list).reshape([-1,4,2])
364
+
365
+ # get degree of corners:
366
+ squares_rollup = np.roll(squares, 1, axis=1)
367
+ squares_rolldown = np.roll(squares, -1, axis=1)
368
+ vec1 = squares_rollup - squares
369
+ normalized_vec1 = vec1 / (np.linalg.norm(vec1, axis=-1, keepdims=True) + 1e-10)
370
+ vec2 = squares_rolldown - squares
371
+ normalized_vec2 = vec2 / (np.linalg.norm(vec2, axis=-1, keepdims=True) + 1e-10)
372
+ inner_products = np.sum(normalized_vec1 * normalized_vec2, axis=-1) # [n_squares, 4]
373
+ squares_degree = np.arccos(inner_products) * 180 / np.pi # [n_squares, 4]
374
+
375
+ # get square score
376
+ overlap_scores = []
377
+ degree_scores = []
378
+ length_scores = []
379
+
380
+ for connects, segments, square, degree in zip(connect_array, segments_array, squares, squares_degree):
381
+ '''
382
+ 0 -- 1
383
+ | |
384
+ 3 -- 2
385
+
386
+ # segments: [4, 2]
387
+ # connects: [4]
388
+ '''
389
+
390
+ ###################################### OVERLAP SCORES
391
+ cover = 0
392
+ perimeter = 0
393
+ # check 0 > 1 > 2 > 3
394
+ square_length = []
395
+
396
+ for start_idx in range(4):
397
+ end_idx = (start_idx + 1) % 4
398
+
399
+ connect_idx = connects[start_idx] # segment idx of segment01
400
+ start_segments = segments[start_idx]
401
+ end_segments = segments[end_idx]
402
+
403
+ start_point = square[start_idx]
404
+ end_point = square[end_idx]
405
+
406
+ # check whether outside or inside
407
+ start_position, start_min, start_cover_param, start_peri_param = check_outside_inside(start_segments, connect_idx)
408
+ end_position, end_min, end_cover_param, end_peri_param = check_outside_inside(end_segments, connect_idx)
409
+
410
+ cover += dist_segments[connect_idx] + start_cover_param * start_min + end_cover_param * end_min
411
+ perimeter += dist_segments[connect_idx] + start_peri_param * start_min + end_peri_param * end_min
412
+
413
+ square_length.append(dist_segments[connect_idx] + start_peri_param * start_min + end_peri_param * end_min)
414
+
415
+ overlap_scores.append(cover / perimeter)
416
+ ######################################
417
+ ###################################### DEGREE SCORES
418
+ '''
419
+ deg0 vs deg2
420
+ deg1 vs deg3
421
+ '''
422
+ deg0, deg1, deg2, deg3 = degree
423
+ deg_ratio1 = deg0 / deg2
424
+ if deg_ratio1 > 1.0:
425
+ deg_ratio1 = 1 / deg_ratio1
426
+ deg_ratio2 = deg1 / deg3
427
+ if deg_ratio2 > 1.0:
428
+ deg_ratio2 = 1 / deg_ratio2
429
+ degree_scores.append((deg_ratio1 + deg_ratio2) / 2)
430
+ ######################################
431
+ ###################################### LENGTH SCORES
432
+ '''
433
+ len0 vs len2
434
+ len1 vs len3
435
+ '''
436
+ len0, len1, len2, len3 = square_length
437
+ len_ratio1 = len0 / len2 if len2 > len0 else len2 / len0
438
+ len_ratio2 = len1 / len3 if len3 > len1 else len3 / len1
439
+ length_scores.append((len_ratio1 + len_ratio2) / 2)
440
+
441
+ ######################################
442
+
443
+ overlap_scores = np.array(overlap_scores)
444
+ overlap_scores /= np.max(overlap_scores)
445
+
446
+ degree_scores = np.array(degree_scores)
447
+ #degree_scores /= np.max(degree_scores)
448
+
449
+ length_scores = np.array(length_scores)
450
+
451
+ ###################################### AREA SCORES
452
+ area_scores = np.reshape(squares, [-1, 4, 2])
453
+ area_x = area_scores[:,:,0]
454
+ area_y = area_scores[:,:,1]
455
+ correction = area_x[:,-1] * area_y[:,0] - area_y[:,-1] * area_x[:,0]
456
+ area_scores = np.sum(area_x[:,:-1] * area_y[:,1:], axis=-1) - np.sum(area_y[:,:-1] * area_x[:,1:], axis=-1)
457
+ area_scores = 0.5 * np.abs(area_scores + correction)
458
+ area_scores /= (map_size * map_size) #np.max(area_scores)
459
+ ######################################
460
+
461
+ ###################################### CENTER SCORES
462
+ centers = np.array([[256 // 2, 256 // 2]], dtype='float32') # [1, 2]
463
+ # squares: [n, 4, 2]
464
+ square_centers = np.mean(squares, axis=1) # [n, 2]
465
+ center2center = np.sqrt(np.sum((centers - square_centers) ** 2))
466
+ center_scores = center2center / (map_size / np.sqrt(2.0))
467
+
468
+
469
+ '''
470
+ score_w = [overlap, degree, area, center, length]
471
+ '''
472
+ score_w = [0.0, 1.0, 10.0, 0.5, 1.0]
473
+ score_array = params['w_overlap'] * overlap_scores \
474
+ + params['w_degree'] * degree_scores \
475
+ + params['w_area'] * area_scores \
476
+ - params['w_center'] * center_scores \
477
+ + params['w_length'] * length_scores
478
+
479
+ best_square = []
480
+
481
+ sorted_idx = np.argsort(score_array)[::-1]
482
+ score_array = score_array[sorted_idx]
483
+ squares = squares[sorted_idx]
484
+
485
+ except Exception as e:
486
+ pass
487
+
488
+ try:
489
+ new_segments[:,0] = new_segments[:,0] * 2 / input_shape[1] * original_shape[1]
490
+ new_segments[:,1] = new_segments[:,1] * 2 / input_shape[0] * original_shape[0]
491
+ new_segments[:,2] = new_segments[:,2] * 2 / input_shape[1] * original_shape[1]
492
+ new_segments[:,3] = new_segments[:,3] * 2 / input_shape[0] * original_shape[0]
493
+ except:
494
+ new_segments = []
495
+
496
+ try:
497
+ squares[:,:,0] = squares[:,:,0] * 2 / input_shape[1] * original_shape[1]
498
+ squares[:,:,1] = squares[:,:,1] * 2 / input_shape[0] * original_shape[0]
499
+ except:
500
+ squares = []
501
+ score_array = []
502
+
503
+ try:
504
+ inter_points = np.array(inter_points)
505
+ inter_points[:,0] = inter_points[:,0] * 2 / input_shape[1] * original_shape[1]
506
+ inter_points[:,1] = inter_points[:,1] * 2 / input_shape[0] * original_shape[0]
507
+ except:
508
+ inter_points = []
509
+
510
+
511
+ return new_segments, squares, score_array, inter_points