image_wmts.py
13.1 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# coding=utf-8
#author: 4N
#createtime: 2021/3/24
#email: nheweijun@sina.com
from app.util import *
import traceback
import numpy
from flask import Response
from .util.ImageData import ImageData
from app.modules.service.image.models import ImageService
from app.models import TileScheme,Service
from app.util.component.ApiTemplate import ApiTemplate
from app.util.component.SliceScheme import SliceScheme
from app.util.component.ParameterUtil import ParameterUtil
import json
import random
import copy
from .util.Opencv import Opencv
from .util.Cache import Cache
from .util.MyThread import MyThread
class Api(ApiTemplate):
api_name = "切片"
def __init__(self,service_name):
super().__init__()
self.service_name = service_name
def process(self):
result = {}
parameter: dict = self.para
try:
if parameter.get("service_name"):
self.service_name = parameter.get("service_name")
#获取缓存数据
image_service_info, zoo, servers = Cache.cache_data(self.service_name,type="name")
# 转换参数
parameter = ParameterUtil.to_lower(parameter)
re = parameter.get("request")
if re and re.__eq__("GetCapabilities"):
service = Service.query.filter_by(guid=image_service_info["service"].service_guid).one_or_none()
return self.get_capabilities(image_service_info["service"],service)
if parameter.get("tilematrix"):
if parameter.get("tilematrix").__contains__(":"):
self.level = int(parameter.get("tilematrix").split(":")[-1])
else:
self.level = int(parameter.get("tilematrix"))
if parameter.get("tilerow"):
self.row = int(parameter.get("tilerow"))
if parameter.get("tilecol"):
self.col = int(parameter.get("tilecol"))
image_type = parameter.get("format") if parameter.get("format") else "image/png"
quality = int(parameter.get("quality")) if parameter.get("quality") else 30
slice_para = image_service_info["scheme"]
extent = SliceScheme.get_polygon(slice_para, self.level, self.row, self.col)
height, width = 256,256
# 多线程获取分布式数据
intersect_image = [im for im in image_service_info["images"] if self.determin_intersect(json.loads(im.extent),extent)]
if len(intersect_image) > 1:
# 结果矩阵
pixel_array = numpy.zeros((height, width, 3), dtype=int) + 65536
thread_list = []
for image in intersect_image:
# 该影像的服务器,随机选取一个
image_servers = image.server.split(",")
image_servers = [ser for ser in image_servers if ser in servers]
if len(image_servers)>0:
indx = int(random.random() * len(image_servers))
image_server = image_servers[indx]
else:
image_server = "None"
bands = json.loads(image.band_view)
image_data = ImageData(image_server,image)
thread: MyThread = MyThread(image_data.get_data,args=(extent, bands, height, width))
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
data = thread.get_result()
# 掩膜在中央接口生成,合图
mask = numpy.zeros((height, width, 3), dtype=int)
mask_data = numpy.zeros((height, width, 3), dtype=int)
mask[data == 65536] = 1
mask[data != 65536] = 0
mask_data[data == 65536] = 0
mask_data[data != 65536] = 1
# # 掩膜计算
pixel_array = pixel_array * mask + data * mask_data
# opencv 颜色排序为GBR
d1 = copy.copy(pixel_array[:,:,0])
pixel_array[:, :, 0] = pixel_array[:,:,2]
pixel_array[:, :, 2] = d1
elif len(intersect_image) == 1:
# 该影像的服务器,随机选取一个
image = intersect_image[0]
image_servers = image.server.split(",")
#判断可用服务器
image_servers = [ser for ser in image_servers if ser in servers]
if len(image_servers) > 0:
indx = int(random.random() * len(image_servers))
image_server = image_servers[indx]
else:
image_server = "None"
# image_server = image_servers[0]
bands = json.loads(image.band_view)
image_data = ImageData(image_server, image)
pixel_array_t: numpy.ndarray = image_data.get_data(extent, bands, height, width)
pixel_array = numpy.zeros((height, width, 3), dtype=int)
for ii in [0, 1, 2]:
# opencv 颜色排序为GBR
pixel_array[:, :, 2 - ii] = pixel_array_t[:, :, ii]
else:
# 结果矩阵
pixel_array = numpy.zeros((height, width, 3), dtype=int) + 65536
# 将图片生成在内存中,然后直接返回response
im_data = Opencv.create_image(image_type, pixel_array, quality)
return Response(im_data, mimetype=image_type.lower())
except Exception as e:
print(traceback.format_exc())
result["state"] = -1
result["message"] = e.__str__()
return result
def get_capabilities(self, image_service: ImageService, service: Service):
tile_scheme: TileScheme = TileScheme.query.filter_by(guid=image_service.scheme_guid).one_or_none()
if not tile_scheme:
raise Exception("切片方案不存在!")
xml = '''<Capabilities xmlns="http://www.opengis.net/wmts/1.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml" xsi:schemaLocation="http://www.opengis.net/wmts/1.0 http://schemas.opengis.net/wmts/1.0/wmtsGetCapabilities_response.xsd" version="1.0.0">
<!-- Service Identification -->
<ows:ServiceIdentification>
<ows:Title>{title}</ows:Title>
<ows:ServiceType>OGC WMTS</ows:ServiceType>
<ows:ServiceTypeVersion>1.0.0</ows:ServiceTypeVersion>
</ows:ServiceIdentification>
<!-- Operations Metadata -->
<ows:OperationsMetadata>
<ows:Operation name="GetCapabilities">
<ows:DCP>
<ows:HTTP>
<ows:Get xlink:href="{capabilities_url}">
<ows:Constraint name="GetEncoding">
<ows:AllowedValues>
<ows:Value>RESTful</ows:Value>
</ows:AllowedValues>
</ows:Constraint>
</ows:Get>
<!-- add KVP binding in 10.1 -->
<ows:Get xlink:href="{tile_url}?">
<ows:Constraint name="GetEncoding">
<ows:AllowedValues>
<ows:Value>KVP</ows:Value>
</ows:AllowedValues>
</ows:Constraint>
</ows:Get>
</ows:HTTP>
</ows:DCP>
</ows:Operation>
<ows:Operation name="GetTile">
<ows:DCP>
<ows:HTTP>
<ows:Get xlink:href="{tile_url}">
<ows:Constraint name="GetEncoding">
<ows:AllowedValues>
<ows:Value>RESTful</ows:Value>
</ows:AllowedValues>
</ows:Constraint>
</ows:Get>
<ows:Get xlink:href="{tile_url}?">
<ows:Constraint name="GetEncoding">
<ows:AllowedValues>
<ows:Value>KVP</ows:Value>
</ows:AllowedValues>
</ows:Constraint>
</ows:Get>
</ows:HTTP>
</ows:DCP>
</ows:Operation>
</ows:OperationsMetadata>
<Contents>
<!-- Layer -->
<Layer>
<ows:Title>{title}</ows:Title>
<ows:Identifier>{title}</ows:Identifier>
<ows:BoundingBox crs="{crs}">
<ows:LowerCorner>{xmin} {ymin}</ows:LowerCorner>
<ows:UpperCorner>{xmax} {ymax}</ows:UpperCorner>
</ows:BoundingBox>
<Style isDefault="true">
<ows:Title>Default Style</ows:Title>
<ows:Identifier>default</ows:Identifier>
</Style>
<Format>image/png</Format>
<TileMatrixSetLink>
<TileMatrixSet>{tile_name}</TileMatrixSet>
</TileMatrixSetLink>
<ResourceURL format="image/png" resourceType="tile" template="{tile_url}"/>
</Layer>
<!-- TileMatrixSet -->
<TileMatrixSet>
<TileMatrix>
<ows:Title>{tile_title}</ows:Title>
<ows:Abstract>{tile_description}</ows:Abstract>
<ows:Identifier>{tile_name}</ows:Identifier>
<ows:SupportedCRS>{crs}</ows:SupportedCRS>
{tile_matrix}
</TileMatrix>
</TileMatrixSet>
</Contents>
<ServiceMetadataURL xlink:href="{capabilities_url}"/>
</Capabilities>'''
tile_matrix_each = '''
<TileMatrix>
<ows:Identifier>{lev}</ows:Identifier>
<ScaleDenominator>{scale}</ScaleDenominator>
<TopLeftCorner>{top_left}</TopLeftCorner>
<TileWidth>{cols}</TileWidth>
<TileHeight>{rows}</TileHeight>
</TileMatrix>
'''
tile_matrix = ""
top_left = tile_scheme.top_left
for level in json.loads(tile_scheme.levels):
tile_matrix = "{}{}".format(tile_matrix, tile_matrix_each.format(lev=level["level"],
scale=level["scale"],
top_left=top_left,
cols=tile_scheme.cols,
rows=tile_scheme.rows))
extent = json.loads(image_service.extent)
xml = xml.format(
capabilities_url="http://{}/API/Service/Image/Capabilities?guid={}".format(configure.deploy_ip_host,
image_service.guid),
tile_url="http://{}/API/Service/Image/Tile?guid={}".format(configure.deploy_ip_host, image_service.guid),
crs=tile_scheme.crs,
xmin=extent[0],
ymin=extent[1],
xmax=extent[2],
ymax=extent[3],
# TileMatrix = "{TileMatrix}",
# TileRow = "{TileRow}",
# TileCol = "{TileCol}",
guid=image_service.guid,
title=service.title,
tile_title=tile_scheme.name,
tile_name=tile_scheme.name,
tile_description=tile_scheme.description,
tile_matrix=tile_matrix
)
r = Response(response=xml, status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r
def determin_intersect(self, extent1, extent2):
if extent2[2] < extent1[0] or extent2[0] > extent1[2] or extent2[1] > extent1[
3] or extent2[3] < extent1[1]:
return False
else:
return True
api_doc = {
"tags": ["影像接口"],
"parameters": [
{"name": "guid",
"in": "formData",
"type": "string"},
{"name": "request",
"in": "formData",
"type": "string",
"enum": ["GetTile", "GetCapabilities"]},
{"name": "tilematrix",
"in": "formData",
"type": "string"},
{"name": "tilerow",
"in": "formData",
"type": "string"},
{"name": "tilecol",
"in": "formData",
"type": "string"},
{"name": "format",
"in": "formData",
"type": "string"},
{"name": "quality",
"in": "formData",
"type": "string"}
],
"responses": {
200: {
"schema": {
"properties": {
}
}
}
}
}