-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaserbeamsize.py
1388 lines (1110 loc) · 44.6 KB
/
laserbeamsize.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
# pylint: disable=invalid-name
# pylint: disable=too-many-locals
# pylint: disable=too-many-arguments
# pylint: disable=too-many-statements
# pylint: disable=too-many-lines
# pylint: disable=protected-access
# pylint: disable=consider-using-enumerate
# pylint: disable=consider-using-f-string
"""
A module for finding the beam size in an monochrome image.
Full documentation is available at <https://laserbeamsize.readthedocs.io>
Simple and fast calculation of beam sizes from a single monochrome image based
on the ISO 11146 method of variances. Some effort has been made to make
the algorithm less sensitive to background offset and noise.
Finding the center and diameters of a beam in a monochrome image is simple::
>>>> import imageio
>>>> import numpy as np
>>>> import laserbeamsize as lbs
>>>> beam_image = imageio.imread("t-hene.pgm")
>>>> x, y, dx, dy, phi = lbs.beam_size(beam_image)
>>>> print("The center of the beam ellipse is at (%.0f, %.0f)" % (x, y))
>>>> print("The ellipse diameter (closest to horizontal) is %.0f pixels" % dx)
>>>> print("The ellipse diameter (closest to vertical) is %.0f pixels" % dy)
>>>> print("The ellipse is rotated %.0f° ccw from the horizontal" % (phi * 180/3.1416))
A full graphic can be created by::
>>>> lbs.beam_size_plot(beam_image)
>>>> plt.show()
A mosaic of images might be created by::
>>>> # read images for each location
>>>> z = np.array([89,94,99,104,109,114,119,124,129,134,139], dtype=float) #[mm]
>>>> filenames = ["%d.pgm" % location for location in z]
>>>> images = [imageio.imread(filename) for filename in filenames]
>>>> lbs.beam_size_montage(images, z * 1e-3, pixel_size=3.75, crop=True)
>>>> plt.show()
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage
from PIL import Image, ImageDraw
__all__ = ('subtract_image',
'subtract_threshold',
'subtract_tilted_background',
'corner_background',
'corner_mask',
'perimeter_mask',
'corner_subtract',
'rotate_image',
'rotated_rect_mask',
'rotated_rect_arrays',
'axes_arrays',
'basic_beam_size',
'basic_beam_size_naive',
'beam_size',
'beam_ellipticity',
'beam_test_image',
'draw_beam_figure',
'ellipse_arrays',
'elliptical_mask',
'major_axis_arrays',
'minor_axis_arrays',
'beam_size_plot',
'beam_size_and_plot',
'beam_size_montage'
)
def rotate_points(x, y, x0, y0, phi):
"""
Rotate x and y around designated center (x0, y0).
Args:
x: x-values of point or array of points to be rotated
y: y-values of point or array of points to be rotated
x0: horizontal center of rotation
y0: vertical center of rotation
phi: angle to rotate (+ is ccw) in radians
Returns:
x, y: locations of rotated points
"""
xp = x - x0
yp = y - y0
s = np.sin(-phi)
c = np.cos(-phi)
xf = xp * c - yp * s
yf = xp * s + yp * c
xf += x0
yf += y0
return xf, yf
def values_along_line(image, x0, y0, x1, y1, N=100):
"""
Return x, y, z, and distance values between (x0, y0) and (x1, y1).
Args:
image: the image to work with
x0: x-value of start of line
y0: y-value of start of line
x1: x-value of end of line
y1: y-value of end of line
N: number of points in returned array
Returns:
x: index of horizontal pixel values along line
y: index of vertical pixel values along line
z: image values at each of the x, y positions
s: distance from start of minor axis to x, y position
"""
d = np.sqrt((x1 - x0)**2 + (y1 - y0)**2)
s = np.linspace(0, 1, N)
x = x0 + s * (x1 - x0)
y = y0 + s * (y1 - y0)
xx = x.astype(int)
yy = y.astype(int)
zz = image[yy, xx]
return xx, yy, zz, (s - 0.5) * d
def major_axis_arrays(image, xc, yc, dx, dy, phi, diameters=3):
"""
Return x, y, z, and distance values along semi-major axis.
Args:
image: the image to work with
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
diameters: number of diameters to use
Returns:
x: index of horizontal pixel values along line
y: index of vertical pixel values along line
z: image values at each of the x, y positions
s: distance from start of minor axis to x, y position
"""
v, h = image.shape
if dx > dy:
rx = diameters * dx / 2
left = max(xc - rx, 0)
right = min(xc + rx, h - 1)
x = np.array([left, right])
y = np.array([yc, yc])
xr, yr = rotate_points(x, y, xc, yc, phi)
else:
ry = diameters * dy / 2
top = max(yc - ry, 0)
bottom = min(yc + ry, v - 1)
x = np.array([xc, xc])
y = np.array([top, bottom])
xr, yr = rotate_points(x, y, xc, yc, phi)
return values_along_line(image, xr[0], yr[0], xr[1], yr[1])
def minor_axis_arrays(image, xc, yc, dx, dy, phi, diameters=3):
"""
Return x, y, z, and distance values along semi-minor axis.
Args:
image: the image to work with
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
diameters: number of diameters to use
Returns:
x: index of horizontal pixel values along line
y: index of vertical pixel values along line
z: image values at each of the x, y positions
s: distance from start of minor axis to x, y position
"""
v, h = image.shape
if dx <= dy:
rx = diameters * dx / 2
left = max(xc - rx, 0)
right = min(xc + rx, h - 1)
x = np.array([left, right])
y = np.array([yc, yc])
xr, yr = rotate_points(x, y, xc, yc, phi)
else:
ry = diameters * dy / 2
top = max(yc - ry, 0)
bottom = min(yc + ry, v - 1)
x = np.array([xc, xc])
y = np.array([top, bottom])
xr, yr = rotate_points(x, y, xc, yc, phi)
return values_along_line(image, xr[0], yr[0], xr[1], yr[1])
def subtract_image(original, background):
"""
Subtract background from original image.
This is only needed because when subtracting some pixels may become
negative. Unfortunately when the arrays have an unsigned data type
these negative values end up having very large pixel values.
This could be done as a simple loop with an if statement but the
implementation below is about 250X faster for 960 x 1280 arrays.
Args:
original: the image to work with
background: the image to be subtracted
Returns:
image: 2D array with background subtracted
"""
# convert to signed version
o = original.astype(int)
b = background.astype(int)
# subtract and zero negative entries
r = o - b
np.place(r, r < 0, 0)
# return array that matches original type
return r.astype(original.dtype.name)
def subtract_threshold(image, threshold):
"""
Return image with constant subtracted.
Subtract threshold from entire image. Negative values are set to zero.
Args:
image : the image to work with
threshold: value to subtract every pixel
Returns:
image: 2D array with threshold subtracted
"""
subtracted = np.array(image)
np.place(subtracted, subtracted < threshold, threshold)
subtracted -= threshold
return subtracted
def rotate_image(original, x0, y0, phi):
"""
Create image rotated about specified centerpoint.
The image is rotated about a centerpoint (x0, y0) and then
cropped to the original size such that the centerpoint remains
in the same location.
Args:
image: the image to work with
x: column
y: row
phi: angle [radians]
Returns:
image: rotated 2D array with same dimensions as original
"""
# center of original image
cy, cx = (np.array(original.shape) - 1) / 2.0
# rotate image using defaults mode='constant' and cval=0.0
rotated = scipy.ndimage.rotate(original, np.degrees(phi), order=1)
# center of rotated image, defaults mode='constant' and cval=0.0
ry, rx = (np.array(rotated.shape) - 1) / 2.0
# position of (x0, y0) in rotated image
new_x0, new_y0 = rotate_points(x0, y0, cx, cy, phi)
new_x0 += rx - cx
new_y0 += ry - cy
voff = int(new_y0 - y0)
hoff = int(new_x0 - x0)
# crop so center remains in same location as original
ov, oh = original.shape
rv, rh = rotated.shape
rv1 = max(voff, 0)
sv1 = max(-voff, 0)
vlen = min(voff + ov, rv) - rv1
rh1 = max(hoff, 0)
sh1 = max(-hoff, 0)
hlen = min(hoff + oh, rh) - rh1
# move values into zero-padded array
s = np.full_like(original, 0)
sv1_end = sv1 + vlen
sh1_end = sh1 + hlen
rv1_end = rv1 + vlen
rh1_end = rh1 + hlen
s[sv1:sv1_end, sh1:sh1_end] = rotated[rv1:rv1_end, rh1:rh1_end]
return s
def basic_beam_size(image):
"""
Determine the beam center, diameters, and tilt using ISO 11146 standard.
Find the center and sizes of an elliptical spot in an 2D array.
The function does nothing to eliminate background noise. It just finds the first
and second order moments and returns the beam parameters. Consequently
a beam spot in an image with a constant background will fail badly.
FWIW, this implementation is roughly 800X faster than one that finds
the moments using for loops.
Args:
image: 2D array of image with beam spot
Returns:
xc: horizontal center of beam
yc: vertical center of beam
dx: horizontal diameter of beam
dy: vertical diameter of beam
phi: angle that elliptical beam is rotated [radians]
"""
v, h = image.shape
# total of all pixels
p = np.sum(image, dtype=float) # float avoids integer overflow
# sometimes the image is all zeros, just return
if p == 0:
return int(h / 2), int(v / 2), 0, 0, 0
# find the centroid
hh = np.arange(h, dtype=float) # float avoids integer overflow
vv = np.arange(v, dtype=float) # ditto
xc = np.sum(np.dot(image, hh)) / p
yc = np.sum(np.dot(image.T, vv)) / p
# find the variances
hs = hh - xc
vs = vv - yc
xx = np.sum(np.dot(image, hs**2)) / p
xy = np.dot(np.dot(image.T, vs), hs) / p
yy = np.sum(np.dot(image.T, vs**2)) / p
# Ensure that the case xx==yy is handled correctly
if xx == yy:
disc = np.abs(2 * xy)
phi = np.sign(xy) * np.pi / 4
else:
diff = xx - yy
disc = np.sign(diff) * np.sqrt(diff**2 + 4 * xy**2)
phi = 0.5 * np.arctan(2 * xy / diff)
# finally, the major and minor diameters
dx = np.sqrt(8 * (xx + yy + disc))
dy = np.sqrt(8 * (xx + yy - disc))
# phi is negative because image is inverted
phi *= -1
return xc, yc, dx, dy, phi
def elliptical_mask(image, xc, yc, dx, dy, phi):
"""
Create a boolean mask for a rotated elliptical disk.
The returned mask is the same size as `image`.
Args:
image: 2D array
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
Returns:
masked_image: 2D array with True values inside ellipse
"""
v, h = image.shape
y, x = np.ogrid[:v, :h]
sinphi = np.sin(phi)
cosphi = np.cos(phi)
rx = dx / 2
ry = dy / 2
xx = x - xc
yy = y - yc
r2 = (xx * cosphi - yy * sinphi)**2 / rx**2 + (xx * sinphi + yy * cosphi)**2 / ry**2
the_mask = r2 <= 1
return the_mask
def corner_mask(image, corner_fraction=0.035):
"""
Create boolean mask for image with corners marked as True.
Each of the four corners is a fixed percentage of the entire image.
ISO 11146-3 recommends values from 2-5% for `corner_fraction`
the default is 0.035=3.5% of the iamge.
Args:
image : the image to work with
corner_fraction: the fractional size of corner rectangles
Returns:
masked_image: 2D array with True values in four corners
"""
v, h = image.shape
n = int(v * corner_fraction)
m = int(h * corner_fraction)
the_mask = np.full_like(image, False, dtype=bool)
the_mask[:n, :m] = True
the_mask[:n, -m:] = True
the_mask[-n:, :m] = True
the_mask[-n:, -m:] = True
return the_mask
def perimeter_mask(image, corner_fraction=0.035):
"""
Create boolean mask for image with a perimeter marked as True.
The perimeter is the same width as the corners created by corner_mask
which is a fixed percentage (default 3.5%) of the entire image.
Args:
image : the image to work with
corner_fraction: determines the width of the perimeter
Returns:
masked_image: 2D array with True values around rect perimeter
"""
v, h = image.shape
n = int(v * corner_fraction)
m = int(h * corner_fraction)
the_mask = np.full_like(image, False, dtype=np.bool)
the_mask[:, :m] = True
the_mask[:, -m:] = True
the_mask[:n, :] = True
the_mask[-n:, :] = True
return the_mask
def corner_background(image, corner_fraction=0.035):
"""
Return the mean and stdev of background in corners of image.
The mean and standard deviation are estimated using the pixels from
the rectangles in the four corners. The default size of these rectangles
is 0.035 or 3.5% of the full image size.
ISO 11146-3 recommends values from 2-5% for `corner_fraction`.
Args:
image : the image to work with
corner_fraction: the fractional size of corner rectangles
Returns:
corner_mean: average pixel value in corners
"""
if corner_fraction == 0:
return 0, 0
mask = corner_mask(image, corner_fraction)
img = np.ma.masked_array(image, ~mask)
mean = np.mean(img)
stdev = np.std(img)
return mean, stdev
def corner_subtract(image, corner_fraction=0.035, nT=3):
"""
Return image with background subtracted.
The mean and standard deviation are estimated using the pixels from
the rectangles in the four corners. The default size of these rectangles
is 0.035 or 3.5% of the full image size.
The new image will have a constant (`mean + nT * stdev`) subtracted.
ISO 11146-3 recommends values from 2-5% for `corner_fraction`.
ISO 11146-3 recommends from 2-4 for `nT`.
Some care has been taken to ensure that any values in the image that are
less than the background are set to zero.
Args:
image : the image to work with
corner_fraction: the fractional size of corner rectangles
nT: how many standard deviations to subtract
Returns:
image: 2D array with background subtracted
"""
back, sigma = corner_background(image, corner_fraction)
offset = int(back + nT * sigma)
return subtract_threshold(image, offset)
def subtract_tilted_background(image, corner_fraction=0.035):
"""
Return image with tilted planar background subtracted.
Take all the points around the perimeter of an image and fit these
to a tilted plane to determine the background to subtract. Details of
the linear algebra are at https://math.stackexchange.com/questions/99299
Since the sample contains noise, it is important not to remove
this noise at this stage and therefore we offset the plane so
that one standard deviation of noise remains.
Args:
image : the image to work with
corner_fraction: the fractional size of corner rectangles
Returns:
image: 2D array with tilted planar background subtracted
"""
v, h = image.shape
xx, yy = np.meshgrid(range(h), range(v))
mask = perimeter_mask(image, corner_fraction=corner_fraction)
perimeter_values = image[mask]
# coords is (y_value, x_value, 1) for each point in perimeter_values
coords = np.stack((yy[mask], xx[mask], np.ones(np.size(perimeter_values))), 1)
# fit a plane to all corner points
b = np.array(perimeter_values).T
A = np.array(coords)
a, b, c = np.linalg.inv(A.T @ A) @ A.T @ b
# calculate the fitted background plane
z = a * yy + b * xx + c
# find the standard deviation of the noise in the perimeter
# and subtract this value from the plane
# since we don't want to lose the image noise just yet
z -= np.std(perimeter_values)
# finally, subtract the plane from the original image
return subtract_image(image, z)
def rotated_rect_mask_slow(image, xc, yc, dx, dy, phi, mask_diameters=3):
"""
Create ISO 11146 rectangular mask for specified beam.
ISO 11146-2 §7.2 states that integration should be carried out over
"a rectangular integration area which is centred to the beam centroid,
defined by the spatial first order moments, orientated parallel to
the principal axes of the power density distribution, and sized
three times the beam widths".
This routine creates a mask with `true` values for each pixel in
the image that should be part of the integration.
The rectangular mask is `mask_diameters' times the pixel diameters
of the ellipse.
The rectangular mask is rotated about (xc, yc) so that it is aligned
with the elliptical spot.
Args:
image: the image to work with
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
Returns:
masked_image: 2D array with True values inside rectangle
"""
raw_mask = np.full_like(image, 0, dtype=float)
v, h = image.shape
rx = mask_diameters * dx / 2
ry = mask_diameters * dy / 2
vlo = max(0, int(yc - ry))
vhi = min(v, int(yc + ry))
hlo = max(0, int(xc - rx))
hhi = min(h, int(xc + rx))
raw_mask[vlo:vhi, hlo:hhi] = 1
rot_mask = rotate_image(raw_mask, xc, yc, phi)
return rot_mask
def rotated_rect_mask(image, xc, yc, dx, dy, phi, mask_diameters=3):
"""
Create ISO 11146 rectangular mask for specified beam.
ISO 11146-2 §7.2 states that integration should be carried out over
"a rectangular integration area which is centred to the beam centroid,
defined by the spatial first order moments, orientated parallel to
the principal axes of the power density distribution, and sized
three times the beam widths".
This routine creates a mask with `true` values for each pixel in
the image that should be part of the integration.
The rectangular mask is `mask_diameters` times the pixel diameters
of the ellipse.
The rectangular mask is rotated about (xc, yc) and then drawn using PIL
Args:
image: the image to work with
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
mask_diameters: number of diameters to include
Returns:
masked_image: 2D array with True values inside rectangle
"""
v, h = image.shape
rx = mask_diameters * dx / 2
ry = mask_diameters * dy / 2
s = np.sin(-phi)
c = np.cos(-phi)
xx, xy = rx * c, rx * s
yx, yy = - ry * s, ry * c
x1, y1 = xc + xx + yx, yc + xy + yy
x2, y2 = xc + xx - yx, yc + xy - yy
x3, y3 = xc - xx - yx, yc - xy - yy
x4, y4 = xc - xx + yx, yc - xy + yy
g = Image.new('L', (h, v), 0)
ImageDraw.Draw(g).polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)], outline=1, fill=1)
mask = np.array(g)
return mask
def rotated_rect_arrays(xc, yc, dx, dy, phi, mask_diameters=3):
"""
Return x, y arrays to draw a rotated rectangle.
Args:
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
Returns:
x, y : two arrays for points on corners of rotated rectangle
"""
rx = mask_diameters * dx / 2
ry = mask_diameters * dy / 2
# rectangle with center at (xc, yc)
x = np.array([-rx, -rx, +rx, +rx, -rx]) + xc
y = np.array([-ry, +ry, +ry, -ry, -ry]) + yc
x_rot, y_rot = rotate_points(x, y, xc, yc, phi)
return np.array([x_rot, y_rot])
def axes_arrays(xc, yc, dx, dy, phi, mask_diameters=3):
"""
Return x, y arrays needed to draw semi-axes of ellipse.
Args:
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
Returns:
x, y arrays needed to draw semi-axes of ellipse
"""
rx = mask_diameters * dx / 2
ry = mask_diameters * dy / 2
# major and minor ellipse axes with center at (xc, yc)
x = np.array([-rx, rx, 0, 0, 0]) + xc
y = np.array([0, 0, 0, -ry, ry]) + yc
x_rot, y_rot = rotate_points(x, y, xc, yc, phi)
return np.array([x_rot, y_rot])
def beam_size(image, mask_diameters=3, corner_fraction=0.035, nT=3,
max_iter=25, phi=None):
"""
Determine beam parameters in an image with noise.
The function first estimates the elliptical spot by excluding all points
that are less than the average value found in the corners of the image.
These beam parameters are then used to determine a rectangle that surrounds
the elliptical spot. The rectangle size is `mask_diameters` times the spot
diameters. This is the integration region used for estimate a new beam
spot.
This process is repeated until two successive spot sizes match again as
outlined in ISO 11146
`corner_fraction` determines the size of the corners. ISO 11146-3
recommends values from 2-5%. The default value of 3.5% works pretty well.
`mask_diameters` is the size of the rectangular mask in diameters
of the ellipse. ISO 11146 states that `mask_diameters` should be 3.
This default value works fine.
`nT` accounts for noise in the background. The background is estimated
using the values in the cornes of the image as `mean+nT * stdev`. ISO 11146
states that `2<nT<4`. The default value works fine.
`max_iter` is the maximum number of iterations done before giving up.
Args:
image: 2D array of image of beam
mask_diameters: the size of the integration rectangle in diameters
corner_fraction: the fractional size of the corners
nT: the multiple of background noise to remove
max_iter: maximum number of iterations.
phi: (optional) fixed tilt of ellipse in radians
Returns:
xc: horizontal center of beam
yc: vertical center of beam
dx: horizontal diameter of beam
dy: vertical diameter of beam
phi: angle that elliptical beam is rotated [radians]
"""
if len(image.shape) > 2:
raise Exception('Color images are not supported. Convert to gray/monochrome.')
# remove any offset
zero_background_image = corner_subtract(image, corner_fraction, nT)
# zero_background_image = np.copy(image)
xc, yc, dx, dy, phi_ = basic_beam_size(zero_background_image)
for _iteration in range(1, max_iter):
phi_ = phi or phi_
xc2, yc2, dx2, dy2 = xc, yc, dx, dy
mask = rotated_rect_mask(image, xc, yc, dx, dy, phi_, mask_diameters)
masked_image = np.copy(zero_background_image)
# zero values outside mask
# when mask is rotated some pixels may not be exactly 1
masked_image[mask < 0.5] = 0
xc, yc, dx, dy, phi_ = basic_beam_size(masked_image)
if abs(xc - xc2) < 1 and abs(yc - yc2) < 1 and abs(dx - dx2) < 1 and abs(dy - dy2) < 1:
break
phi_ = phi or phi_
return xc, yc, dx, dy, phi_
def beam_ellipticity(dx, dy):
"""
Calculate the ellipticity of the beam.
The ISO 11146 standard defines ellipticity as the "ratio between the
minimum and maximum beam widths". These widths (diameters) returned
by `beam_size()` can be used to make this calculation.
When `ellipticity > 0.87`, then the beam profile may be considered to have
circular symmetry. The equivalent beam diameter is the root mean square
of the beam diameters.
Args:
dx: x diameter of the beam spot
dy: y diameter of the beam spot
Returns:
ellipticity: varies from 0 (line) to 1 (round)
d_circular: equivalent diameter of a circular beam
"""
if dy < dx:
ellipticity = dy / dx
elif dx < dy:
ellipticity = dx / dy
else:
ellipticity = 1
d_circular = np.sqrt((dx**2 + dy**2) / 2)
return ellipticity, d_circular
def beam_test_image(h, v, xc, yc, dx, dy, phi, noise=0, max_value=255):
"""
Create a test image.
Create a v x h image with an elliptical beam with specified center and
beam dimensions. By default the values in the image will range from 0 to
255. The default image will have no background and no noise.
Args:
h: number of columns in 2D test image
v: number of rows in 2D test image
xc: horizontal center of beam
yc: vertical center of beam
dx: ellipse diameter for axis closest to horizontal
dy: ellipse diameter for axis closest to vertical
phi: angle that elliptical beam is rotated [radians]
noise: normally distributed pixel noise to add to image
max_value: all values in image fall between 0 and `max_value`
Returns:
image: integer 2D array of a Gaussian elliptical spot
"""
rx = dx / 2
ry = dy / 2
image0 = np.zeros([v, h])
y, x = np.ogrid[:v, :h]
scale = max_value - 3 * noise
image0 = scale * np.exp(-2 * (x - xc)**2 / rx**2 - 2 * (y - yc)**2 / ry**2)
image1 = rotate_image(image0, xc, yc, phi)
if noise > 0:
image1 += np.random.poisson(noise, size=(v, h))
# after adding noise, the signal may exceed the range 0 to max_value
np.place(image1, image1 > max_value, max_value)
np.place(image1, image1 < 0, 0)
if max_value < 256:
return image1.astype(np.uint8)
if max_value < 65536:
return image1.astype(np.uint16)
return image1
def ellipse_arrays(xc, yc, dx, dy, phi, npoints=200):
"""
Return x, y arrays to draw a rotated ellipse.
Args:
xc: horizontal center of beam
yc: vertical center of beam
dx: horizontal diameter of beam
dy: vertical diameter of beam
phi: angle that elliptical beam is rotated [radians]
Returns:
x, y : two arrays of points on the ellipse
"""
t = np.linspace(0, 2 * np.pi, npoints)
a = dx / 2 * np.cos(t)
b = dy / 2 * np.sin(t)
xp = xc + a * np.cos(phi) - b * np.sin(phi)
yp = yc - a * np.sin(phi) - b * np.cos(phi)
return np.array([xp, yp])
def basic_beam_size_naive(image):
"""
Slow but simple implementation of ISO 11146 beam standard.
This is identical to `basic_beam_size()` and is the obvious way to
program the calculation of the necessary moments. It is slow.
Args:
image: 2D array of image with beam spot in it
Returns:
xc: horizontal center of beam
yc: vertical center of beam
dx: horizontal diameter of beam
dy: vertical diameter of beam
phi: angle that elliptical beam is rotated [radians]
"""
v, h = image.shape
# locate the center just like ndimage.center_of_mass(image)
p = 0.0
xc = 0.0
yc = 0.0
for i in range(v):
for j in range(h):
p += image[i, j]
xc += image[i, j] * j
yc += image[i, j] * i
xc = int(xc / p)
yc = int(yc / p)
# calculate variances
xx = 0.0
yy = 0.0
xy = 0.0
for i in range(v):
for j in range(h):
xx += image[i, j] * (j - xc)**2
xy += image[i, j] * (j - xc) * (i - yc)
yy += image[i, j] * (i - yc)**2
xx /= p
xy /= p
yy /= p
# compute major and minor axes as well as rotation angle
dx = 2 * np.sqrt(2) * np.sqrt(xx + yy + np.sign(xx - yy) * np.sqrt((xx - yy)**2 + 4 * xy**2))
dy = 2 * np.sqrt(2) * np.sqrt(xx + yy - np.sign(xx - yy) * np.sqrt((xx - yy)**2 + 4 * xy**2))
phi = 2 * np.arctan2(2 * xy, xx - yy)
return xc, yc, dx, dy, phi
def draw_beam_figure():
"""Draw a simple astigmatic beam ellipse with labels."""
theta = np.radians(30)
xc = 0
yc = 0
dx = 50
dy = 25
plt.subplots(1, 1, figsize=(6, 6))
# If the aspect ratio is not `equal` then the major and minor radii
# do not appear to be orthogonal to each other!
plt.axes().set_aspect('equal')
xp, yp = ellipse_arrays(xc, yc, dx, dy, theta)
plt.plot(xp, yp, 'k', lw=2)
xp, yp = rotated_rect_arrays(xc, yc, dx, dy, theta)
plt.plot(xp, yp, ':b', lw=2)
sint = np.sin(theta) / 2
cost = np.cos(theta) / 2
plt.plot([xc - dx * cost, xc + dx * cost], [yc + dx * sint, yc - dx * sint], ':b')
plt.plot([xc + dy * sint, xc - dy * sint], [yc + dy * cost, yc - dy * cost], ':r')
# draw axes
plt.annotate("x'", xy=(-25, 0), xytext=(25, 0),
arrowprops=dict(arrowstyle="<-"), va='center', fontsize=16)
plt.annotate("y'", xy=(0, 25), xytext=(0, -25),
arrowprops=dict(arrowstyle="<-"), ha='center', fontsize=16)
plt.annotate(r'$\phi$', xy=(13, -2.5), fontsize=16)
plt.annotate('', xy=(15.5, 0), xytext=(
14, -8.0), arrowprops=dict(arrowstyle="<-", connectionstyle="arc3, rad=-0.2"))
plt.annotate(r'$d_x$', xy=(-17, 7), color='blue', fontsize=16)
plt.annotate(r'$d_y$', xy=(-4, -8), color='red', fontsize=16)
plt.xlim(-30, 30)
plt.ylim(30, -30) # inverted to match image coordinates!
plt.axis('off')
def crop_image_to_rect(image, xc, yc, xmin, xmax, ymin, ymax):
"""
Return image cropped to specified rectangle.
Args:
image: image of beam
xc: horizontal center of beam
yc: vertical center of beam
xmin: left edge (pixels)
xmax: right edge (pixels)
ymin: top edge (pixels)
ymax: bottom edge (pixels)
Returns:
cropped_image: cropped image
new_xc, new_yc: new beam center (pixels)
"""
v, h = image.shape
xmin = max(0, int(xmin))
xmax = min(h, int(xmax))
ymin = max(0, int(ymin))
ymax = min(v, int(ymax))
new_xc = xc - xmin
new_yc = yc - ymin
return image[ymin:ymax, xmin:xmax], new_xc, new_yc
def crop_image_to_integration_rect(image, xc, yc, dx, dy, phi):
"""
Return image cropped to integration rectangle.
Since the image is being cropped, the center of the beam will move.