-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathFigure_To_Pdf.py
2361 lines (1988 loc) · 83.5 KB
/
Figure_To_Pdf.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 -*-
#
# Copyright (c) 2014-2015 University of Dundee.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
import json
import numpy
import html
from datetime import datetime
import os
from os import path
import zipfile
from math import atan2, atan, sin, cos, sqrt, radians, floor, ceil
from copy import deepcopy
from omero.model import ImageAnnotationLinkI, ImageI, LengthI
import omero.scripts as scripts
from omero.gateway import BlitzGateway
from omero.rtypes import rstring, robject
from omero.model.enums import UnitsLength
from io import BytesIO
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
import Image
import ImageDraw
logger = logging.getLogger('figure_to_pdf')
try:
import markdown
markdown_imported = True
except ImportError:
markdown_imported = False
logger.error("Markdown not installed. See"
" https://pypi.python.org/pypi/Markdown")
try:
from reportlab.pdfgen import canvas
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.colors import Color
from reportlab.platypus import Paragraph
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
reportlab_installed = True
except ImportError:
reportlab_installed = False
logger.error("Reportlab not installed.")
DEFAULT_OFFSET = 0
ORIGINAL_DIR = "1_originals"
RESAMPLED_DIR = "2_pre_resampled"
FINAL_DIR = "3_final"
README_TXT = """These folders contain images used in the creation
of the figure. Each folder contains one image per figure panel,
with images numbered according to the order they were added to
the figure. The numbered folders represent the sequence of
processing steps:
- 1_originals: This contains the full-sized and un-cropped images that are
rendered by OMERO according to your chosen rendering settings.
- 2_pre_resampled: This folder will only contain those images that are
resampled in order to match the export figure resolution. This will be
all panels for export of TIFF figures. For export of PDF Figures,
only panels that have a 'dpi' set, which is higher than their
existing resolution will be resampled.
- 3_final: These are the image panels that are inserted into the
final figure, saved following any cropping, rotation and resampling steps.
"""
# Create a dict we can use for scalebar unit conversions
unit_symbols = {}
for name in LengthI.SYMBOLS.keys():
if name in ("PIXEL", "REFERENCEFRAME"):
continue
klass = getattr(UnitsLength, name)
unit = LengthI(1, klass)
to_microns = LengthI(unit, UnitsLength.MICROMETER)
unit_symbols[name] = {
'symbol': unit.getSymbol(),
'microns': to_microns.getValue()
}
def scale_to_export_dpi(pixels):
"""
Original figure coordinates assume 72 dpi figure, but we want to
export at 300 dpi, so everything needs scaling accordingly
"""
return pixels * 300//72
def compress(target, base):
"""
Creates a ZIP recursively from a given base directory.
@param target: Name of the zip file we want to write E.g.
"folder.zip"
@param base: Name of folder that we want to zip up E.g. "folder"
"""
zip_file = zipfile.ZipFile(target, 'w')
try:
for root, dirs, files in os.walk(base):
archive_root = os.path.relpath(root, base)
for f in files:
fullpath = os.path.join(root, f)
archive_name = os.path.join(archive_root, f)
zip_file.write(fullpath, archive_name)
finally:
zip_file.close()
class Bounds(object):
def __init__(self, *points):
self.minx = None
self.maxx = None
self.miny = None
self.maxy = None
for point in points:
self.add_point(*point)
def add_point(self, x, y):
if self.minx is None or x < self.minx:
self.minx = x
if self.maxx is None or x > self.maxx:
self.maxx = x
if self.miny is None or y < self.miny:
self.miny = y
if self.maxy is None or y > self.maxy:
self.maxy = y
def get_center(self):
if self.minx is None:
return None
return (self.minx + self.maxx) / 2.0, (self.miny + self.maxy) / 2.0
def grow(self, pixels):
if self.minx is None:
return self
self.minx -= pixels
self.miny -= pixels
self.maxx += pixels
self.maxy += pixels
return self
def round(self):
self.minx = int(floor(self.minx))
self.miny = int(floor(self.miny))
self.maxx = int(ceil(self.maxx))
self.maxy = int(ceil(self.maxy))
return self
def get_size(self):
if self.minx is None:
return None
return (self.maxx - self.minx, self.maxy - self.miny)
class ShapeExport(object):
# base class for different export formats
def __init__(self, panel):
self.panel = panel
for s in panel.get("shapes", ()):
getattr(self, 'draw_%s' % s['type'].lower(), lambda s: None)(s)
@staticmethod
def get_rgb(color):
# Convert from E.g. '#ff0000' to (255, 0, 0)
red = int(color[1:3], 16)
green = int(color[3:5], 16)
blue = int(color[5:7], 16)
return (red, green, blue)
@staticmethod
def get_rgba_int(color):
# Convert from E.g. '#ff0000ff' to (255, 0, 0, 255)
red = int(color[1:3], 16)
green = int(color[3:5], 16)
blue = int(color[5:7], 16)
alpha = int(color[7:9] or 'ff', 16)
return (red, green, blue, alpha)
@staticmethod
def get_rgba(color):
# Convert from E.g. '#ff0000ff' to (1.0, 0, 0, 1.0)
return tuple(map(lambda i: i / 255.0, ShapeExport.get_rgba_int(color)))
@staticmethod
def apply_transform(tf, point):
return [
point[0] * tf['A00'] + point[1] * tf['A01'] + tf['A02'],
point[0] * tf['A10'] + point[1] * tf['A11'] + tf['A12'],
] if tf else point
def draw_rectangle(self, shape):
# to support rotation/transforms, convert rectangle to a simple
# four point polygon and draw that instead
s = deepcopy(shape)
t = shape.get('transform')
points = [
(shape['x'], shape['y']),
(shape['x'] + shape['width'], shape['y']),
(shape['x'] + shape['width'], shape['y'] + shape['height']),
(shape['x'], shape['y'] + shape['height']),
]
s['points'] = ' '.join(','.join(
map(str, self.apply_transform(t, point))) for point in points)
self.draw_polygon(s)
def draw_point(self, shape):
s = deepcopy(shape)
s['radiusX'] = s['radiusY'] = self.point_radius / self.scale
self.draw_ellipse(s)
class ShapeToPdfExport(ShapeExport):
point_radius = 5
def __init__(self, canvas, panel, page, crop, page_height):
self.canvas = canvas
self.page = page
# The crop region on the original image coordinates...
self.crop = crop
self.page_height = page_height
# Get a mapping from original coordinates to the actual size of panel
self.scale = float(panel['width']) / crop['width']
super(ShapeToPdfExport, self).__init__(panel)
def panel_to_page_coords(self, shape_x, shape_y):
"""
Convert coordinate from the image onto the PDF page.
Handles zoom, offset & rotation of panel, rotating the
x, y point around the centre of the cropped region
and scaling appropriately.
Also includes 'inPanel' key - True if point within
the cropped panel region
"""
rotation = self.panel['rotation']
if rotation != 0:
# img coords: centre of rotation
cx = self.crop['x'] + (self.crop['width']/2)
cy = self.crop['y'] + (self.crop['height']/2)
dx = cx - shape_x
dy = cy - shape_y
# distance of point from centre of rotation
h = sqrt(dx * dx + dy * dy)
# and the angle
angle1 = atan2(dx, dy)
# Add the rotation to the angle and calculate new
# opposite and adjacent lengths from centre of rotation
angle2 = angle1 - radians(rotation)
newo = sin(angle2) * h
newa = cos(angle2) * h
# to give correct x and y within cropped panel
shape_x = cx - newo
shape_y = cy - newa
# convert to coords within crop region
shape_x = shape_x - self.crop['x']
shape_y = shape_y - self.crop['y']
# check if points are within panel
in_panel = True
if shape_x < 0 or shape_x > self.crop['width']:
in_panel = False
if shape_y < 0 or shape_y > self.crop['height']:
in_panel = False
# Handle page offsets
x = self.panel['x'] - self.page['x']
y = self.panel['y'] - self.page['y']
# scale and position on page within panel
shape_x = (shape_x * self.scale) + x
shape_y = (shape_y * self.scale) + y
return {'x': shape_x, 'y': shape_y, 'inPanel': in_panel}
def draw_shape_label(self, shape, bounds):
center = bounds.get_center()
text = html.escape(shape.get('text', ''))
if not text or not center:
return
size = shape.get('fontSize', 12) * 2 / 3
r, g, b, a = self.get_rgba(shape['strokeColor'])
# bump up alpha a bit to make text more readable
rgba = (r, g, b, 0.5 + a / 2.0)
style = ParagraphStyle(
'label',
parent=getSampleStyleSheet()['Normal'],
alignment=TA_CENTER,
textColor=Color(*rgba),
fontSize=size,
leading=size,
)
para = Paragraph(text, style)
w, h = para.wrap(10000, 100)
para.drawOn(
self.canvas, center[0] - w / 2, center[1] - h / 2 + size / 4)
def draw_line(self, shape):
start = self.panel_to_page_coords(shape['x1'], shape['y1'])
end = self.panel_to_page_coords(shape['x2'], shape['y2'])
x1 = start['x']
y1 = self.page_height - start['y']
x2 = end['x']
y2 = self.page_height - end['y']
# Don't draw if both points outside panel
if (start['inPanel'] is False) and (end['inPanel'] is False):
return
rgb = self.get_rgb(shape['strokeColor'])
r = float(rgb[0])/255
g = float(rgb[1])/255
b = float(rgb[2])/255
self.canvas.setStrokeColorRGB(r, g, b)
stroke_width = shape.get('strokeWidth', 1)
self.canvas.setLineWidth(stroke_width)
p = self.canvas.beginPath()
p.moveTo(x1, y1)
p.lineTo(x2, y2)
self.canvas.drawPath(p, fill=1, stroke=1)
self.draw_shape_label(shape, Bounds((x1, y1), (x2, y2)))
def draw_arrow(self, shape):
start = self.panel_to_page_coords(shape['x1'], shape['y1'])
end = self.panel_to_page_coords(shape['x2'], shape['y2'])
x1 = start['x']
y1 = self.page_height - start['y']
x2 = end['x']
y2 = self.page_height - end['y']
stroke_width = shape.get('strokeWidth', 1)
# Don't draw if both points outside panel
if (start['inPanel'] is False) and (end['inPanel'] is False):
return
rgb = self.get_rgb(shape['strokeColor'])
r = float(rgb[0])/255
g = float(rgb[1])/255
b = float(rgb[2])/255
self.canvas.setStrokeColorRGB(r, g, b)
self.canvas.setFillColorRGB(r, g, b)
head_size = (stroke_width * 4) + 5
dx = x2 - x1
dy = y2 - y1
self.canvas.setLineWidth(stroke_width)
p = self.canvas.beginPath()
f = -1
if dy == 0:
line_angle = radians(90)
if dx < 0:
f = 1
else:
line_angle = atan(dx / dy)
if dy < 0:
f = 1
# Angle of arrow head is 0.8 radians (0.4 either side of line_angle)
arrow_point1_x = x2 + (f * sin(line_angle - 0.4) * head_size)
arrow_point1_y = y2 + (f * cos(line_angle - 0.4) * head_size)
arrow_point2_x = x2 + (f * sin(line_angle + 0.4) * head_size)
arrow_point2_y = y2 + (f * cos(line_angle + 0.4) * head_size)
arrow_point_mid_x = x2 + (f * sin(line_angle) * head_size * 0.5)
arrow_point_mid_y = y2 + (f * cos(line_angle) * head_size * 0.5)
# Draw the line (at lineWidth)
p.moveTo(x1, y1)
p.lineTo(arrow_point_mid_x, arrow_point_mid_y)
self.canvas.drawPath(p, fill=1, stroke=1)
# Draw the arrow head (at lineWidth: 0)
self.canvas.setLineWidth(0)
p.moveTo(arrow_point1_x, arrow_point1_y)
p.lineTo(arrow_point2_x, arrow_point2_y)
p.lineTo(x2, y2)
p.lineTo(arrow_point1_x, arrow_point1_y)
self.canvas.drawPath(p, fill=1, stroke=1)
self.draw_shape_label(shape, Bounds((x1, y1), (x2, y2)))
def draw_polygon(self, shape, closed=True):
polygon_in_viewport = False
points = []
for point in shape['points'].split(" "):
# Older polygons/polylines may be 'x,y,'
xy = point.split(",")
x = xy[0]
y = xy[1]
coords = self.panel_to_page_coords(float(x), float(y))
points.append([coords['x'], self.page_height - coords['y']])
polygon_in_viewport = polygon_in_viewport or coords['inPanel']
# Don't draw if all points outside panel viewport
if not polygon_in_viewport:
return
stroke_width = shape.get('strokeWidth', 1)
r, g, b, a = self.get_rgba(shape['strokeColor'])
self.canvas.setStrokeColorRGB(r, g, b, alpha=a)
self.canvas.setLineWidth(stroke_width)
if 'fillColor' in shape:
r, g, b, a = self.get_rgba(shape['fillColor'])
self.canvas.setFillColorRGB(r, g, b, alpha=a)
fill = 1 if closed else 0
else:
fill = 0
p = self.canvas.beginPath()
# Go to start...
p.moveTo(points[0][0], points[0][1])
# ...around other points...
for point in points[1:]:
p.lineTo(point[0], point[1])
# ...and back over first line
if closed:
for point in points[0:2]:
p.lineTo(point[0], point[1])
self.canvas.drawPath(p, fill=fill, stroke=1)
self.draw_shape_label(shape, Bounds(*points))
def draw_polyline(self, shape):
self.draw_polygon(shape, False)
def draw_ellipse(self, shape):
stroke_width = shape.get('strokeWidth', 1)
c = self.panel_to_page_coords(shape['x'], shape['y'])
# Don't draw if centre outside panel
if c['inPanel'] is False:
return
cx = c['x']
cy = self.page_height - c['y']
rx = shape['radiusX'] * self.scale
ry = shape['radiusY'] * self.scale
rotation = (shape['rotation'] + self.panel['rotation']) * -1
r, g, b, a = self.get_rgba(shape['strokeColor'])
self.canvas.setStrokeColorRGB(r, g, b, alpha=a)
if 'fillColor' in shape:
r, g, b, a = self.get_rgba(shape['fillColor'])
self.canvas.setFillColorRGB(r, g, b, alpha=a)
fill = 1
else:
fill = 0
label_bounds = Bounds((cx, cy))
# For rotation, we reset our coordinates around cx, cy
# so that rotation applies around cx, cy
self.canvas.saveState()
self.canvas.translate(cx, cy)
self.canvas.rotate(rotation)
# centre is now at 0, 0
cx = 0
cy = 0
height = ry * 2
width = rx * 2
left = cx - rx
bottom = cy - ry
# Draw ellipse...
p = self.canvas.beginPath()
self.canvas.setLineWidth(stroke_width)
p.ellipse(left, bottom, width, height)
self.canvas.drawPath(p, stroke=1, fill=fill)
# Restore coordinates, rotation etc.
self.canvas.restoreState()
self.draw_shape_label(shape, label_bounds)
class ShapeToPilExport(ShapeExport):
"""
Class for drawing panel shapes onto a PIL image.
We get a PIL image, the panel dict, and crop coordinates
"""
point_radius = 25
def __init__(self, pil_img, panel, crop):
self.pil_img = pil_img
self.panel = panel
# The crop region on the original image coordinates...
self.crop = crop
self.scale = pil_img.size[0] / crop['width']
self.draw = ImageDraw.Draw(pil_img)
super(ShapeToPilExport, self).__init__(panel)
def get_panel_coords(self, shape_x, shape_y):
"""
Convert coordinate from the image onto the panel.
Handles zoom, offset & rotation of panel, rotating the
x, y point around the centre of the cropped region
and scaling appropriately
"""
rotation = self.panel['rotation']
if rotation != 0:
# img coords: centre of rotation
cx = self.crop['x'] + (self.crop['width']/2)
cy = self.crop['y'] + (self.crop['height']/2)
dx = cx - shape_x
dy = cy - shape_y
# distance of point from centre of rotation
h = sqrt(dx * dx + dy * dy)
# and the angle
angle1 = atan2(dx, dy)
# Add the rotation to the angle and calculate new
# opposite and adjacent lengths from centre of rotation
angle2 = angle1 - radians(rotation)
newo = sin(angle2) * h
newa = cos(angle2) * h
# to give correct x and y within cropped panel
shape_x = cx - newo
shape_y = cy - newa
# convert to coords within crop region
shape_x = (shape_x - self.crop['x']) * self.scale
shape_y = (shape_y - self.crop['y']) * self.scale
return {'x': shape_x, 'y': shape_y}
def draw_shape_label(self, shape, bounds):
center = bounds.get_center()
text = shape.get('text')
size = int(shape.get('fontSize', 12) * 2.5)
if not text or not center:
return
r, g, b, a = self.get_rgba_int(shape['strokeColor'])
# bump up alpha a bit to make text more readable
rgba = (r, g, b, 128 + a / 2)
font_name = "FreeSans.ttf"
from omero.gateway import THISPATH
path_to_font = os.path.join(THISPATH, "pilfonts", font_name)
try:
font = ImageFont.truetype(path_to_font, size)
except Exception:
font = ImageFont.load(
'%s/pilfonts/B%0.2d.pil' % (self.GATEWAYPATH, size))
textsize = font.getsize(text)
xy = (center[0] - textsize[0] / 2.0, center[1] - textsize[1] / 2.0)
self.draw.text(xy, text, fill=rgba, font=font)
def draw_arrow(self, shape):
start = self.get_panel_coords(shape['x1'], shape['y1'])
end = self.get_panel_coords(shape['x2'], shape['y2'])
x1 = start['x']
y1 = start['y']
x2 = end['x']
y2 = end['y']
head_size = ((shape.get('strokeWidth', 1) * 4) + 5)
head_size = scale_to_export_dpi(head_size)
stroke_width = scale_to_export_dpi(shape.get('strokeWidth', 2))
rgb = ShapeToPdfExport.get_rgb(shape['strokeColor'])
# Do some trigonometry to get the line angle can calculate arrow points
dx = x2 - x1
dy = y2 - y1
if dy == 0:
line_angle = radians(90)
else:
line_angle = atan(dx / dy)
f = -1
if dy < 0:
f = 1
# Angle of arrow head is 0.8 radians (0.4 either side of line_angle)
arrow_point1_x = x2 + (f * sin(line_angle - 0.4) * head_size)
arrow_point1_y = y2 + (f * cos(line_angle - 0.4) * head_size)
arrow_point2_x = x2 + (f * sin(line_angle + 0.4) * head_size)
arrow_point2_y = y2 + (f * cos(line_angle + 0.4) * head_size)
arrow_point_mid_x = x2 + (f * sin(line_angle) * head_size * 0.5)
arrow_point_mid_y = y2 + (f * cos(line_angle) * head_size * 0.5)
points = ((x2, y2),
(arrow_point1_x, arrow_point1_y),
(arrow_point2_x, arrow_point2_y),
(x2, y2)
)
# Draw Line of arrow - to midpoint of head at full stroke width
self.draw.line([(x1, y1), (arrow_point_mid_x, arrow_point_mid_y)],
fill=rgb, width=int(stroke_width))
# Draw Arrow head, up to tip at x2, y2
self.draw.polygon(points, fill=rgb, outline=rgb)
self.draw_shape_label(shape, Bounds((x1, y1), (x2, y2)))
# Override to not just call draw_polygon, because we want square corners
# for rectangles and not the rounded corners draw_polygon creates
def draw_rectangle(self, shape):
points = [
(shape['x'], shape['y']),
(shape['x'] + shape['width'], shape['y']),
(shape['x'] + shape['width'], shape['y'] + shape['height']),
(shape['x'], shape['y'] + shape['height']),
]
p = []
t = shape.get('transform')
for point in points:
transformed = self.apply_transform(t, point)
coords = self.get_panel_coords(*transformed)
p.append((coords['x'], coords['y']))
p.append(p[0])
points = p
stroke_width = scale_to_export_dpi(int(shape.get('strokeWidth', 2)))
buffer = int(ceil(stroke_width) * 1.5)
# if fill, draw filled polygon without outline, then add line later
# with correct stroke width
rgba = self.get_rgba_int(shape.get('fillColor', '#00000000'))
# need to draw on separate image and then paste on to get transparency
bounds = Bounds(*points).round()
offset = (bounds.minx, bounds.miny)
points = [
(point[0] - offset[0] + buffer, point[1] - offset[1] + buffer)
for point in points
]
bounds.grow(buffer)
temp_image = Image.new('RGBA', bounds.get_size())
temp_draw = ImageDraw.Draw(temp_image)
# if fill color, draw polygon without outline first
if rgba[3]:
temp_draw.polygon(points, fill=rgba, outline=(0, 0, 0, 0))
def extend_line(p0, p1, pixels):
dx = p1[0] - p0[0]
dy = p1[1] - p0[1]
d = sqrt(dx * dx + dy * dy)
return (
p0,
(p1[0] + dx * pixels / d, p1[1] + dy * pixels / d)
)
# Draw all the lines (NB: polygon doesn't handle line width)
rgba = self.get_rgba_int(shape['strokeColor'])
width = int(round(stroke_width))
for i in range(4):
# extend each line a little bit to fill in the corners
line = extend_line(points[i], points[i + 1], width / 2)
temp_draw.line(line, fill=rgba, width=width)
self.pil_img.paste(
temp_image, (bounds.minx, bounds.miny), mask=temp_image)
self.draw_shape_label(shape, bounds)
def draw_polygon(self, shape, closed=True):
points = []
for point in shape['points'].split(" "):
# Older polygons/polylines may be 'x,y,'
xy = point.split(",")
x = xy[0]
y = xy[1]
coords = self.get_panel_coords(float(x), float(y))
points.append((coords['x'], coords['y']))
if closed:
points.append(points[0])
stroke_width = scale_to_export_dpi(shape.get('strokeWidth', 2))
buffer = int(ceil(stroke_width))
# if fill, draw filled polygon without outline, then add line later
# with correct stroke width
rgba = self.get_rgba_int(shape.get('fillColor', '#00000000'))
# need to draw on separate image and then paste on to get transparency
bounds = Bounds(*points).round()
offset = (bounds.minx, bounds.miny)
points = [
(point[0] - offset[0] + buffer, point[1] - offset[1] + buffer)
for point in points
]
bounds.grow(buffer)
temp_image = Image.new('RGBA', bounds.get_size())
temp_draw = ImageDraw.Draw(temp_image)
# if fill color, draw polygon without outline first
if closed and rgba[3]:
temp_draw.polygon(points, fill=rgba, outline=(0, 0, 0, 0))
# Draw all the lines (NB: polygon doesn't handle line width)
rgba = self.get_rgba_int(shape['strokeColor'])
temp_draw.line(points, fill=rgba, width=int(round(stroke_width)))
# Draw ellipse at each corner
# see https://stackoverflow.com/questions/33187698/
r = (stroke_width/2) * 0.9 # seems to look OK with this size
if closed:
corners = points[:]
else:
corners = points[1: -1]
for point in corners:
temp_draw.ellipse((point[0] - r, point[1] - r,
point[0] + r, point[1] + r), fill=rgba)
self.pil_img.paste(
temp_image, (bounds.minx, bounds.miny), mask=temp_image)
self.draw_shape_label(shape, bounds)
def draw_polyline(self, shape):
self.draw_polygon(shape, False)
def draw_line(self, shape):
start = self.get_panel_coords(shape['x1'], shape['y1'])
end = self.get_panel_coords(shape['x2'], shape['y2'])
x1 = start['x']
y1 = start['y']
x2 = end['x']
y2 = end['y']
stroke_width = scale_to_export_dpi(shape.get('strokeWidth', 2))
rgba = ShapeToPdfExport.get_rgba_int(shape['strokeColor'])
self.draw.line(
[(x1, y1), (x2, y2)], fill=rgba, width=int(stroke_width))
self.draw_shape_label(shape, Bounds((x1, y1), (x2, y2)))
def draw_ellipse(self, shape):
w = int(scale_to_export_dpi(shape.get('strokeWidth', 2)))
ctr = self.get_panel_coords(shape['x'], shape['y'])
cx = ctr['x']
cy = ctr['y']
rx = self.scale * shape['radiusX']
ry = self.scale * shape['radiusY']
rotation = (shape['rotation'] + self.panel['rotation']) * -1
width = int((rx * 2) + w)
height = int((ry * 2) + w)
temp_ellipse = Image.new('RGBA', (width + 1, height + 1),
(255, 255, 255, 0))
ellipse_draw = ImageDraw.Draw(temp_ellipse)
# Draw outer ellipse, then remove inner ellipse with full opacity
rgba = ShapeToPdfExport.get_rgba_int(shape['strokeColor'])
ellipse_draw.ellipse((0, 0, width, height), fill=rgba)
rgba = self.get_rgba_int(shape.get('fillColor', '#00000000'))
ellipse_draw.ellipse((w, w, width - w, height - w), fill=rgba)
temp_ellipse = temp_ellipse.rotate(rotation, resample=Image.BICUBIC,
expand=True)
# Use ellipse as mask, so transparent part is not pasted
paste_x = cx - (temp_ellipse.size[0]/2)
paste_y = cy - (temp_ellipse.size[1]/2)
self.pil_img.paste(temp_ellipse, (int(paste_x), int(paste_y)),
mask=temp_ellipse)
self.draw_shape_label(shape, Bounds((cx, cy)))
class FigureExport(object):
"""
Super class for exporting various figures, such as PDF or TIFF etc.
"""
def __init__(self, conn, script_params, export_images=False):
self.conn = conn
self.script_params = script_params
self.export_images = export_images
self.ns = "omero.web.figure.pdf"
self.mimetype = "application/pdf"
figure_json_string = script_params['Figure_JSON']
try:
# Since unicode can't be wrapped by rstring, py2
figure_json_string = figure_json_string.decode('utf8')
except AttributeError:
# python 3
pass
self.figure_json = self.version_transform_json(
self._fix_figure_json(json.loads(figure_json_string)))
n = datetime.now()
# time-stamp name by default: Figure_2013-10-29_22-43-53.pdf
self.figure_name = u"Figure_%s-%s-%s_%s-%s-%s" % (
n.year, n.month, n.day, n.hour, n.minute, n.second)
if 'figureName' in self.figure_json:
self.figure_name = self.figure_json['figureName']
# get Figure width & height...
self.page_width = self.figure_json['paper_width']
self.page_height = self.figure_json['paper_height']
def _fix_figure_json(self, figure_json):
"""Ensure that the figure JSON is proper.
"""
# In some cases, dx and dy end up missing or set to null.
# See issue #257 (missing) and #292 (null value).
for panel in figure_json['panels']:
for key in ['dx', 'dy']:
offset = panel.get(key)
if offset is None:
panel[key] = DEFAULT_OFFSET
return figure_json
def version_transform_json(self, figure_json):
v = figure_json.get('version')
if v < 3:
print("Transforming to VERSION 3")
for p in figure_json['panels']:
if p.get('export_dpi'):
# rename 'export_dpi' attr to 'min_export_dpi'
p['min_export_dpi'] = p.get('export_dpi')
del p['export_dpi']
# update strokeWidth to page pixels/coords instead of
# image pixels. Scale according to size of panel and zoom
if p.get('shapes') and len(p['shapes']) > 0:
image_pixels_width = self.get_crop_region(p)['width']
page_coords_width = float(p.get('width'))
stroke_width_scale = page_coords_width/image_pixels_width
for shape in p['shapes']:
stroke_width = shape.get('strokeWidth', 1)
stroke_width = stroke_width * stroke_width_scale
# Set stroke-width to 0.25, 0.5, 0.75, 1 or greater
if stroke_width > 0.875:
stroke_width = int(round(stroke_width))
elif stroke_width > 0.625:
stroke_width = 0.75
elif stroke_width > 0.375:
stroke_width = 0.5
else:
stroke_width = 0.25
shape['strokeWidth'] = stroke_width
return figure_json
def get_zip_name(self):
name = self.figure_name
# in case we have path/to/name.pdf, just use name.pdf
name = path.basename(name)
# Remove commas: causes problems 'duplicate headers' in file download
name = name.replace(",", ".")
return "%s.zip" % name
def get_figure_file_name(self, page=None):
"""
For PDF export we will only create a single figure file, but
for TIFF export we may have several pages, so we need unique names
for each to avoid overwriting.
This method supports both, simply using different extension
(pdf/tiff) for each.
@param page: If we know a page number we want to use.
"""
# Extension is pdf or tiff
fext = self.get_figure_file_ext()
name = self.figure_name
# in case we have path/to/name, just use name
name = path.basename(name)
# if ends with E.g. .pdf, remove extension
if name.endswith("." + fext):
name = name[0: -len("." + fext)]
# Name with extension and folder
full_name = "%s.%s" % (name, fext)
# Remove commas: causes problems 'duplicate headers' in file download
full_name = full_name.replace(",", ".")
index = page if page is not None else 1
if fext == "tiff" and self.page_count > 1:
full_name = "%s_page_%02d.%s" % (name, index, fext)
if self.zip_folder_name is not None:
full_name = os.path.join(self.zip_folder_name, full_name)
while(os.path.exists(full_name)):
index += 1
full_name = "%s_page_%02d.%s" % (name, index, fext)
if self.zip_folder_name is not None:
full_name = os.path.join(self.zip_folder_name, full_name)
# Handy to know what the last created file is:
self.figure_file_name = full_name
return full_name
def build_figure(self):
"""
The main building of the figure happens here, independently of format.
We set up directories as needed, call create_figure() to create
the PDF or TIFF then iterate through figure pages, adding panels
for each page.
Then we add an info page and create a zip of everything if needed.
Finally the created file or zip is uploaded to OMERO and attached
as a file annotation to all the images in the figure.
"""
# test to see if we've got multiple pages
page_count = ('page_count' in self.figure_json and
self.figure_json['page_count'] or 1)
self.page_count = int(page_count)
paper_spacing = ('paper_spacing' in self.figure_json and
self.figure_json['paper_spacing'] or 50)
page_col_count = ('page_col_count' in self.figure_json and
int(self.figure_json['page_col_count']) or 1)
# Create a zip if we have multiple TIFF pages or we're exporting Images
export_option = self.script_params['Export_Option']
create_zip = False
if self.export_images:
create_zip = True
if (self.page_count > 1) and (export_option.startswith("TIFF")):
create_zip = True
# somewhere to put PDF and images
self.zip_folder_name = None
if create_zip:
self.zip_folder_name = "figure"
curr_dir = os.getcwd()
zip_dir = os.path.join(curr_dir, self.zip_folder_name)
os.mkdir(zip_dir)
if self.export_images:
for d in (ORIGINAL_DIR, RESAMPLED_DIR, FINAL_DIR):
img_dir = os.path.join(zip_dir, d)
os.mkdir(img_dir)
self.add_read_me_file()
# Create the figure file(s)
self.create_figure()
panels_json = self.figure_json['panels']
image_ids = set()
group_id = None
# We get our group from the first image
id1 = panels_json[0]['imageId']
group_id = self.conn.getObject("Image", id1).getDetails().group.id.val
# For each page, add panels...
col = 0
row = 0
for p in range(self.page_count):
self.add_page_color()
px = col * (self.page_width + paper_spacing)
py = row * (self.page_height + paper_spacing)
page = {'x': px, 'y': py}
self.add_panels_to_page(panels_json, image_ids, page)
# complete page and save
self.save_page(p)
col = col + 1
if col >= page_col_count:
col = 0
row = row + 1
# Add thumbnails and links page
self.add_info_page(panels_json)
# Saves the completed figure file
self.save_figure()
# PDF will get created in this group
if group_id is None:
group_id = self.conn.getEventContext().groupId
self.conn.SERVICE_OPTS.setOmeroGroup(group_id)
return self.create_file_annotation(image_ids)
def create_file_annotation(self, image_ids):