forked from GalSim-developers/GalSim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.py
2040 lines (1713 loc) · 81.9 KB
/
image.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
# Copyright (c) 2012-2023 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
__all__ = [ 'Image', '_Image',
'ImageS', 'ImageI', 'ImageF', 'ImageD',
'ImageCF', 'ImageCD', 'ImageUS', 'ImageUI', ]
import numpy as np
from . import _galsim
from .position import PositionI, _PositionD, parse_pos_args
from .bounds import BoundsI, BoundsD, _BoundsI
from ._utilities import lazy_property
from .errors import GalSimError, GalSimBoundsError, GalSimValueError, GalSimImmutableError
from .errors import GalSimUndefinedBoundsError, GalSimIncompatibleValuesError, convert_cpp_errors
# Sometimes (on 32-bit systems) there are two numpy.int32 types. This can lead to some confusion
# when doing arithmetic with images. So just make sure both of them point to ImageViewI in the
# _cpp_type dict. One of them is what you get when you just write numpy.int32. The other is
# what numpy decides an int16 + int32 is.
# For more information regarding this rather unexpected behaviour for numpy.int32 types, see
# the following (closed, marked "wontfix") ticket on the numpy issue tracker:
# http://projects.scipy.org/numpy/ticket/1246
alt_int32 = (np.array([0], dtype=np.int16) + np.array([0], dtype=np.int32)).dtype.type
class Image:
"""A class for storing image data along with the pixel scale or WCS information
The Image class encapsulates all the relevant information about an image including a NumPy array
for the pixel values, a bounding box, and some kind of WCS that converts between pixel
coordinates and world coordinates. The NumPy array may be constructed by the Image class
itself, or an existing array can be provided by the user.
This class creates shallow copies unless a deep copy is explicitly requested using the `copy`
method. The main reason for this is that it allows users to work directly with and modify
subimages of larger images (for example, to successively draw many galaxies into one large
image). For other implications of this convention, see the description of initialization
instructions below.
In most applications with images, we will use (x,y) to refer to the coordinates. We adopt
the same meaning for these coordinates as most astronomy applications do: ds9, SAOImage,
SExtractor, etc. all treat x as the column number and y as the row number. However, this
is different from the default convention used by numpy. In numpy, the access is by
[row_num,col_num], which means this is really [y,x] in terms of the normal x,y values.
Users are typically insulated from this concern by the Image API, but if you access the
numpy array directly via the ``array`` attribute, you will need to be careful about this
difference.
There are 6 data types that the Image can use for the data values. These are ``numpy.uint16``,
``numpy.uint32``, ``numpy.int16``, ``numpy.int32``, ``numpy.float32``, and ``numpy.float64``.
If you are constructing a new Image from scratch, the default is ``numpy.float32``, but you
can specify one of the other data types.
There are several ways to construct an Image:
(Optional arguments are shown with their default values after the = sign.)
``Image(ncol, nrow, dtype=numpy.float32, init_value=0, xmin=1, ymin=1, ...)``
This constructs a new image, allocating memory for the pixel values according to
the number of columns and rows. You can specify the data type as ``dtype`` if you
want. The default is ``numpy.float32`` if you don't specify it. You can also
optionally provide an initial value for the pixels, which defaults to 0.
The optional ``xmin,ymin`` allow you to specify the location of the lower-left
pixel, which defaults to (1,1). Reminder, with our convention for x,y coordinates
described above, ncol is the number of pixels in the x direction, and nrow is the
number of pixels in the y direction.
``Image(bounds, dtype=numpy.float32, init_value=0, ...)``
This constructs a new image, allocating memory for the pixel values according to a
given `Bounds` object. Particularly, the bounds should be a `BoundsI` instance.
You can specify the data type as ``dtype`` if you want. The default is
``numpy.float32`` if you don't specify it. You can also optionally provide an
initial value for the pixels, which defaults to 0.
``Image(array, xmin=1, ymin=1, make_const=False, copy=False ...)``
This views an existing NumPy array as an Image, where updates to either the image
or the original array will affect the other one. The data type is taken from
``array.dtype``, which must be one of the allowed types listed above. You can also
optionally set the origin ``xmin, ymin`` if you want it to be something other than
(1,1).
You can also optionally force the Image to be read-only with ``make_const=True``,
though if the original NumPy array is modified then the contents of ``Image.array``
will change.
If you want to make a copy of the input array, rather than just view the existing
array, you can force a copy with::
>>> image = galsim.Image(array, copy=True)
``Image(image, dtype=image.dtype, copy=True)``
This creates a copy of an Image, possibly changing the type. e.g.::
>>> image_float = galsim.Image(64, 64) # default dtype=numpy.float32
>>> image_double = galsim.Image(image_float, dtype=numpy.float64)
You can see a list of valid values for dtype in ``galsim.Image.valid_dtypes``.
Without the ``dtype`` argument, this is equivalent to ``image.copy()``, which makes
a deep copy. If you want a copy that shares data with the original, see
the `view` method.
If you only want to enforce the image to have a given type and not make a copy
if the array is already the correct type, you can use, e.g.::
>>> image_double = galsim.Image(image, dtype=numpy.float64, copy=False)
You can specify the ``ncol``, ``nrow``, ``bounds``, ``array``, or ``image`` parameters by
keyword argument if you want, or you can pass them as simple arg as shown aboves, and the
constructor will figure out what they are.
The other keyword arguments (shown as ... above) relate to the conversion between sky
coordinates, which is how all the GalSim objects are defined, and the pixel coordinates.
There are three options for this:
scale
You can optionally specify a pixel scale to use. This would normally have
units arcsec/pixel, but it doesn't have to be arcsec. If you want to
use different units for the physical scale of your galsim objects, then
the same unit would be used here.
wcs
A WCS object that provides a non-trivial mapping between sky units and
pixel units. The ``scale`` parameter is equivalent to
``wcs=PixelScale(scale)``. But there are a number of more complicated options.
See the WCS class for more details.
None
If you do not provide either of the above, then the conversion is undefined.
When drawing onto such an image, a suitable pixel scale will be automatically
set according to the Nyquist scale of the object being drawn.
After construction, you can set or change the scale or wcs with::
>>> image.scale = new_scale
>>> image.wcs = new_wcs
Note that ``image.scale`` will only work if the WCS is a `PixelScale`. Once you set the
wcs to be something non-trivial, then you must interact with it via the ``wcs`` attribute.
The ``image.scale`` syntax will raise an exception.
There are also two read-only attributes::
>>> image.bounds
>>> image.array
The ``array`` attribute is a NumPy array of the Image's pixels. The individual elements in the
array attribute are accessed as ``image.array[y,x]``, matching the standard NumPy convention,
while the Image class's own accessor uses either ``(x,y)`` or ``[x,y]``.
That is, the following are equivalent::
>>> ixy = image(x,y)
>>> ixy = image[x,y]
>>> ixy = image.array[y,x]
>>> ixy = image.getValue(x,y)
Similarly, for setting individual pixel values, the following are equivalent::
>>> image[x,y] = new_ixy
>>> image.array[y,x] = new_ixy
>>> image.setValue(x,y,new_ixy)
"""
_cpp_type = { np.uint16 : _galsim.ImageViewUS,
np.uint32 : _galsim.ImageViewUI,
np.int16 : _galsim.ImageViewS,
np.int32 : _galsim.ImageViewI,
np.float32 : _galsim.ImageViewF,
np.float64 : _galsim.ImageViewD,
np.complex64 : _galsim.ImageViewCF,
np.complex128 : _galsim.ImageViewCD,
}
_cpp_valid_dtypes = list(_cpp_type.keys())
_alias_dtypes = {
int : np.int32, # So that user gets what they would expect
float : np.float64, # if using dtype=int or float or complex
complex : np.complex128,
np.int64 : np.int32, # Not equivalent, but will convert
}
# Note: Numpy uses int64 for int on 64 bit machines. We don't implement int64 at all,
# so we cannot quite match up to the numpy convention for dtype=int. e.g. via
# int : numpy.zeros(1,dtype=int).dtype.type
# If this becomes too confusing, we might need to add an ImageL class that uses int64.
# Hard to imagine a use case where this would be required though...
# This one is in the public API. (No leading underscore.)
valid_dtypes = _cpp_valid_dtypes + list(_alias_dtypes.keys())
def __init__(self, *args, **kwargs):
# Parse the args, kwargs
ncol = None
nrow = None
bounds = None
array = None
image = None
if len(args) > 2:
raise TypeError("Error, too many unnamed arguments to Image constructor")
elif len(args) == 2:
ncol = args[0]
nrow = args[1]
xmin = kwargs.pop('xmin',1)
ymin = kwargs.pop('ymin',1)
elif len(args) == 1:
if isinstance(args[0], np.ndarray):
array = args[0]
array, xmin, ymin = self._get_xmin_ymin(array, kwargs)
make_const = kwargs.pop('make_const',False)
elif isinstance(args[0], BoundsI):
bounds = args[0]
elif isinstance(args[0], (list, tuple)):
array = np.array(args[0])
array, xmin, ymin = self._get_xmin_ymin(array, kwargs)
make_const = kwargs.pop('make_const',False)
elif isinstance(args[0], Image):
image = args[0]
else:
raise TypeError("Unable to parse %s as an array, bounds, or image."%args[0])
else:
if 'array' in kwargs:
array = kwargs.pop('array')
array, xmin, ymin = self._get_xmin_ymin(array, kwargs)
make_const = kwargs.pop('make_const',False)
elif 'bounds' in kwargs:
bounds = kwargs.pop('bounds')
elif 'image' in kwargs:
image = kwargs.pop('image')
else:
ncol = kwargs.pop('ncol',None)
nrow = kwargs.pop('nrow',None)
xmin = kwargs.pop('xmin',1)
ymin = kwargs.pop('ymin',1)
# Pop off the other valid kwargs:
dtype = kwargs.pop('dtype', None)
init_value = kwargs.pop('init_value', None)
scale = kwargs.pop('scale', None)
wcs = kwargs.pop('wcs', None)
copy = kwargs.pop('copy', None)
# Check that we got them all
if kwargs:
raise TypeError("Image constructor got unexpected keyword arguments: %s",kwargs)
# Figure out what dtype we want:
dtype = Image._alias_dtypes.get(dtype,dtype)
if dtype is not None and dtype not in Image.valid_dtypes:
raise GalSimValueError("Invlid dtype.", dtype, Image.valid_dtypes)
if array is not None:
if copy is None: copy = False
if dtype is None:
dtype = array.dtype.type
if dtype in Image._alias_dtypes:
dtype = Image._alias_dtypes[dtype]
array = array.astype(dtype, copy=copy)
elif dtype not in Image._cpp_valid_dtypes:
raise GalSimValueError("Invalid dtype of provided array.", array.dtype,
Image._cpp_valid_dtypes)
elif copy:
array = np.array(array)
else:
array = array.astype(dtype, copy=copy)
# Be careful here: we have to watch out for little-endian / big-endian issues.
# The path of least resistance is to check whether the array.dtype is equal to the
# native one (using the dtype.isnative flag), and if not, make a new array that has a
# type equal to the same one but with the appropriate endian-ness.
if not array.dtype.isnative:
array = array.astype(array.dtype.newbyteorder('='))
self._dtype = array.dtype.type
elif dtype is not None:
self._dtype = dtype
else:
self._dtype = np.float32
# Construct the image attribute
if (ncol is not None or nrow is not None):
if ncol is None or nrow is None:
raise GalSimIncompatibleValuesError(
"Both nrow and ncol must be provided", ncol=ncol, nrow=nrow)
if ncol != int(ncol) or nrow != int(nrow):
raise TypeError("nrow, ncol must be integers")
ncol = int(ncol)
nrow = int(nrow)
self._array = self._make_empty(shape=(nrow,ncol), dtype=self._dtype)
self._bounds = BoundsI(xmin, xmin+ncol-1, ymin, ymin+nrow-1)
if init_value:
self.fill(init_value)
elif bounds is not None:
if not isinstance(bounds, BoundsI):
raise TypeError("bounds must be a galsim.BoundsI instance")
self._array = self._make_empty(bounds.numpyShape(), dtype=self._dtype)
self._bounds = bounds
if init_value:
self.fill(init_value)
elif array is not None:
self._array = array.view()
nrow,ncol = array.shape
self._bounds = BoundsI(xmin, xmin+ncol-1, ymin, ymin+nrow-1)
if make_const or not array.flags.writeable:
self._array.flags.writeable = False
if init_value is not None:
raise GalSimIncompatibleValuesError(
"Cannot specify init_value with array", init_value=init_value, array=array)
elif image is not None:
if not isinstance(image, Image):
raise TypeError("image must be an Image")
if init_value is not None:
raise GalSimIncompatibleValuesError(
"Cannot specify init_value with image", init_value=init_value, image=image)
if wcs is None and scale is None:
wcs = image.wcs
self._bounds = image.bounds
if dtype is None:
self._dtype = image.dtype
else:
# Allow dtype to force a retyping of the provided image
# e.g. im = ImageF(...)
# im2 = ImageD(im)
self._dtype = dtype
if copy is False:
self._array = image.array.astype(self._dtype, copy=False)
else:
self._array = self._make_empty(shape=image.bounds.numpyShape(), dtype=self._dtype)
self._array[:,:] = image.array[:,:]
else:
self._array = np.zeros(shape=(1,1), dtype=self._dtype)
self._bounds = BoundsI()
if init_value is not None:
raise GalSimIncompatibleValuesError(
"Cannot specify init_value without setting an initial size",
init_value=init_value, ncol=ncol, nrow=nrow, bounds=bounds)
# Construct the wcs attribute
if scale is not None:
if wcs is not None:
raise GalSimIncompatibleValuesError(
"Cannot provide both scale and wcs to Image constructor", wcs=wcs, scale=scale)
self.wcs = PixelScale(float(scale))
else:
if wcs is not None and not isinstance(wcs, BaseWCS):
raise TypeError("wcs parameters must be a galsim.BaseWCS instance")
self.wcs = wcs
@staticmethod
def _get_xmin_ymin(array, kwargs):
"""A helper function for parsing xmin, ymin, bounds options with a given array
"""
if not isinstance(array, np.ndarray):
raise TypeError("array must be a numpy.ndarray instance")
xmin = kwargs.pop('xmin',1)
ymin = kwargs.pop('ymin',1)
if 'bounds' in kwargs:
b = kwargs.pop('bounds')
if not isinstance(b, BoundsI):
raise TypeError("bounds must be a galsim.BoundsI instance")
if b.xmax-b.xmin+1 != array.shape[1]:
raise GalSimIncompatibleValuesError(
"Shape of array is inconsistent with provided bounds", array=array, bounds=b)
if b.ymax-b.ymin+1 != array.shape[0]:
raise GalSimIncompatibleValuesError(
"Shape of array is inconsistent with provided bounds", array=array, bounds=b)
if b.isDefined():
xmin = b.xmin
ymin = b.ymin
else:
# Indication that array is formally undefined, even though provided.
if 'dtype' not in kwargs:
kwargs['dtype'] = array.dtype.type
array = None
xmin = None
ymin = None
elif array.shape[1] == 0:
# Another way to indicate that we don't have a defined image.
if 'dtype' not in kwargs:
kwargs['dtype'] = array.dtype.type
array = None
xmin = None
ymin = None
return array, xmin, ymin
def __repr__(self):
s = 'galsim.Image(bounds=%r' % self.bounds
if self.bounds.isDefined():
s += ', array=\n%r' % self.array
s += ', wcs=%r' % self.wcs
if self.isconst:
s += ', make_const=True'
s += ')'
return s
def __str__(self):
# Get the type name without the <type '...'> part.
t = str(self.dtype).split("'")[1]
if self.wcs is not None and self.wcs._isPixelScale:
return 'galsim.Image(bounds=%s, scale=%s, dtype=%s)'%(self.bounds, self.scale, t)
else:
return 'galsim.Image(bounds=%s, wcs=%s, dtype=%s)'%(self.bounds, self.wcs, t)
# Pickling almost works out of the box, but numpy arrays lose their non-writeable flag
# when pickled, so make sure to set it to preserve const Images.
def __getstate__(self):
d = self.__dict__.copy()
d.pop('_image',None)
return d, self.isconst
def __setstate__(self, args):
d, isconst = args
self.__dict__ = d
if isconst:
self._array.flags.writeable = False
# Read-only attributes:
@property
def dtype(self):
"""The dtype of the underlying numpy array.
"""
return self._dtype
@property
def bounds(self):
"""The bounds of the `Image`.
"""
return self._bounds
@property
def array(self):
"""The underlying numpy array.
"""
return self._array
@property
def nrow(self):
"""The number of rows in the image
"""
return self._array.shape[0]
@property
def ncol(self):
"""The number of columns in the image
"""
return self._array.shape[1]
@property
def isconst(self):
"""Whether the `Image` is constant. I.e. modifying its values is an error.
"""
return self._array.flags.writeable == False
@property
def iscomplex(self):
"""Whether the `Image` values are complex.
"""
return self._array.dtype.kind == 'c'
@property
def isinteger(self):
"""Whether the `Image` values are integral.
"""
return self._array.dtype.kind in ('i','u')
@property
def iscontiguous(self):
"""Indicates whether each row of the image is contiguous in memory.
Note: it is ok for the end of one row to not be contiguous with the start of the
next row. This just checks that each individual row has a stride of 1.
"""
return self._array.strides[1]//self._array.itemsize == 1
@lazy_property
def _image(self):
cls = self._cpp_type[self.dtype]
_data = self._array.__array_interface__['data'][0]
return cls(_data,
self._array.strides[1]//self._array.itemsize,
self._array.strides[0]//self._array.itemsize,
self._bounds._b)
# Allow scale to work as a PixelScale wcs.
@property
def scale(self):
"""The pixel scale of the `Image`. Only valid if the wcs is a `PixelScale`.
If the WCS is either not set (i.e. it is ``None``) or it is a `PixelScale`, then
it is permissible to change the scale with::
>>> image.scale = new_pixel_scale
"""
try:
return self.wcs.scale
except Exception:
if self.wcs:
raise GalSimError(
"image.wcs is not a simple PixelScale; scale is undefined.") from None
else:
return None
@scale.setter
def scale(self, value):
if self.wcs is not None and not self.wcs._isPixelScale:
raise GalSimError("image.wcs is not a simple PixelScale; scale is undefined.")
else:
self.wcs = PixelScale(value)
# Convenience functions
@property
def xmin(self):
"""Alias for self.bounds.xmin."""
return self._bounds.xmin
@property
def xmax(self):
"""Alias for self.bounds.xmax."""
return self._bounds.xmax
@property
def ymin(self):
"""Alias for self.bounds.ymin."""
return self._bounds.ymin
@property
def ymax(self):
"""Alias for self.bounds.ymax."""
return self._bounds.ymax
@property
def outer_bounds(self):
"""The bounds of the outer edge of the pixels.
Equivalent to galsim.BoundsD(im.xmin-0.5, im.xmax+0.5, im.ymin-0.5, im.ymax+0.5)
"""
return BoundsD(self.xmin-0.5, self.xmax+0.5, self.ymin-0.5, self.ymax+0.5)
# real, imag for everything, even real images.
@property
def real(self):
"""Return the real part of an image.
This is a property, not a function. So write ``im.real``, not ``im.real()``.
This works for real or complex. For real images, it acts the same as `view`.
"""
return _Image(self.array.real, self.bounds, self.wcs)
@property
def imag(self):
"""Return the imaginary part of an image.
This is a property, not a function. So write ``im.imag``, not ``im.imag()``.
This works for real or complex. For real images, the returned array is read-only and
all elements are 0.
"""
return _Image(self.array.imag, self.bounds, self.wcs)
@property
def conjugate(self):
"""Return the complex conjugate of an image.
This works for real or complex. For real images, it acts the same as `view`.
Note that for complex images, this is not a conjugate view into the original image.
So changing the original image does not change the conjugate (or vice versa).
"""
return _Image(self.array.conjugate(), self.bounds, self.wcs)
def copy(self):
"""Make a copy of the `Image`
"""
return _Image(self.array.copy(), self.bounds, self.wcs)
def get_pixel_centers(self):
"""A convenience function to get the x and y values at the centers of the image pixels.
Returns:
(x, y), each of which is a numpy array the same shape as ``self.array``
"""
x,y = np.meshgrid(np.arange(self.array.shape[1], dtype=float),
np.arange(self.array.shape[0], dtype=float))
x += self.bounds.xmin
y += self.bounds.ymin
return x, y
def _make_empty(self, shape, dtype):
"""Helper function to make an empty numpy array of the given shape, making sure that
the array is 16-btye aligned so it is usable by FFTW.
"""
# cf. http://stackoverflow.com/questions/9895787/memory-alignment-for-fast-fft-in-python-using-shared-arrrays
nbytes = shape[0] * shape[1] * np.dtype(dtype).itemsize
if nbytes == 0:
# Make degenerate images have 1 element. Otherwise things get weird.
return np.zeros(shape=(1,1), dtype=self._dtype)
buf = np.zeros(nbytes + 16, dtype=np.uint8)
start_index = -buf.__array_interface__['data'][0] % 16
a = buf[start_index:start_index + nbytes].view(dtype).reshape(shape)
#assert a.ctypes.data % 16 == 0
return a
def resize(self, bounds, wcs=None):
"""Resize the image to have a new bounds (must be a `BoundsI` instance)
Note that the resized image will have uninitialized data. If you want to preserve
the existing data values, you should either use `subImage` (if you want a smaller
portion of the current `Image`) or make a new `Image` and copy over the current values
into a portion of the new image (if you are resizing to a larger `Image`).
Parameters:
bounds: The new bounds to resize to.
wcs: If provided, also update the wcs to the given value. [default: None,
which means keep the existing wcs]
"""
if self.isconst:
raise GalSimImmutableError("Cannot modify an immutable Image", self)
if not isinstance(bounds, BoundsI):
raise TypeError("bounds must be a galsim.BoundsI instance")
self._array = self._make_empty(shape=bounds.numpyShape(), dtype=self.dtype)
self._bounds = bounds
if wcs is not None:
self.wcs = wcs
def subImage(self, bounds):
"""Return a view of a portion of the full image
This is equivalent to self[bounds]
"""
if not isinstance(bounds, BoundsI):
raise TypeError("bounds must be a galsim.BoundsI instance")
if not self.bounds.isDefined():
raise GalSimUndefinedBoundsError("Attempt to access subImage of undefined image")
if not self.bounds.includes(bounds):
raise GalSimBoundsError("Attempt to access subImage not (fully) in image",
bounds,self.bounds)
i1 = bounds.ymin - self.ymin
i2 = bounds.ymax - self.ymin + 1
j1 = bounds.xmin - self.xmin
j2 = bounds.xmax - self.xmin + 1
subarray = self.array[i1:i2, j1:j2]
# NB. The wcs is still accurate, since the sub-image uses the same (x,y) values
# as the original image did for those pixels. It's only once you recenter or
# reorigin that you need to update the wcs. So that's taken care of in im.shift.
return _Image(subarray, bounds, self.wcs)
def setSubImage(self, bounds, rhs):
"""Set a portion of the full image to the values in another image
This is equivalent to self[bounds] = rhs
"""
if self.isconst:
raise GalSimImmutableError("Cannot modify the values of an immutable Image", self)
self.subImage(bounds).copyFrom(rhs)
def __getitem__(self, *args):
"""Return either a subimage or a single pixel value.
For example,::
>>> subimage = im[galsim.BoundsI(3,7,3,7)]
>>> value = im[galsim.PositionI(5,5)]
>>> value = im[5,5]
"""
if len(args) == 1:
if isinstance(args[0], BoundsI):
return self.subImage(*args)
elif isinstance(args[0], PositionI):
return self(*args)
elif isinstance(args[0], tuple):
return self.getValue(*args[0])
else:
raise TypeError("image[index] only accepts BoundsI or PositionI for the index")
elif len(args) == 2:
return self(*args)
else:
raise TypeError("image[..] requires either 1 or 2 args")
def __setitem__(self, *args):
"""Set either a subimage or a single pixel to new values.
For example,::
>>> im[galsim.BoundsI(3,7,3,7)] = im2
>>> im[galsim.PositionI(5,5)] = 17.
>>> im[5,5] = 17.
"""
if len(args) == 2:
if isinstance(args[0], BoundsI):
self.setSubImage(*args)
elif isinstance(args[0], PositionI):
self.setValue(*args)
elif isinstance(args[0], tuple):
self.setValue(*args)
else:
raise TypeError("image[index] only accepts BoundsI or PositionI for the index")
elif len(args) == 3:
return self.setValue(*args)
else:
raise TypeError("image[..] requires either 1 or 2 args")
def wrap(self, bounds, hermitian=False):
"""Wrap the values in a image onto a given subimage and return the subimage.
This would typically be used on a k-space image where you initially draw a larger image
than you want for the FFT and then wrap it onto a smaller subset. This will cause
aliasing of course, but this is often preferable to just using the smaller image
without wrapping.
For complex images of FFTs, one often only stores half the image plane with the
implicit understanding that the function is Hermitian, so im(-x,-y) == im(x,y).conjugate().
In this case, the wrapping needs to work slightly differently, so you can specify
that your image is implicitly Hermitian with the ``hermitian`` argument. Options are:
hermitian=False
(default) Normal non-Hermitian image.
hermitian='x'
Only x>=0 values are stored with x<0 values being implicitly Hermitian.
In this case im.bounds.xmin and bounds.xmin must be 0.
hermitian='y'
Only y>=0 values are stored with y<0 values being implicitly Hermitian.
In this case im.bounds.ymin and bounds.ymin must be 0.
Also, in the two Hermitian cases, the direction that is not implicitly Hermitian must be
symmetric in the image's bounds. The wrap bounds must be almost symmetric, but missing
the most negative value. For example,::
>>> N = 100
>>> im_full = galsim.ImageCD(bounds=galsim.BoundsI(0,N/2,-N/2,N/2), scale=dk)
>>> # ... fill with im[i,j] = FT(kx=i*dk, ky=j*dk)
>>> N2 = 64
>>> im_wrap = im_full.wrap(galsim.BoundsI(0,N/2,-N2/2,N2/2-1, hermitian='x')
This sets up im_wrap to be the properly Hermitian version of the data appropriate for
passing to an FFT.
Note that this routine modifies the original image (and not just the subimage onto which
it is wrapped), so if you want to keep the original pristine, you should call
``wrapped_image = image.copy().wrap(bounds)``.
Parameters:
bounds: The bounds of the subimage onto which to wrap the full image.
hermitian: Whether the image is implicitly Hermitian and if so, whether it is the
x or y values that are not stored. [default: False]
Returns:
the subimage, image[bounds], after doing the wrapping.
"""
if not isinstance(bounds, BoundsI):
raise TypeError("bounds must be a galsim.BoundsI instance")
# Get this at the start to check for invalid bounds and raise the exception before
# possibly writing data past the edge of the image.
if not hermitian:
return self._wrap(bounds, False, False)
elif hermitian == 'x':
if self.bounds.xmin != 0:
raise GalSimIncompatibleValuesError(
"hermitian == 'x' requires self.bounds.xmin == 0",
hermitian=hermitian, bounds=self.bounds)
if bounds.xmin != 0:
raise GalSimIncompatibleValuesError(
"hermitian == 'x' requires bounds.xmin == 0",
hermitian=hermitian, bounds=bounds)
return self._wrap(bounds, True, False)
elif hermitian == 'y':
if self.bounds.ymin != 0:
raise GalSimIncompatibleValuesError(
"hermitian == 'y' requires self.bounds.ymin == 0",
hermitian=hermitian, bounds=self.bounds)
if bounds.ymin != 0:
raise GalSimIncompatibleValuesError(
"hermitian == 'y' requires bounds.ymin == 0",
hermitian=hermitian, bounds=bounds)
return self._wrap(bounds, False, True)
else:
raise GalSimValueError("Invalid value for hermitian", hermitian, (False, 'x', 'y'))
def _wrap(self, bounds, hermx, hermy):
"""A version of `wrap` without the sanity checks.
Equivalent to ``image.wrap(bounds, hermitian='x' if hermx else 'y' if hermy else False)``
"""
ret = self.subImage(bounds)
_galsim.wrapImage(self._image, bounds._b, hermx, hermy)
return ret
def bin(self, nx, ny):
"""Bin the image pixels in blocks of nx x ny pixels.
This returns a new image that is a binned version of the current image.
Adjacent pixel values in nx x ny blocks are added together to produce the flux in each
output pixel.
If the current number of pixels in each direction is not a multiple of nx, ny, then the
last pixel in each direction will be the sum of fewer than nx or ny pixels as needed.
See also subsample, which is the opposite of this.
If the wcs is a Jacobian (or simpler), the output image will have its wcs set properly.
But if the wcs is more complicated, the output wcs would be fairly complicated to figure
out properly, so we leave it as None. The user should set it themselves if required.
Parameters:
nx: The number of adjacent pixels in the x direction to add together into each
output pixel.
ny: The number of adjacent pixels in the y direction to add together into each
output pixel.
Returns:
a new `Image`
"""
ncol = self.xmax - self.xmin + 1
nrow = self.ymax - self.ymin + 1
nbins_x = (ncol-1) // nx + 1
nbins_y = (nrow-1) // ny + 1
nbins = nbins_x * nbins_y
# target_bins just provides a number from 0..nbins for each target pixel
target_bins = np.arange(nbins).reshape(nbins_y, nbins_x)
# current_bins is the same number for each pixel in the current image.
current_bins = np.repeat(np.repeat(target_bins, ny, axis=0), nx, axis=1)
current_bins = current_bins[0:nrow, 0:ncol]
# bincount with weights is a tricky way to do the sum over the bins
target_ar = np.bincount(current_bins.ravel(), weights=self.array.ravel())
target_ar = target_ar.reshape(target_bins.shape)
if self.wcs is None or not self.wcs._isUniform:
target_wcs = None
else:
if self.wcs._isPixelScale and nx == ny:
target_wcs = PixelScale(self.scale * nx)
else:
dudx, dudy, dvdx, dvdy = self.wcs.jacobian().getMatrix().ravel()
dudx *= nx
dvdx *= nx
dudy *= ny
dvdy *= ny
target_wcs = JacobianWCS(dudx, dudy, dvdx, dvdy)
# Set the origin so that corresponding image positions correspond to the same world_pos
x0 = (self.wcs.origin.x - self.xmin + 0.5) / nx + 0.5
y0 = (self.wcs.origin.y - self.ymin + 0.5) / ny + 0.5
target_wcs = target_wcs.shiftOrigin(_PositionD(x0,y0), self.wcs.world_origin)
target_bounds = _BoundsI(1, nbins_x, 1, nbins_y)
return _Image(target_ar, target_bounds, target_wcs)
def subsample(self, nx, ny, dtype=None):
"""Subdivide the image pixels into nx x ny sub-pixels.
This returns a new image that is a subsampled version of the current image.
Each pixel's flux is split (uniformly) into nx x ny smaller pixels.
See also bin, which is the opposite of this. Note that subsample(nx,ny) followed by
bin(nx,ny) is essentially a no op.
If the wcs is a Jacobian (or simpler), the output image will have its wcs set properly.
But if the wcs is more complicated, the output wcs would be fairly complicated to figure
out properly, so we leave it as None. The user should set it themselves if required.
Parameters:
nx: The number of sub-pixels in the x direction for each original pixel.
ny: The number of sub-pixels in the y direction for each original pixel.
dtype: Optionally provide a dtype for the return image. [default: None, which
means to use the same dtype as the original image]
Returns:
a new `Image`
"""
ncol = self.xmax - self.xmin + 1
nrow = self.ymax - self.ymin + 1
npix_x = ncol * nx
npix_y = nrow * ny
flux_factor = nx * ny
target_ar = np.repeat(np.repeat(self.array, ny, axis=0), nx, axis=1)
target_ar = target_ar.astype(dtype, copy=False) # Cute. This is a no op if dtype=None
target_ar /= flux_factor
if self.wcs is None or not self.wcs._isUniform:
target_wcs = None
else:
if self.wcs._isPixelScale and nx == ny:
target_wcs = PixelScale(self.scale / nx)
else:
dudx, dudy, dvdx, dvdy = self.wcs.jacobian().getMatrix().ravel()
dudx /= nx
dvdx /= nx
dudy /= ny
dvdy /= ny
target_wcs = JacobianWCS(dudx, dudy, dvdx, dvdy)
# Set the origin so that corresponding image positions correspond to the same world_pos
x0 = (self.wcs.origin.x - self.xmin + 0.5) * nx + 0.5
y0 = (self.wcs.origin.y - self.ymin + 0.5) * ny + 0.5
target_wcs = target_wcs.shiftOrigin(_PositionD(x0,y0), self.wcs.world_origin)
target_bounds = _BoundsI(1, npix_x, 1, npix_y)
return _Image(target_ar, target_bounds, target_wcs)
def calculate_fft(self):
"""Performs an FFT of an `Image` in real space to produce a k-space `Image`.
Note: the image will be padded with zeros as needed to make an image with bounds that
look like ``BoundsI(-N/2, N/2-1, -N/2, N/2-1)``.
The input image must have a `PixelScale` wcs. The output image will be complex (an
`ImageCF` or `ImageCD` instance) and its scale will be 2pi / (N dx), where dx is the scale
of the input image.
Returns:
an `Image` instance with the k-space image.
"""
if self.wcs is None:
raise GalSimError("calculate_fft requires that the scale be set.")
if not self.wcs._isPixelScale:
raise GalSimError("calculate_fft requires that the image has a PixelScale wcs.")
if not self.bounds.isDefined():
raise GalSimUndefinedBoundsError(
"calculate_fft requires that the image have defined bounds.")
No2 = max(-self.bounds.xmin, self.bounds.xmax+1, -self.bounds.ymin, self.bounds.ymax+1)
full_bounds = _BoundsI(-No2, No2-1, -No2, No2-1)
if self.bounds == full_bounds:
# Then the image is already in the shape we need.
ximage = self
else:
# Then we pad out with zeros
ximage = Image(full_bounds, dtype=self.dtype, init_value=0)
ximage[self.bounds] = self[self.bounds]
dx = self.scale
# dk = 2pi / (N dk)
dk = np.pi / (No2 * dx)
out = Image(_BoundsI(0,No2,-No2,No2-1), dtype=np.complex128, scale=dk)
with convert_cpp_errors():
_galsim.rfft(ximage._image, out._image, True, True)
out *= dx*dx
out.setOrigin(0,-No2)
return out
def calculate_inverse_fft(self):
"""Performs an inverse FFT of an `Image` in k-space to produce a real-space `Image`.
The starting image is typically an `ImageCD`, although if the Fourier function is real
valued, then you could get away with using an `ImageD` or `ImageF`.
The image is assumed to be Hermitian. In fact, only the portion with x >= 0 needs to
be defined, with f(-x,-y) taken to be conj(f(x,y)).
Note: the k-space image will be padded with zeros and/or wrapped as needed to make an
image with bounds that look like ``BoundsI(0, N/2, -N/2, N/2-1)``. If you are building a
larger k-space image and then wrapping, you should wrap directly into an image of
this shape.
The input image must have a `PixelScale` wcs. The output image will be real (an `ImageD`
instance) and its scale will be 2pi / (N dk), where dk is the scale of the input image.
Returns:
an `Image` instance with the real-space image.
"""
if self.wcs is None:
raise GalSimError("calculate_inverse_fft requires that the scale be set.")
if not self.wcs._isPixelScale:
raise GalSimError("calculate_inverse_fft requires that the image has a PixelScale wcs.")
if not self.bounds.isDefined():
raise GalSimUndefinedBoundsError("calculate_inverse_fft requires that the image have "
"defined bounds.")
if not self.bounds.includes(0,0):
raise GalSimBoundsError("calculate_inverse_fft requires that the image includes (0,0)",
PositionI(0,0), self.bounds)
No2 = max(self.bounds.xmax, -self.bounds.ymin, self.bounds.ymax)
target_bounds = _BoundsI(0, No2, -No2, No2-1)
if self.bounds == target_bounds:
# Then the image is already in the shape we need.
kimage = self
else:
# Then we can pad out with zeros and wrap to get this in the form we need.
full_bounds = _BoundsI(0, No2, -No2, No2)
kimage = Image(full_bounds, dtype=self.dtype, init_value=0)
posx_bounds = _BoundsI(0, self.bounds.xmax, self.bounds.ymin, self.bounds.ymax)
kimage[posx_bounds] = self[posx_bounds]
kimage = kimage.wrap(target_bounds, hermitian = 'x')
dk = self.scale
# dx = 2pi / (N dk)