-
Notifications
You must be signed in to change notification settings - Fork 100
/
views.py
2456 lines (2161 loc) · 85.3 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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# webgateway/views.py - django application view handling functions
#
# Copyright (c) 2007-2015 Glencoe Software, Inc. All rights reserved.
#
# This software is distributed under the terms described by the LICENCE file
# you can find at the root of the distribution bundle, which states you are
# free to use it only for non commercial purposes.
# If the file is missing please request a copy by contacting
# jason@glencoesoftware.com.
#
# Author: Carlos Neves <carlos(at)glencoesoftware.com>
import re
import json
import omero
import omero.clients
from django.http import HttpResponse, HttpResponseServerError
from django.http import HttpResponseRedirect, HttpResponseNotAllowed, Http404
from django.template import loader as template_loader
from django.views.decorators.http import require_POST
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template import RequestContext as Context
from django.core.servers.basehttp import FileWrapper
from omero.rtypes import rlong, unwrap
from omero.constants.namespaces import NSBULKANNOTATIONS
from omero.util.ROI_utils import pointsStringToXYlist, xyListToBbox
from plategrid import PlateGrid
from omero_version import build_year
from marshal import imageMarshal, shapeMarshal, rgb_int2rgba
try:
from hashlib import md5
except:
from md5 import md5
from cStringIO import StringIO
import tempfile
from omero import ApiUsageException
from omero.util.decorators import timeit, TimeIt
from omeroweb.http import HttpJavascriptResponse, HttpJsonResponse, \
HttpJavascriptResponseServerError
import glob
# from models import StoredConnection
from webgateway_cache import webgateway_cache, CacheBase, webgateway_tempfile
cache = CacheBase()
import logging
import os
import traceback
import time
import zipfile
import shutil
from omeroweb.decorators import login_required, ConnCleaningHttpResponse
from omeroweb.connector import Connector
from omeroweb.webgateway.util import zip_archived_files, getIntOrDefault
logger = logging.getLogger(__name__)
try:
from PIL import Image
from PIL import ImageDraw
except: # pragma: nocover
try:
import Image
import ImageDraw
except:
logger.error('No Pillow installed')
try:
import numpy
numpyInstalled = True
except ImportError:
logger.error('No numpy installed')
numpyInstalled = False
def index(request):
""" /webgateway/ index placeholder """
return HttpResponse("Welcome to webgateway")
def _safestr(s):
return unicode(s).encode('utf-8')
class UserProxy (object):
"""
Represents the current user of the connection, with methods delegating to
the connection itself.
"""
def __init__(self, blitzcon):
"""
Initialises the User proxy with the L{omero.gateway.BlitzGateway}
connection
@param blitzcon: connection
@type blitzcon: L{omero.gateway.BlitzGateway}
"""
self._blitzcon = blitzcon
self.loggedIn = False
def logIn(self):
""" Sets the loggedIn Flag to True """
self.loggedIn = True
def isAdmin(self):
"""
True if the current user is an admin
@return: True if the current user is an admin
@rtype: Boolean
"""
return self._blitzcon.isAdmin()
def canBeAdmin(self):
"""
True if the current user can be admin
@return: True if the current user can be admin
@rtype: Boolean
"""
return self._blitzcon.canBeAdmin()
def getId(self):
"""
Returns the ID of the current user
@return: User ID
@rtype: Long
"""
return self._blitzcon.getUserId()
def getName(self):
"""
Returns the Name of the current user
@return: User Name
@rtype: String
"""
return self._blitzcon.getUser().omeName
def getFirstName(self):
"""
Returns the first name of the current user
@return: First Name
@rtype: String
"""
return self._blitzcon.getUser().firstName or self.getName()
# def getPreferences (self):
# return self._blitzcon._user.getPreferences()
#
# def getUserObj (self):
# return self._blitzcon._user
#
# class SessionCB (object):
# def _log (self, what, c):
# logger.debug('CONN:%s %s:%d:%s' % (what, c._user, os.getpid(),
# c._sessionUuid))
#
# def create (self, c):
# self._log('create',c)
#
# def join (self, c):
# self._log('join',c)
#
# def close (self, c):
# self._log('close',c)
# _session_cb = SessionCB()
def _split_channel_info(rchannels):
"""
Splits the request query channel information for images into a sequence of
channels, window ranges and channel colors.
@param rchannels: The request string with channel info. E.g
1|100:505$0000FF,-2,3|620:3879$FF0000
@type rchannels: String
@return: E.g. [1, -2, 3] [[100.0, 505.0], (None, None), [620.0,
3879.0]] [u'0000FF', None, u'FF0000']
@rtype: tuple of 3 lists
"""
channels = []
windows = []
colors = []
for chan in rchannels.split(','):
chan = chan.split('|')
t = chan[0].strip()
color = None
if t.find('$') >= 0:
t, color = t.split('$')
try:
channels.append(int(t))
ch_window = (None, None)
if len(chan) > 1:
t = chan[1].strip()
if t.find('$') >= 0:
t, color = t.split('$')
t = t.split(':')
if len(t) == 2:
try:
ch_window = [float(x) for x in t]
except ValueError:
pass
windows.append(ch_window)
colors.append(color)
except ValueError:
pass
logger.debug(str(channels)+","+str(windows)+","+str(colors))
return channels, windows, colors
def getImgDetailsFromReq(request, as_string=False):
"""
Break the GET information from the request object into details on how
to render the image.
The following keys are recognized:
z - Z axis position
t - T axis position
q - Quality set (0,0..1,0)
m - Model (g for greyscale, c for color)
p - Projection (see blitz_gateway.ImageWrapper.PROJECTIONS for keys)
x - X position (for now based on top/left offset on the browser window)
y - Y position (same as above)
c - a comma separated list of channels to be rendered (start index 1)
- format for each entry [-]ID[|wndst:wndend][#HEXCOLOR][,...]
zm - the zoom setting (as a percentual value)
@param request: http request with keys above
@param as_string: If True, return a string representation of the
rendering details
@return: A dict or String representation of rendering details
above.
@rtype: Dict or String
"""
r = request.GET
rv = {}
for k in ('z', 't', 'q', 'm', 'zm', 'x', 'y', 'p'):
if k in r:
rv[k] = r[k]
if 'c' in r:
rv['c'] = []
ci = _split_channel_info(r['c'])
logger.debug(ci)
for i in range(len(ci[0])):
# a = abs channel, i = channel, s = window start, e = window end,
# c = color
rv['c'].append({'a': abs(ci[0][i]), 'i': ci[0][i],
's': ci[1][i][0], 'e': ci[1][i][1],
'c': ci[2][i]})
if as_string:
return "&".join(["%s=%s" % (x[0], x[1]) for x in rv.items()])
return rv
@login_required()
def render_birds_eye_view(request, iid, size=None,
conn=None, **kwargs):
"""
Returns an HttpResponse wrapped jpeg with the rendered bird's eye view
for image 'iid'. We now use a thumbnail for performance. #10626
@param request: http request
@param iid: Image ID
@param conn: L{omero.gateway.BlitzGateway} connection
@param size: Maximum size of the longest side of the resulting
bird's eye view.
@return: http response containing jpeg
"""
if size is None:
size = 96 # Use cached thumbnail
return render_thumbnail(request, iid, w=size, **kwargs)
@login_required()
def render_thumbnail(request, iid, w=None, h=None, conn=None, _defcb=None,
**kwargs):
"""
Returns an HttpResponse wrapped jpeg with the rendered thumbnail for image
'iid'
@param request: http request
@param iid: Image ID
@param w: Thumbnail max width. 64 by default
@param h: Thumbnail max height
@return: http response containing jpeg
"""
server_id = request.session['connector'].server_id
direct = True
if w is None:
size = (64,)
else:
if h is None:
size = (int(w),)
else:
size = (int(w), int(h))
if size == (96,):
direct = False
user_id = conn.getUserId()
z = getIntOrDefault(request, 'z', None)
t = getIntOrDefault(request, 't', None)
rdefId = getIntOrDefault(request, 'rdefId', None)
# TODO - cache handles rdefId
jpeg_data = webgateway_cache.getThumb(request, server_id, user_id, iid,
size)
if jpeg_data is None:
prevent_cache = False
img = conn.getObject("Image", iid)
if img is None:
logger.debug("(b)Image %s not found..." % (str(iid)))
if _defcb:
jpeg_data = _defcb(size=size)
prevent_cache = True
else:
raise Http404
else:
jpeg_data = img.getThumbnail(
size=size, direct=direct, rdefId=rdefId, z=z, t=t)
if jpeg_data is None:
logger.debug("(c)Image %s not found..." % (str(iid)))
if _defcb:
jpeg_data = _defcb(size=size)
prevent_cache = True
else:
return HttpResponseServerError(
'Failed to render thumbnail')
else:
prevent_cache = img._thumbInProgress
if not prevent_cache:
webgateway_cache.setThumb(request, server_id, user_id, iid,
jpeg_data, size)
else:
pass
rsp = HttpResponse(jpeg_data, content_type='image/jpeg')
return rsp
@login_required()
def render_roi_thumbnail(request, roiId, w=None, h=None, conn=None, **kwargs):
"""
For the given ROI, choose the shape to render (first time-point, mid
z-section) then render a region around that shape, scale to width and
height (or default size) and draw the shape on to the region
"""
server_id = request.session['connector'].server_id
# need to find the z indices of the first shape in T
roiResult = conn.getRoiService().findByRoi(
long(roiId), None, conn.SERVICE_OPTS)
if roiResult is None or roiResult.rois is None:
raise Http404
zz = set()
minT = None
shapes = {}
for roi in roiResult.rois:
imageId = roi.image.id.val
for s in roi.copyShapes():
if s is None: # seems possible in some situations
continue
t = unwrap(s.getTheT())
z = unwrap(s.getTheZ())
shapes[(z, t)] = s
if minT is None:
minT = t
if t < minT:
zz = set([z])
minT = t
elif minT == t:
zz.add(z)
zList = list(zz)
if len(zList) == 0:
raise Http404("No Shapes found for ROI %s" % roiId)
zList.sort()
midZ = zList[len(zList)/2]
s = shapes[(midZ, minT)]
pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn)
if pi is None:
raise Http404
image, compress_quality = pi
return get_shape_thumbnail(request, conn, image, s, compress_quality)
@login_required()
def render_shape_thumbnail(request, shapeId, w=None, h=None, conn=None,
**kwargs):
"""
For the given Shape, redner a region around that shape, scale to width and
height (or default size) and draw the shape on to the region.
"""
server_id = request.session['connector'].server_id
# need to find the z indices of the first shape in T
params = omero.sys.Parameters()
params.map = {'id': rlong(shapeId)}
shape = conn.getQueryService().findByQuery(
"select s from Shape s join fetch s.roi where s.id = :id", params,
conn.SERVICE_OPTS)
if shape is None:
raise Http404
imageId = shape.roi.image.id.val
pi = _get_prepared_image(request, imageId, server_id=server_id, conn=conn)
if pi is None:
raise Http404
image, compress_quality = pi
return get_shape_thumbnail(request, conn, image, shape, compress_quality)
def get_shape_thumbnail(request, conn, image, s, compress_quality):
"""
Render a region around the specified Shape, scale to width and height (or
default size) and draw the shape on to the region. Returns jpeg data.
@param image: ImageWrapper
@param s: omero.model.Shape
"""
MAX_WIDTH = 250
color = request.GET.get("color", "fff")
colours = {"f00": (255, 0, 0), "0f0": (0, 255, 0), "00f": (0, 0, 255),
"ff0": (255, 255, 0), "fff": (255, 255, 255), "000": (0, 0, 0)}
lineColour = colours["f00"]
if color in colours:
lineColour = colours[color]
# used for padding if we go outside the image area
bg_color = (221, 221, 221)
bBox = None # bounding box: (x, y, w, h)
shape = {}
theT = s.getTheT() is not None and s.getTheT().getValue() or 0
theZ = s.getTheZ() is not None and s.getTheZ().getValue() or 0
if type(s) == omero.model.RectangleI:
shape['type'] = 'Rectangle'
shape['x'] = s.getX().getValue()
shape['y'] = s.getY().getValue()
shape['width'] = s.getWidth().getValue()
shape['height'] = s.getHeight().getValue()
bBox = (shape['x'], shape['y'], shape['width'], shape['height'])
elif type(s) == omero.model.MaskI:
shape['type'] = 'Mask'
shape['x'] = s.getX().getValue()
shape['y'] = s.getY().getValue()
shape['width'] = s.getWidth().getValue()
shape['height'] = s.getHeight().getValue()
bBox = (shape['x'], shape['y'], shape['width'], shape['height'])
# TODO: support for mask
elif type(s) == omero.model.EllipseI:
shape['type'] = 'Ellipse'
shape['cx'] = int(s.getCx().getValue())
shape['cy'] = int(s.getCy().getValue())
shape['rx'] = int(s.getRx().getValue())
shape['ry'] = int(s.getRy().getValue())
bBox = (shape['cx']-shape['rx'], shape['cy']-shape['ry'],
2*shape['rx'], 2*shape['ry'])
elif type(s) == omero.model.PolylineI:
shape['type'] = 'PolyLine'
shape['xyList'] = pointsStringToXYlist(s.getPoints().getValue())
bBox = xyListToBbox(shape['xyList'])
elif type(s) == omero.model.LineI:
shape['type'] = 'Line'
shape['x1'] = int(s.getX1().getValue())
shape['x2'] = int(s.getX2().getValue())
shape['y1'] = int(s.getY1().getValue())
shape['y2'] = int(s.getY2().getValue())
x = min(shape['x1'], shape['x2'])
y = min(shape['y1'], shape['y2'])
bBox = (x, y, max(shape['x1'], shape['x2'])-x,
max(shape['y1'], shape['y2'])-y)
elif type(s) == omero.model.PointI:
shape['type'] = 'Point'
shape['cx'] = s.getCx().getValue()
shape['cy'] = s.getCy().getValue()
bBox = (shape['cx']-50, shape['cy']-50, 100, 100)
elif type(s) == omero.model.PolygonI:
shape['type'] = 'Polygon'
shape['xyList'] = pointsStringToXYlist(s.getPoints().getValue())
bBox = xyListToBbox(shape['xyList'])
elif type(s) == omero.model.LabelI:
shape['type'] = 'Label'
shape['x'] = s.getX().getValue()
shape['y'] = s.getY().getValue()
bBox = (shape['x']-50, shape['y']-50, 100, 100)
else:
logger.debug("Shape type not supported: %s" % str(type(s)))
# we want to render a region larger than the bounding box
x, y, w, h = bBox
# make the aspect ratio (w/h) = 3/2
requiredWidth = max(w, h*3/2)
requiredHeight = requiredWidth*2/3
# make the rendered region 1.5 times larger than the bounding box
newW = int(requiredWidth * 1.5)
newH = int(requiredHeight * 1.5)
# Don't want the region to be smaller than the thumbnail dimensions
if newW < MAX_WIDTH:
newW = MAX_WIDTH
newH = newW*2/3
# Don't want the region to be bigger than a 'Big Image'!
def getConfigValue(key):
try:
return conn.getConfigService().getConfigValue(key)
except:
logger.warn("webgateway: get_shape_thumbnail() could not get"
" Config-Value for %s" % key)
pass
max_plane_width = getConfigValue("omero.pixeldata.max_plane_width")
max_plane_height = getConfigValue("omero.pixeldata.max_plane_height")
if (max_plane_width is None or max_plane_height is None or
(newW > int(max_plane_width)) or (newH > int(max_plane_height))):
# generate dummy image to return
dummy = Image.new('RGB', (MAX_WIDTH, MAX_WIDTH*2/3), bg_color)
draw = ImageDraw.Draw(dummy)
draw.text((10, 30), "Shape too large to \ngenerate thumbnail",
fill=(255, 0, 0))
rv = StringIO()
dummy.save(rv, 'jpeg', quality=90)
return HttpResponse(rv.getvalue(), content_type='image/jpeg')
xOffset = (newW - w)/2
yOffset = (newH - h)/2
newX = int(x - xOffset)
newY = int(y - yOffset)
# Need to check if any part of our region is outside the image. (assume
# that SOME of the region is within the image!)
sizeX = image.getSizeX()
sizeY = image.getSizeY()
left_xs, right_xs, top_xs, bottom_xs = 0, 0, 0, 0
if newX < 0:
newW = newW + newX
left_xs = abs(newX)
newX = 0
if newY < 0:
newH = newH + newY
top_xs = abs(newY)
newY = 0
if newW+newX > sizeX:
right_xs = (newW+newX) - sizeX
newW = newW - right_xs
if newH+newY > sizeY:
bottom_xs = (newH+newY) - sizeY
newH = newH - bottom_xs
# now we should be getting the correct region
jpeg_data = image.renderJpegRegion(theZ, theT, newX, newY, newW, newH,
level=None,
compression=compress_quality)
img = Image.open(StringIO(jpeg_data))
# add back on the xs we were forced to trim
if left_xs != 0 or right_xs != 0 or top_xs != 0 or bottom_xs != 0:
jpg_w, jpg_h = img.size
xs_w = jpg_w + right_xs + left_xs
xs_h = jpg_h + bottom_xs + top_xs
xs_image = Image.new('RGBA', (xs_w, xs_h), bg_color)
xs_image.paste(img, (left_xs, top_xs))
img = xs_image
# we have our full-sized region. Need to resize to thumbnail.
current_w, current_h = img.size
factor = float(MAX_WIDTH) / current_w
resizeH = int(current_h * factor)
img = img.resize((MAX_WIDTH, resizeH))
draw = ImageDraw.Draw(img)
if shape['type'] == 'Rectangle':
rectX = int(xOffset * factor)
rectY = int(yOffset * factor)
rectW = int((w+xOffset) * factor)
rectH = int((h+yOffset) * factor)
draw.rectangle((rectX, rectY, rectW, rectH), outline=lineColour)
# hack to get line width of 2
draw.rectangle((rectX-1, rectY-1, rectW+1, rectH+1),
outline=lineColour)
elif shape['type'] == 'Line':
lineX1 = (shape['x1'] - newX + left_xs) * factor
lineX2 = (shape['x2'] - newX + left_xs) * factor
lineY1 = (shape['y1'] - newY + top_xs) * factor
lineY2 = (shape['y2'] - newY + top_xs) * factor
draw.line((lineX1, lineY1, lineX2, lineY2), fill=lineColour, width=2)
elif shape['type'] == 'Ellipse':
rectX = int(xOffset * factor)
rectY = int(yOffset * factor)
rectW = int((w+xOffset) * factor)
rectH = int((h+yOffset) * factor)
draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour)
# hack to get line width of 2
draw.ellipse((rectX-1, rectY-1, rectW+1, rectH+1), outline=lineColour)
elif shape['type'] == 'Point':
point_radius = 2
rectX = (MAX_WIDTH/2) - point_radius
rectY = int(resizeH/2) - point_radius
rectW = rectX + (point_radius * 2)
rectH = rectY + (point_radius * 2)
draw.ellipse((rectX, rectY, rectW, rectH), outline=lineColour)
# hack to get line width of 2
draw.ellipse((rectX-1, rectY-1, rectW+1, rectH+1), outline=lineColour)
elif 'xyList' in shape:
# resizedXY = [(int(x*factor), int(y*factor))
# for (x,y) in shape['xyList']]
def resizeXY(xy):
x, y = xy
return (int((x-newX + left_xs)*factor),
int((y-newY + top_xs)*factor))
resizedXY = [resizeXY(xy) for xy in shape['xyList']]
# doesn't support 'width' of line
# draw.polygon(resizedXY, outline=lineColour)
x2 = y2 = None
for l in range(1, len(resizedXY)):
x1, y1 = resizedXY[l-1]
x2, y2 = resizedXY[l]
draw.line((x1, y1, x2, y2), fill=lineColour, width=2)
start_x, start_y = resizedXY[0]
if shape['type'] != 'PolyLine':
# Seems possible to have Polygon with only 1 point!
if x2 is None:
x2 = start_x + 1 # This will create a visible dot
if y2 is None:
y2 = start_y + 1
draw.line((x2, y2, start_x, start_y), fill=lineColour, width=2)
rv = StringIO()
compression = 0.9
img.save(rv, 'jpeg', quality=int(compression*100))
jpeg = rv.getvalue()
return HttpResponse(jpeg, content_type='image/jpeg')
@login_required()
def render_shape_mask(request, shapeId, conn=None, **kwargs):
""" Returns mask as a png (supports transparency) """
if not numpyInstalled:
raise NotImplementedError("numpy not installed")
params = omero.sys.Parameters()
params.map = {'id': rlong(shapeId)}
shape = conn.getQueryService().findByQuery(
"select s from Shape s where s.id = :id", params,
conn.SERVICE_OPTS)
if shape is None:
raise Http404("Shape ID: %s not found" % shapeId)
width = int(shape.getWidth().getValue())
height = int(shape.getHeight().getValue())
color = unwrap(shape.getFillColor())
fill = (255, 255, 0, 255)
if color is not None:
color = rgb_int2rgba(color)
fill = (color[0], color[1], color[2], int(color[3] * 255))
mask_packed = shape.getBytes()
# convert bytearray into something we can use
intarray = numpy.fromstring(mask_packed, dtype=numpy.uint8)
binarray = numpy.unpackbits(intarray)
# Couldn't get the 'proper' way of doing this to work,
# TODO: look at this again later. Faster than simple way below:
# E.g. takes ~2 seconds for 1984 x 1984 mask
# pixels = ""
# steps = len(binarray) / 8
# for i in range(steps):
# b = binarray[i*8: (i+1)*8]
# pixels += struct.pack("8B", b[0], b[1], b[2], b[3], b[4],
# b[5], b[6], b[7])
# for b in binarray:
# pixels += struct.pack("1B", b)
# im = Image.frombytes("1", size=(width, height), data=pixels)
# Simple approach - Just set each pixel in turn
# E.g. takes ~12 seconds for 1984 x 1984 mask with most pixels '1'
# Or ~5 seconds for same size mask with most pixels "0"
img = Image.new("RGBA", size=(width, height), color=(0, 0, 0, 0))
x = 0
y = 0
for pix in binarray:
if pix == 1:
img.putpixel((x, y), fill)
x += 1
if x > width - 1:
x = 0
y += 1
rv = StringIO()
# return a png (supports transparency)
img.save(rv, 'png', quality=int(100))
png = rv.getvalue()
return HttpResponse(png, content_type='image/png')
def _get_signature_from_request(request):
"""
returns a string that identifies this image, along with the settings
passed on the request.
Useful for using as img identifier key, for prepared image.
@param request: http request
@return: String
"""
r = request.GET
rv = r.get('m', '_') + r.get('p', '_') + r.get('c', '_') + r.get('q', '_')
return rv
def _get_prepared_image(request, iid, server_id=None, conn=None,
saveDefs=False, retry=True):
"""
Fetches the Image object for image 'iid' and prepares it according to the
request query, setting the channels, rendering model and projection
arguments. The compression level is parsed and returned too.
For parameters in request, see L{getImgDetailsFromReq}
@param request: http request
@param iid: Image ID
@param conn: L{omero.gateway.BlitzGateway} connection
@param saveDefs: Try to save the rendering settings, default z and t.
@param retry: Try an extra attempt at this method
@return: Tuple (L{omero.gateway.ImageWrapper} image, quality)
"""
r = request.GET
logger.debug('Preparing Image:%r saveDefs=%r '
'retry=%r request=%r conn=%s' % (iid, saveDefs, retry,
r, str(conn)))
img = conn.getObject("Image", iid)
if img is None:
return
if 'c' in r:
logger.debug("c="+r['c'])
channels, windows, colors = _split_channel_info(r['c'])
if not img.setActiveChannels(channels, windows, colors):
logger.debug(
"Something bad happened while setting the active channels...")
if r.get('m', None) == 'g':
img.setGreyscaleRenderingModel()
elif r.get('m', None) == 'c':
img.setColorRenderingModel()
# projection 'intmax' OR 'intmax|5:25'
p = r.get('p', None)
pStart, pEnd = None, None
if p is not None and len(p.split('|')) > 1:
p, startEnd = p.split('|', 1)
try:
pStart, pEnd = [int(s) for s in startEnd.split(':')]
except ValueError:
pass
img.setProjection(p)
img.setProjectionRange(pStart, pEnd)
img.setInvertedAxis(bool(r.get('ia', "0") == "1"))
compress_quality = r.get('q', None)
if saveDefs:
'z' in r and img.setDefaultZ(long(r['z'])-1)
't' in r and img.setDefaultT(long(r['t'])-1)
img.saveDefaults()
return (img, compress_quality)
@login_required()
def render_image_region(request, iid, z, t, conn=None, **kwargs):
"""
Returns a jpeg of the OMERO image, rendering only a region specified in
query string as region=x,y,width,height. E.g. region=0,512,256,256
Rendering settings can be specified in the request parameters.
@param request: http request
@param iid: image ID
@param z: Z index
@param t: T index
@param conn: L{omero.gateway.BlitzGateway} connection
@return: http response wrapping jpeg
"""
server_id = request.session['connector'].server_id
# if the region=x,y,w,h is not parsed correctly to give 4 ints then we
# simply provide whole image plane.
# alternatively, could return a 404?
# if h == None:
# return render_image(request, iid, z, t, server_id=None, _conn=None,
# **kwargs)
pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn)
if pi is None:
raise Http404
img, compress_quality = pi
tile = request.GET.get('tile', None)
region = request.GET.get('region', None)
level = None
if tile:
try:
img._prepareRenderingEngine()
w, h = img._re.getTileSize()
levels = img._re.getResolutionLevels()-1
zxyt = tile.split(",")
# w = int(zxyt[3])
# h = int(zxyt[4])
level = levels-int(zxyt[0])
x = int(zxyt[1])*w
y = int(zxyt[2])*h
except:
logger.debug("render_image_region: tile=%s" % tile)
logger.debug(traceback.format_exc())
elif region:
try:
xywh = region.split(",")
x = int(xywh[0])
y = int(xywh[1])
w = int(xywh[2])
h = int(xywh[3])
except:
logger.debug("render_image_region: region=%s" % region)
logger.debug(traceback.format_exc())
# region details in request are used as key for caching.
jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t)
if jpeg_data is None:
jpeg_data = img.renderJpegRegion(z, t, x, y, w, h, level=level,
compression=compress_quality)
if jpeg_data is None:
raise Http404
webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data)
rsp = HttpResponse(jpeg_data, content_type='image/jpeg')
return rsp
@login_required()
def render_image(request, iid, z=None, t=None, conn=None, **kwargs):
"""
Renders the image with id {{iid}} at {{z}} and {{t}} as jpeg.
Many options are available from the request dict. See
L{getImgDetailsFromReq} for list.
I am assuming a single Pixels object on image with image-Id='iid'. May be
wrong
@param request: http request
@param iid: image ID
@param z: Z index
@param t: T index
@param conn: L{omero.gateway.BlitzGateway} connection
@return: http response wrapping jpeg
"""
server_id = request.session['connector'].server_id
pi = _get_prepared_image(request, iid, server_id=server_id, conn=conn)
if pi is None:
raise Http404
img, compress_quality = pi
jpeg_data = webgateway_cache.getImage(request, server_id, img, z, t)
if jpeg_data is None:
jpeg_data = img.renderJpeg(z, t, compression=compress_quality)
if jpeg_data is None:
raise Http404
webgateway_cache.setImage(request, server_id, img, z, t, jpeg_data)
format = request.GET.get('format', 'jpeg')
rsp = HttpResponse(jpeg_data, content_type='image/jpeg')
if 'download' in kwargs and kwargs['download']:
if format == 'png':
# convert jpeg data to png...
i = Image.open(StringIO(jpeg_data))
output = StringIO()
i.save(output, 'png')
jpeg_data = output.getvalue()
output.close()
rsp = HttpResponse(jpeg_data, content_type='image/png')
# don't seem to need to do this for tiff
elif format == 'tif':
rsp = HttpResponse(jpeg_data, content_type='image/tif')
fileName = img.getName().decode('utf8').replace(" ", "_")
fileName = fileName.replace(",", ".")
rsp['Content-Type'] = 'application/force-download'
rsp['Content-Length'] = len(jpeg_data)
rsp['Content-Disposition'] = (
'attachment; filename=%s.%s'
% (fileName, format))
return rsp
@login_required()
def render_ome_tiff(request, ctx, cid, conn=None, **kwargs):
"""
Renders the OME-TIFF representation of the image(s) with id cid in ctx
(i)mage, (d)ataset, or (p)roject.
For multiple images export, images that require pixels pyramid (big
images) will be silently skipped.
If exporting a single big image or if all images in a multple image export
are big, a 404 will be triggered.
A request parameter dryrun can be passed to return the count of images
that would actually be exported.
@param request: http request
@param ctx: 'p' or 'd' or 'i'
@param cid: Project, Dataset or Image ID
@param conn: L{omero.gateway.BlitzGateway} connection
@return: http response wrapping the tiff (or zip for multiple
files), or redirect to temp file/zip
if dryrun is True, returns count of images that would
be exported
"""
server_id = request.session['connector'].server_id
imgs = []
if ctx == 'p':
obj = conn.getObject("Project", cid)
if obj is None:
raise Http404
for d in obj.listChildren():
imgs.extend(list(d.listChildren()))
name = obj.getName()
elif ctx == 'd':
obj = conn.getObject("Dataset", cid)
if obj is None:
raise Http404
imgs.extend(list(obj.listChildren()))
selection = filter(None,
request.GET.get('selection', '').split(','))
if len(selection):
logger.debug(selection)
logger.debug(imgs)
imgs = filter(lambda x: str(x.getId()) in selection, imgs)
logger.debug(imgs)
if len(imgs) == 0:
raise Http404
name = '%s-%s' % (obj.getParent().getName(), obj.getName())
elif ctx == 'w':
obj = conn.getObject("Well", cid)
if obj is None:
raise Http404
imgs.extend([x.getImage() for x in obj.listChildren()])
plate = obj.getParent()
coord = "%s%s" % (plate.getRowLabels()[obj.row],
plate.getColumnLabels()[obj.column])
name = '%s-%s-%s' % (plate.getParent().getName(), plate.getName(),
coord)
else:
obj = conn.getObject("Image", cid)
if obj is None:
raise Http404
imgs.append(obj)
imgs = filter(lambda x: not x.requiresPixelsPyramid(), imgs)
if request.GET.get('dryrun', False):
rv = json.dumps(len(imgs))
c = request.GET.get('callback', None)
if c is not None and not kwargs.get('_internal', False):
rv = '%s(%s)' % (c, rv)
return HttpJavascriptResponse(rv)
if len(imgs) == 0:
raise Http404
if len(imgs) == 1:
obj = imgs[0]
key = ('_'.join((str(x.getId()) for x in obj.getAncestry())) +
'_' + str(obj.getId()) + '_ome_tiff')
# total name len <= 255, 9 is for .ome.tiff
fnamemax = 255 - len(str(obj.getId())) - 10
objname = obj.getName()[:fnamemax]
fpath, rpath, fobj = webgateway_tempfile.new(
str(obj.getId()) + '-' + objname + '.ome.tiff', key=key)
if fobj is True:
# already exists
return HttpResponseRedirect(settings.STATIC_URL +
'webgateway/tfiles/' + rpath)
tiff_data = webgateway_cache.getOmeTiffImage(request, server_id,
imgs[0])
if tiff_data is None:
try:
tiff_data = imgs[0].exportOmeTiff()