-
Notifications
You must be signed in to change notification settings - Fork 12
/
views.py
188 lines (145 loc) · 5.71 KB
/
views.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
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
# Copyright 2014 NeuroData (http://neurodata.io)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Create your views here.
import numpy as np
import re
from contextlib import closing
import cStringIO
import django.http
from PIL import Image
import base64
from ndproj.ndproject import NDProject
from spdb.spatialdb import SpatialDB
from ndlib.ndctypelib import recolor_ctype
from ndlib.ndtype import DTYPE_uint8, DTYPE_uint16, ANNOTATION_CHANNELS
from ndlib.windowcutout import windowCutout
import json
#import synaptogram
"""RESTful interface to a synaptogram. Rerturn a png file."""
def synaptogram_view (request, webargs):
"""Render a synaptogram as a Web page"""
try:
m = re.match ("(?P<token>[\d\w]+)/(?P<channels>[\d\w,]+)/(xy|xz|yz)/(?P<resolution>[\d]+)/(?P<xlow>[\d]+),(?P<xhigh>[\d]+)/(?P<ylow>[\d]+),(?P<yhigh>[\d]+)/(?P<zlow>[\d]+),(?P<zhigh>[\d]+)/", webargs)
md = m.groupdict()
token = md['token']
chanstr = md['channels']
resolution = int(md['resolution'])
xlow = int(md['xlow'])
xhigh = int(md['xhigh'])
ylow = int(md['ylow'])
yhigh = int(md['yhigh'])
zlow = int(md['zlow'])
zhigh = int(md['zhigh'])
channels = chanstr.split(',')
# get the project
proj = NDProject.fromTokenName(token)
# and the database and then call the db function
with closing (SpatialDB(proj)) as db:
# convert to cutout coordinates
(xoffset, yoffset, zoffset) = proj.datasetcfg.get_offset(resolution)
(xlow, xhigh) = (xlow-xoffset, xhigh-xoffset)
(ylow, yhigh) = (ylow-yoffset, yhigh-yoffset)
(zlow, zhigh) = (zlow-zoffset, zhigh-zoffset)
corner = [ xlow, ylow, zlow ]
dim = [ xhigh-xlow, yhigh-ylow, zhigh-zlow ]
outputdict = {}
# get the data region for each channel
for chan in channels:
# data type on a per channel basis
ch = proj.getChannelObj(chan)
try:
cb = db.cutout ( ch, corner, dim, resolution )
# apply window for 16 bit projects
if ch.getDataType() in DTYPE_uint16:
[startwindow, endwindow] = window_range = ch.window_range
if (endwindow != 0):
cb.data = np.uint8(windowCutout(cb.data, window_range))
outputdict[chan] = []
for zslice in cb.data:
if ch.getChannelType() in ANNOTATION_CHANNELS:
# parse annotation project
imagemap = np.zeros( [ dim[1], dim[0] ], dtype=np.uint32 )
imagemap = recolor_ctype( zslice, imagemap )
img = Image.frombuffer( 'RGBA', (dim[0],dim[1]), imagemap, 'raw', 'RGBA', 0, 1 )
else:
# parse image project
img = Image.frombuffer( 'L', (dim[0], dim[1]), zslice.flatten(), 'raw', 'L', 0, 1 )
# convert to base64
fileobj = cStringIO.StringIO()
img.save(fileobj, "PNG")
fileobj.seek(0)
encodedimg = base64.b64encode(fileobj.read())
outputdict[chan].append(encodedimg)
#outputdict[chan] = cb.data.tolist()
outputdict['{}.dtype'.format(chan)] = str(cb.data.dtype)
except KeyError:
raise Exception ("Channel %s not found" % ( chan ))
outputdict['shape'] = cb.data.shape
jsonstr = json.dumps ( outputdict )
return django.http.HttpResponse(json.dumps(outputdict), content_type="application/json")
except:
raise
def synaptogram_view_old (request, webargs):
"""Render a synaptogram as a Web page"""
try:
# token and channels
token, chanstr, centroidstr, rest = webargs.split('/',3)
channels = chanstr.split(',')
centroid = map(lambda x: int(x),centroidstr.split(','))
# create the synaptogram object
sog = synaptogram.Synaptogram ( token, channels, centroid )
# set options
# if there is a reference string in the URL
s = re.search ( 'reference/([\w\-,]+)/', rest )
if s != None:
sog.setReference(s.group(1).split(','))
# tell which channels are EM channels -- no reference
s = re.search ( 'EM/([\w\-,]+)/', rest )
if s != None:
sog.setEM(s.group(1).split(','))
# if there is a enhance string in the URL
s = re.search ( 'enhance/([\d.]+)/', rest )
if s != None:
sog.setEnhance(float(s.group(1)))
s = re.search ( 'normalize/', rest )
if s != None:
sog.setNormalize()
s = re.search ( 'normalize2/', rest )
if s != None:
sog.setNormalize2()
# resolution
s = re.search ( 'resolution/([\d]+)/', rest )
if s != None:
sog.setResolution(int(s.group(1)))
# Width of the input data
s = re.search ( 'width/([\d]+)/', rest )
if s != None:
sog.setWidth(int(s.group(1)))
# Width of the input data
s = re.search ( 'tile/([\d]+)/', rest )
if s != None:
sog.setTileWidth(int(s.group(1)))
# Width of the input data
s = re.search ( 'frame/([\d]+)/', rest )
if s != None:
sog.setFrameWidth(int(s.group(1)))
# construct the picture
sogimg = sog.construct()
# Draw the image file
fobj = cStringIO.StringIO()
sogimg.save ( fobj, "PNG" )
fobj.seek(0)
return django.http.HttpResponse(fobj.read(), content_type="image/png" )
except Exception, e:
raise