-
Notifications
You must be signed in to change notification settings - Fork 32
/
ROI_Split_Figure.py
947 lines (811 loc) · 34.3 KB
/
ROI_Split_Figure.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
components/tools/OmeroPy/scripts/omero/figure_scripts/ROI_Split_Figure.py
-----------------------------------------------------------------------------
Copyright (C) 2006-2014 University of Dundee. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
------------------------------------------------------------------------------
This script takes a number of images and displays regions defined by their
ROIs as zoomed panels beside the images.
@author William Moore
<a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a>
@author Jean-Marie Burel
<a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
@author Donald MacDonald
<a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
@version 3.0
<small>
(<b>Internal version:</b> $Revision: $Date: $)
</small>
@since 3.0-Beta4.1
"""
import omero
import omero.scripts as scripts
import omero.util.imageUtil as imgUtil
import omero.util.figureUtil as figUtil
import omero.util.script_utils as scriptUtil
from omero.gateway import BlitzGateway
from omero.rtypes import rlong, robject, rstring, wrap, unwrap
import os
from omero.constants.namespaces import NSCREATED
from omero.constants.projection import ProjectionType
import StringIO
from datetime import date
try:
from PIL import Image, ImageDraw # see ticket:2597
except ImportError:
import Image
import ImageDraw # see ticket:2597
COLOURS = scriptUtil.COLOURS # name:(rgba) map
OVERLAY_COLOURS = dict(COLOURS, **scriptUtil.EXTRA_COLOURS)
logStrings = []
def log(text):
"""
Adds the text to a list of logs. Compiled into figure legend at the end.
"""
print text
logStrings.append(text)
def getROIsplitView(re, pixels, zStart, zEnd, splitIndexes, channelNames,
mergedNames, colourChannels, mergedIndexes, mergedColours,
roiX, roiY, roiWidth, roiHeight, roiZoom, tIndex, spacer,
algorithm, stepping, fontsize, showTopLabels):
"""
This takes a ROI rectangle from an image and makes a split view canvas of
the region in the ROI, zoomed by a defined factor.
@param re The OMERO rendering engine.
"""
if algorithm is None: # omero::constants::projection::ProjectionType
algorithm = ProjectionType.MAXIMUMINTENSITY
mode = "RGB"
white = (255, 255, 255)
sizeX = pixels.getSizeX().getValue()
sizeY = pixels.getSizeY().getValue()
sizeZ = pixels.getSizeZ().getValue()
sizeC = pixels.getSizeC().getValue()
if pixels.getPhysicalSizeX():
physicalX = pixels.getPhysicalSizeX().getValue()
else:
physicalX = 0
if pixels.getPhysicalSizeY():
physicalY = pixels.getPhysicalSizeY().getValue()
else:
physicalY = 0
log(" Pixel size (um): x: %.3f y: %.3f" % (physicalX, physicalY))
log(" Image dimensions (pixels): x: %d y: %d" % (sizeX, sizeY))
log(" Projecting ROIs...")
proStart = zStart
proEnd = zEnd
# make sure we're within Z range for projection.
if proEnd >= sizeZ:
proEnd = sizeZ - 1
if proStart > sizeZ:
proStart = 0
log(" WARNING: Current image has fewer Z-sections than the primary"
" image projection.")
if proStart < 0:
proStart = 0
log(" Projecting z range: %d - %d (max Z is %d)"
% (proStart+1, proEnd+1, sizeZ))
# set up rendering engine with the pixels
pixelsId = pixels.getId().getValue()
re.lookupPixels(pixelsId)
if not re.lookupRenderingDef(pixelsId):
re.resetDefaults()
if not re.lookupRenderingDef(pixelsId):
raise "Failed to lookup Rendering Def"
re.load()
# if we are missing some merged colours, get them from rendering engine.
for index in mergedIndexes:
if index not in mergedColours:
color = tuple(re.getRGBA(index))
mergedColours[index] = color
print "Adding colour to index", color, index
# now get each channel in greyscale (or colour)
# a list of renderedImages (data as Strings) for the split-view row
renderedImages = []
panelWidth = 0
channelMismatch = False
# first, turn off all channels in pixels
for i in range(sizeC):
re.setActive(i, False)
# for each channel in the splitview...
box = (roiX, roiY, roiX+roiWidth, roiY+roiHeight)
for index in splitIndexes:
if index >= sizeC:
# can't turn channel on - simply render black square!
channelMismatch = True
else:
re.setActive(index, True) # turn channel on
if colourChannels:
# if split channels are coloured...
if index in mergedColours:
# and this channel is in the combined image
rgba = tuple(mergedColours[index])
re.setRGBA(index, *rgba) # set coloured
else:
re.setRGBA(index, 255, 255, 255, 255)
else:
# if not colourChannels - channels are white
re.setRGBA(index, 255, 255, 255, 255)
info = (channelNames[index], re.getChannelWindowStart(index),
re.getChannelWindowEnd(index))
log(" Render channel: %s start: %d end: %d" % info)
if proStart == proEnd:
# if it's a single plane, we can render a region (region not
# supported with projection)
planeDef = omero.romio.PlaneDef()
planeDef.z = long(proStart)
planeDef.t = long(tIndex)
regionDef = omero.romio.RegionDef()
regionDef.x = roiX
regionDef.y = roiY
regionDef.width = roiWidth
regionDef.height = roiHeight
planeDef.region = regionDef
rPlane = re.renderCompressed(planeDef)
roiImage = Image.open(StringIO.StringIO(rPlane))
else:
projection = re.renderProjectedCompressed(
algorithm, tIndex, stepping, proStart, proEnd)
fullImage = Image.open(StringIO.StringIO(projection))
roiImage = fullImage.crop(box)
roiImage.load()
# hoping that when we zoom, don't zoom fullImage
if roiZoom is not 1:
newSize = (int(roiWidth*roiZoom), int(roiHeight*roiZoom))
roiImage = roiImage.resize(newSize, Image.ANTIALIAS)
renderedImages.append(roiImage)
panelWidth = roiImage.size[0]
re.setActive(index, False) # turn the channel off again!
# turn on channels in mergedIndexes.
for i in mergedIndexes:
if i >= sizeC:
channelMismatch = True
else:
re.setActive(i, True)
if i in mergedColours:
rgba = mergedColours[i]
re.setRGBA(i, *rgba)
# get the combined image, using the existing rendering settings
channelsString = ", ".join([str(i) for i in mergedIndexes])
log(" Rendering merged channels: %s" % channelsString)
if proStart != proEnd:
merged = re.renderProjectedCompressed(
algorithm, tIndex, stepping, proStart, proEnd)
else:
planeDef = omero.romio.PlaneDef()
planeDef.z = proStart
planeDef.t = tIndex
merged = re.renderCompressed(planeDef)
fullMergedImage = Image.open(StringIO.StringIO(merged))
roiMergedImage = fullMergedImage.crop(box)
# make sure this is not just a lazy copy of the full image
roiMergedImage.load()
if roiZoom is not 1:
newSize = (int(roiWidth*roiZoom), int(roiHeight*roiZoom))
roiMergedImage = roiMergedImage.resize(newSize, Image.ANTIALIAS)
if channelMismatch:
log(" WARNING channel mismatch: The current image has fewer channels"
" than the primary image.")
if panelWidth == 0: # E.g. No split-view panels
panelWidth = roiMergedImage.size[0]
# now assemble the roi split-view canvas
font = imgUtil.getFont(fontsize)
textHeight = font.getsize("Textq")[1]
topSpacer = 0
if showTopLabels:
if mergedNames:
topSpacer = (textHeight * len(mergedIndexes)) + spacer
else:
topSpacer = textHeight + spacer
imageCount = len(renderedImages) + 1 # extra image for merged image
# no spaces around panels
canvasWidth = ((panelWidth + spacer) * imageCount) - spacer
canvasHeight = roiMergedImage.size[1] + topSpacer
print "imageCount", imageCount, "canvasWidth", canvasWidth, \
"canvasHeight", canvasHeight
size = (canvasWidth, canvasHeight)
# create a canvas of appropriate width, height
canvas = Image.new(mode, size, white)
px = 0
textY = topSpacer - textHeight - spacer/2
panelY = topSpacer
# paste the split images in, with channel labels
draw = ImageDraw.Draw(canvas)
print "mergedColours", mergedColours
for i, index in enumerate(splitIndexes):
label = channelNames[index]
indent = (panelWidth - (font.getsize(label)[0])) / 2
# text is coloured if channel is not coloured AND in the merged image
rgb = (0, 0, 0)
if index in mergedColours:
if not colourChannels:
rgb = tuple(mergedColours[index])
if rgb == (255, 255, 255, 255):
# if white (unreadable), needs to be black!
rgb = (0, 0, 0)
if showTopLabels:
draw.text((px+indent, textY), label, font=font, fill=rgb)
if i < len(renderedImages):
imgUtil.pasteImage(renderedImages[i], canvas, px, panelY)
px = px + panelWidth + spacer
# and the merged image
if showTopLabels:
# indent = (panelWidth - (font.getsize("Merged")[0])) / 2
# draw.text((px+indent, textY), "Merged", font=font, fill=(0,0,0))
if (mergedNames):
for index in mergedIndexes:
if index in mergedColours:
rgb = tuple(mergedColours[index])
if rgb == (255, 255, 255, 255):
rgb = (0, 0, 0)
else:
rgb = (0, 0, 0)
if index in channelNames:
name = channelNames[index]
else:
name = str(index)
combTextWidth = font.getsize(name)[0]
inset = int((panelWidth - combTextWidth) / 2)
draw.text((px + inset, textY), name, font=font, fill=rgb)
textY = textY - textHeight
else:
combTextWidth = font.getsize("Merged")[0]
inset = int((panelWidth - combTextWidth) / 2)
draw.text((px + inset, textY), "Merged", font=font,
fill=(0, 0, 0))
imgUtil.pasteImage(roiMergedImage, canvas, px, panelY)
# return the roi splitview canvas, as well as the full merged image
return (canvas, fullMergedImage, panelY)
def drawRectangle(image, roiX, roiY, roiX2, roiY2, colour, stroke=1):
roiDraw = ImageDraw.Draw(image)
for s in range(stroke):
roiBox = (roiX, roiY, roiX2, roiY2)
roiDraw.rectangle(roiBox, outline=colour)
roiX += 1
roiY += 1
roiX2 -= 1
roiY2 -= 1
def getRectangle(roiService, imageId, roiLabel):
"""
Returns (x, y, width, height, zMin, zMax, tMin, tMax) of the first
rectange in the image that has @roiLabel as text
"""
result = roiService.findByImage(imageId, None)
roiText = roiLabel.lower()
roiCount = 0
rectCount = 0
foundLabelledRoi = False
for roi in result.rois:
roiCount += 1
# go through all the shapes of the ROI
for shape in roi.copyShapes():
if type(shape) == omero.model.RectangleI:
t = unwrap(shape.getTheT())
z = unwrap(shape.getTheZ())
x = shape.getX().getValue()
y = shape.getY().getValue()
tv = shape.getTextValue()
if tv is not None:
text = tv.getValue()
else:
text = ""
# get ranges for whole ROI
if rectCount == 0:
zMin = z
zMax = zMin
tMin = t
tMax = tMin
width = shape.getWidth().getValue()
height = shape.getHeight().getValue()
else:
zMin = min(zMin, z)
zMax = max(zMax, z)
tMin = min(tMin, t)
tMax = max(tMax, t)
rectCount += 1
if text is not None and text.lower() == roiText:
foundLabelledRoi = True
if foundLabelledRoi:
return (int(x), int(y), int(width), int(height), int(zMin),
int(zMax), int(tMin), int(tMax))
else:
rectCount = 0 # try another ROI
# if we got here without finding an ROI that matched, simply return any
# ROI we have (last one)
if roiCount > 0:
return (int(x), int(y), int(width), int(height), int(zMin), int(zMax),
int(tMin), int(tMax))
def getSplitView(conn, imageIds, pixelIds, splitIndexes, channelNames,
mergedNames, colourChannels, mergedIndexes, mergedColours,
width, height, imageLabels, spacer, algorithm, stepping,
scalebar, overlayColour, roiZoom, roiLabel):
"""
This method makes a figure of a number of images, arranged in rows with
each row being the split-view of a single image. The channels are arranged
left to right, with the combined image added on the right.
The combined image is rendered according to current settings on the
server, but it's channels will be turned on/off according to
@mergedIndexes.
The figure is returned as a PIL 'Image'
@ session session for server access
@ pixelIds a list of the Ids for the pixels we want to display
@ splitIndexes a list of the channel indexes to display. Same
channels for each image/row
@ channelNames the Map of index:names for all channels
@ zStart the start of Z-range for projection
@ zEnd the end of Z-range for projection
@ colourChannels the colour to make each column/ channel
@ mergedIndexes list or set of channels in the merged image
@ mergedColours index: colour dictionary of channels in the merged
image
@ width the size in pixels to show each panel
@ height the size in pixels to show each panel
@ spacer the gap between images and around the figure. Doubled
between rows.
"""
roiService = conn.getRoiService()
re = conn.createRenderingEngine()
queryService = conn.getQueryService() # only needed for movie
# establish dimensions and roiZoom for the primary image
# getTheseValues from the server
rect = getRectangle(roiService, imageIds[0], roiLabel)
if rect is None:
raise Exception("No ROI found for the first image.")
roiX, roiY, roiWidth, roiHeight, yMin, yMax, tMin, tMax = rect
roiOutline = ((max(width, height)) / 200) + 1
if roiZoom is None:
# get the pixels for priamry image.
pixels = queryService.get("Pixels", pixelIds[0])
sizeY = pixels.getSizeY().getValue()
roiZoom = float(height) / float(roiHeight)
log("ROI zoom set by primary image is %F X" % roiZoom)
else:
log("ROI zoom: %F X" % roiZoom)
textGap = spacer/3
fontsize = 12
if width > 500:
fontsize = 48
elif width > 400:
fontsize = 36
elif width > 300:
fontsize = 24
elif width > 200:
fontsize = 16
font = imgUtil.getFont(fontsize)
textHeight = font.getsize("Textq")[1]
maxCount = 0
for row in imageLabels:
maxCount = max(maxCount, len(row))
leftTextWidth = (textHeight + textGap) * maxCount + spacer
maxSplitPanelWidth = 0
totalcanvasHeight = 0
mergedImages = []
roiSplitPanes = []
topSpacers = [] # space for labels above each row
showLabelsAboveEveryRow = False
invalidImages = [] # note any image row indexes that don't have ROIs.
for row, pixelsId in enumerate(pixelIds):
log("Rendering row %d" % (row))
if showLabelsAboveEveryRow:
showTopLabels = True
else:
showTopLabels = (row == 0) # only show top labels for first row
# need to get the roi dimensions from the server
imageId = imageIds[row]
roi = getRectangle(roiService, imageId, roiLabel)
if roi is None:
log("No Rectangle ROI found for this image")
invalidImages.append(row)
continue
roiX, roiY, roiWidth, roiHeight, zMin, zMax, tStart, tEnd = roi
pixels = queryService.get("Pixels", pixelsId)
sizeX = pixels.getSizeX().getValue()
sizeY = pixels.getSizeY().getValue()
zStart = zMin
zEnd = zMax
# work out if any additional zoom is needed (if the full-sized image
# is different size from primary image)
fullSize = (sizeX, sizeY)
imageZoom = imgUtil.getZoomFactor(fullSize, width, height)
if imageZoom != 1.0:
log(" Scaling down the full-size image by a factor of %F"
% imageZoom)
log(" ROI location (top-left) x: %d y: %d and size width:"
" %d height: %d" % (roiX, roiY, roiWidth, roiHeight))
log(" ROI time: %d - %d zRange: %d - %d"
% (tStart+1, tEnd+1, zStart+1, zEnd+1))
# get the split pane and full merged image
roiSplitPane, fullMergedImage, topSpacer = getROIsplitView(
re, pixels, zStart, zEnd, splitIndexes, channelNames, mergedNames,
colourChannels, mergedIndexes, mergedColours, roiX, roiY,
roiWidth, roiHeight, roiZoom, tStart, spacer, algorithm, stepping,
fontsize, showTopLabels)
# and now zoom the full-sized merged image, add scalebar
mergedImage = imgUtil.resizeImage(fullMergedImage, width, height)
if scalebar:
xIndent = spacer
yIndent = xIndent
# and the scale bar will be half size
sbar = float(scalebar) / imageZoom
status, logMsg = figUtil.addScalebar(
sbar, xIndent, yIndent, mergedImage, pixels, overlayColour)
log(logMsg)
# draw ROI onto mergedImage...
# recalculate roi if the image has been zoomed
x = roiX / imageZoom
y = roiY / imageZoom
roiX2 = (roiX + roiWidth) / imageZoom
roiY2 = (roiY + roiHeight) / imageZoom
drawRectangle(
mergedImage, x, y, roiX2, roiY2, overlayColour, roiOutline)
# note the maxWidth of zoomed panels and total height for row
maxSplitPanelWidth = max(maxSplitPanelWidth, roiSplitPane.size[0])
totalcanvasHeight += spacer + max(height+topSpacer,
roiSplitPane.size[1])
mergedImages.append(mergedImage)
roiSplitPanes.append(roiSplitPane)
topSpacers.append(topSpacer)
# remove the labels for the invalid images (without ROIs)
invalidImages.reverse()
for row in invalidImages:
del imageLabels[row]
# make a figure to combine all split-view rows
# each row has 1/2 spacer above and below the panels. Need extra 1/2
# spacer top and bottom
canvasWidth = leftTextWidth + width + spacer + maxSplitPanelWidth + spacer
figureSize = (canvasWidth, totalcanvasHeight + spacer)
figureCanvas = Image.new("RGB", figureSize, (255, 255, 255))
rowY = spacer
for row, image in enumerate(mergedImages):
labelCanvas = figUtil.getVerticalLabels(imageLabels[row], font,
textGap)
vOffset = (image.size[1] - labelCanvas.size[1]) / 2
imgUtil.pasteImage(labelCanvas, figureCanvas, spacer/2,
rowY + topSpacers[row] + vOffset)
imgUtil.pasteImage(
image, figureCanvas, leftTextWidth, rowY + topSpacers[row])
x = leftTextWidth + width + spacer
imgUtil.pasteImage(roiSplitPanes[row], figureCanvas, x, rowY)
rowY = rowY + max(image.size[1] + topSpacers[row],
roiSplitPanes[row].size[1]) + spacer
return figureCanvas
def roiFigure(conn, commandArgs):
"""
This processes the script parameters, adding defaults if needed.
Then calls a method to make the figure, and finally uploads and attaches
this to the primary image.
@param: session The OMERO session
@param: commandArgs Map of String:Object parameters for the script.
Objects are not rtypes, since getValue() was
called when the map was processed below.
But, list and map objects may contain rtypes (need
to call getValue())
@return: the id of the originalFileLink child. (ID object,
not value)
"""
log("ROI figure created by OMERO on %s" % date.today())
log("")
message = "" # message to be returned to the client
pixelIds = []
imageIds = []
imageLabels = []
# function for getting image labels.
def getImageNames(fullName, tagsList, pdList):
name = fullName.split("/")[-1]
return [name]
# default function for getting labels is getName (or use datasets / tags)
if "Image_Labels" in commandArgs:
if commandArgs["Image_Labels"] == "Datasets":
def getDatasets(name, tagsList, pdList):
return [dataset for project, dataset in pdList]
getLabels = getDatasets
elif commandArgs["Image_Labels"] == "Tags":
def getTags(name, tagsList, pdList):
return tagsList
getLabels = getTags
else:
getLabels = getImageNames
else:
getLabels = getImageNames
# Get the images
images, logMessage = scriptUtil.getObjects(conn, commandArgs)
message += logMessage
if not images:
return None, message
# Check for rectangular ROIs and filter images list
images = [image for image in images if image.getROICount("Rectangle") > 0]
if not images:
message += "No rectangle ROI found."
return None, message
# Attach figure to the first image
omeroImage = images[0]
# process the list of images. If imageIds is not set, script can't run.
log("Image details:")
for image in images:
imageIds.append(image.getId())
pixelIds.append(image.getPrimaryPixels().getId())
# a map of imageId : list of (project, dataset) names.
pdMap = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
imageIds)
tagMap = figUtil.getTagsFromImages(conn.getMetadataService(), imageIds)
# Build a legend entry for each image
for image in images:
name = image.getName()
imageDate = image.getAcquisitionDate()
iId = image.getId()
tagsList = tagMap[iId]
pdList = pdMap[iId]
tags = ", ".join(tagsList)
pdString = ", ".join(["%s/%s" % pd for pd in pdList])
log(" Image: %s ID: %d" % (name, iId))
if imageDate:
log(" Date: %s" % imageDate)
else:
log(" Date: not set")
log(" Tags: %s" % tags)
log(" Project/Datasets: %s" % pdString)
imageLabels.append(getLabels(name, tagsList, pdList))
# use the first image to define dimensions, channel colours etc.
sizeX = omeroImage.getSizeX()
sizeY = omeroImage.getSizeY()
sizeZ = omeroImage.getSizeZ()
sizeC = omeroImage.getSizeC()
width = sizeX
if "Width" in commandArgs:
w = commandArgs["Width"]
try:
width = int(w)
except:
log("Invalid width: %s Using default value: %d" % (str(w), sizeX))
height = sizeY
if "Height" in commandArgs:
h = commandArgs["Height"]
try:
height = int(h)
except:
log("Invalid height: %s Using default value" % (str(h), sizeY))
log("Image dimensions for all panels (pixels): width: %d height: %d"
% (width, height))
mergedIndexes = [] # the channels in the combined image,
mergedColours = {}
if "Merged_Colours" in commandArgs:
cColourMap = commandArgs["Merged_Colours"]
for c in cColourMap:
rgb = cColourMap[c]
try:
rgb = int(rgb)
cIndex = int(c)
except ValueError:
print "Merged_Colours map should be index:rgbInt. Not %s:%s" \
% (c, rgb)
continue
rgba = imgUtil.RGBIntToRGBA(rgb)
mergedColours[cIndex] = rgba
mergedIndexes.append(cIndex)
mergedIndexes.sort()
# make sure we have some merged channels
if len(mergedIndexes) == 0:
mergedIndexes = range(sizeC)
mergedIndexes.reverse()
mergedNames = False
if "Merged_Names" in commandArgs:
mergedNames = commandArgs["Merged_Names"]
# Make channel-names map. If argument wasn't specified, name by index
channelNames = {}
if "Channel_Names" in commandArgs:
cNameMap = commandArgs["Channel_Names"]
for c in range(sizeC):
if str(c) in cNameMap:
channelNames[c] = cNameMap[str(c)]
else:
channelNames[c] = str(c)
else:
for c in range(sizeC):
channelNames[c] = str(c)
# Make split-indexes list. If no "Split_Indexes", show none:
# http://www.openmicroscopy.org/community/viewtopic.php?f=4&t=940
splitIndexes = []
if "Split_Indexes" in commandArgs:
for index in commandArgs["Split_Indexes"]:
splitIndexes.append(index)
colourChannels = True
if "Split_Panels_Grey" in commandArgs and commandArgs["Split_Panels_Grey"]:
colourChannels = False
algorithm = ProjectionType.MAXIMUMINTENSITY
if "Algorithm" in commandArgs:
a = commandArgs["Algorithm"]
if (a == "Mean Intensity"):
algorithm = ProjectionType.MEANINTENSITY
stepping = 1
if "Stepping" in commandArgs:
s = commandArgs["Stepping"]
if (0 < s < sizeZ):
stepping = s
scalebar = None
if "Scalebar" in commandArgs:
sb = commandArgs["Scalebar"]
try:
scalebar = int(sb)
if scalebar <= 0:
scalebar = None
else:
log("Scalebar is %d microns" % scalebar)
except:
log("Invalid value for scalebar: %s" % str(sb))
scalebar = None
overlayColour = (255, 255, 255)
if "Overlay_Colour" in commandArgs:
r, g, b, a = OVERLAY_COLOURS[commandArgs["Overlay_Colour"]]
overlayColour = (r, g, b)
roiZoom = None
if "ROI_Zoom" in commandArgs:
roiZoom = float(commandArgs["ROI_Zoom"])
if roiZoom == 0:
roiZoom = None
roiLabel = "FigureROI"
if "ROI_Label" in commandArgs:
roiLabel = commandArgs["ROI_Label"]
spacer = (width/50) + 2
fig = getSplitView(
conn, imageIds, pixelIds, splitIndexes, channelNames, mergedNames,
colourChannels, mergedIndexes, mergedColours, width, height,
imageLabels, spacer, algorithm, stepping, scalebar, overlayColour,
roiZoom, roiLabel)
if fig is None:
logMessage = "No figure produced"
log("\n"+logMessage)
message += logMessage
return None, message
# fig.show() # bug-fixing only
log("")
figLegend = "\n".join(logStrings)
# print figLegend # bug fixing only
format = commandArgs["Format"]
figureName = "roiFigure"
if "Figure_Name" in commandArgs:
figureName = commandArgs["Figure_Name"]
figureName = os.path.basename(figureName)
output = "localfile"
if format == 'PNG':
output = output + ".png"
figureName = figureName + ".png"
fig.save(output, "PNG")
mimetype = "image/png"
elif format == 'TIFF':
output = output + ".tiff"
figureName = figureName + ".tiff"
fig.save(output, "TIFF")
mimetype = "image/tiff"
else:
output = output + ".jpg"
figureName = figureName + ".jpg"
fig.save(output)
mimetype = "image/jpeg"
# Use util method to upload the figure 'output' to the server, attaching
# it to the omeroImage, adding the
# figLegend as the fileAnnotation description.
# Returns the id of the originalFileLink child. (ID object, not value)
namespace = NSCREATED + "/omero/figure_scripts/ROI_Split_Figure"
fileAnnotation, faMessage = scriptUtil.createLinkFileAnnotation(
conn, output, omeroImage, output="ROI Split figure",
mimetype=mimetype, ns=namespace, desc=figLegend,
origFilePathAndName=figureName)
message += faMessage
return fileAnnotation, message
def runAsScript():
"""
The main entry point of the script, as called by the client via the
scripting service, passing the required parameters.
"""
dataTypes = [rstring('Image')]
labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')]
algorithums = [rstring('Maximum Intensity'), rstring('Mean Intensity')]
roiLabel = """Specify an ROI to pick by specifying it's shape label. \
'FigureROI' by default, (not case sensitive). If matching ROI not found, use \
any ROI."""
formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')]
ckeys = COLOURS.keys()
ckeys.sort()
oColours = wrap(OVERLAY_COLOURS.keys())
client = scripts.client(
'ROI_Split_Figure.py',
"""Create a figure of an ROI region as separate zoomed split-channel \
panels.
NB: OMERO.insight client provides a nicer UI for this script under \
'Publishing Options'
See http://help.openmicroscopy.org/scripts.html""",
# provide 'Data_Type' and 'IDs' parameters so that Insight
# auto-populates with currently selected images.
scripts.String(
"Data_Type", optional=False, grouping="01",
description="The data you want to work with.",
values=dataTypes, default="Image"),
scripts.List(
"IDs", optional=False, grouping="02",
description="List of Dataset IDs or Image IDs").ofType(rlong(0)),
scripts.Map(
"Channel_Names", grouping="03",
description="Map of index: channel name for All channels"),
scripts.Bool(
"Merged_Names", grouping="04",
description="If true, label the merged panel with channel names."
" Otherwise label with 'Merged'"),
scripts.List(
"Split_Indexes", grouping="05",
description="List of the channels in the split view panels"),
scripts.Bool(
"Split_Panels_Grey", grouping="06",
description="If true, all split panels are grayscale"),
scripts.Map(
"Merged_Colours", grouping="07",
description="Map of index:int colors for each merged channel."
" Otherwise use existing colour settings"),
scripts.Int(
"Width", grouping="08",
description="Max width of each image panel", min=1),
scripts.Int(
"Height", grouping="09",
description="The max height of each image panel", min=1),
scripts.String(
"Image_Labels", grouping="10",
description="Label images with the Image's Name or it's Datasets"
" or Tags", values=labels),
scripts.String(
"Algorithm", grouping="11",
description="Algorithum for projection.", values=algorithums),
scripts.Int(
"Stepping", grouping="12",
description="The Z-plane increment for projection. Default is 1",
min=1),
scripts.Int(
"Scalebar", grouping="13",
description="Scale bar size in microns. Only shown if image has"
" pixel-size info.", min=1),
scripts.String(
"Format", grouping="14",
description="Format to save image. E.g 'PNG'.",
values=formats, default='JPEG'),
scripts.String(
"Figure_Name", grouping="15",
description="File name of the figure to save."),
scripts.String(
"Overlay_Colour", grouping="16",
description="The color of the scale bar.",
default='White', values=oColours),
scripts.Float(
"ROI_Zoom", grouping="17",
description="How much to zoom the ROI. E.g. x 2. If 0 then zoom"
" roi panel to fit", min=0),
scripts.String("ROI_Label", grouping="18", description=roiLabel),
version="4.3.0",
authors=["William Moore", "OME Team"],
institutions=["University of Dundee"],
contact="ome-users@lists.openmicroscopy.org.uk",
)
try:
conn = BlitzGateway(client_obj=client)
commandArgs = client.getInputs(unwrap=True)
print commandArgs
# call the main script, attaching resulting figure to Image. Returns
# the id of the originalFileLink child. (ID object, not value)
fileAnnotation, message = roiFigure(conn, commandArgs)
# Return message and file annotation (if applicable) to the client
client.setOutput("Message", rstring(message))
if fileAnnotation is not None:
client.setOutput("File_Annotation", robject(fileAnnotation._obj))
finally:
client.closeSession()
if __name__ == "__main__":
runAsScript()