lsst.afw  15.0-21-g91b8abf62
rgb.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 from builtins import object
3 #
4 # LSST Data Management System
5 # Copyright 2015-2016 LSST/AURA
6 #
7 # This product includes software developed by the
8 # LSST Project (http://www.lsst.org/).
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the LSST License Statement and
21 # the GNU General Public License along with this program. If not,
22 # see <https://www.lsstcorp.org/LegalNotices/>.
23 #
24 
25 import numpy as np
26 
27 import lsst.afw.image as afwImage
28 import lsst.afw.math as afwMath
29 from lsst.afw.display.displayLib import replaceSaturatedPixels, getZScale
30 
31 
32 def computeIntensity(imageR, imageG=None, imageB=None):
33  """!Return a naive total intensity from the red, blue, and green intensities
34  \param imageR intensity of image that'll be mapped to red; or intensity if imageG and imageB are None
35  \param imageG intensity of image that'll be mapped to green; or None
36  \param imageB intensity of image that'll be mapped to blue; or None
37 
38  Inputs may be MaskedImages, Images, or numpy arrays and the return is of the same type
39  """
40  if imageG is None or imageB is None:
41  assert imageG is None and imageB is None, \
42  "Please specify either a single image or red, green, and blue images"
43  return imageR
44 
45  imageRGB = [imageR, imageG, imageB]
46 
47  for i, c in enumerate(imageRGB):
48  if hasattr(c, "getImage"):
49  c = imageRGB[i] = c.getImage()
50  if hasattr(c, "getArray"):
51  imageRGB[i] = c.getArray()
52 
53  intensity = (imageRGB[0] + imageRGB[1] + imageRGB[2])/float(3)
54  #
55  # Repack into whatever type was passed to us
56  #
57  Image = afwImage.ImageU if intensity.dtype == 'uint16' else afwImage.ImageF
58 
59  if hasattr(imageR, "getImage"): # a maskedImage
60  intensity = afwImage.makeMaskedImage(Image(intensity))
61  elif hasattr(imageR, "getArray"):
62  intensity = Image(intensity)
63 
64  return intensity
65 
66 
67 class Mapping(object):
68  """!Baseclass to map red, blue, green intensities into uint8 values"""
69 
70  def __init__(self, minimum=None, image=None):
71  """!Create a mapping
72  \param minimum Intensity that should be mapped to black (a scalar or array for R, G, B)
73  \param image The image to be used to calculate the mapping.
74 
75  If provided, also the default for makeRgbImage()
76  """
77  self._uint8Max = float(np.iinfo(np.uint8).max)
78 
79  try:
80  len(minimum)
81  except TypeError:
82  minimum = 3*[minimum]
83  assert len(minimum) == 3, "Please provide 1 or 3 values for minimum"
84 
85  self.minimum = minimum
86  self._image = image
87 
88  def makeRgbImage(self, imageR=None, imageG=None, imageB=None,
89  xSize=None, ySize=None, rescaleFactor=None):
90  """!Convert 3 arrays, imageR, imageG, and imageB into a numpy RGB image
91  \param imageR Image to map to red (if None, use the image passed to the ctor)
92  \param imageG Image to map to green (if None, use imageR)
93  \param imageB Image to map to blue (if None, use imageR)
94  \param xSize Desired width of RGB image (or None). If ySize is None, preserve aspect ratio
95  \param ySize Desired height of RGB image (or None)
96  \param rescaleFactor Make size of output image rescaleFactor*size of the input image (or None)
97 
98  N.b. images may be afwImage.Images or numpy arrays
99  """
100  if imageR is None:
101  if self._image is None:
102  raise RuntimeError(
103  "You must provide an image (or pass one to the constructor)")
104  imageR = self._image
105 
106  if imageG is None:
107  imageG = imageR
108  if imageB is None:
109  imageB = imageR
110 
111  imageRGB = [imageR, imageG, imageB]
112  for i, c in enumerate(imageRGB):
113  if hasattr(c, "getImage"):
114  c = imageRGB[i] = c.getImage()
115  if hasattr(c, "getArray"):
116  imageRGB[i] = c.getArray()
117 
118  if xSize is not None or ySize is not None:
119  assert rescaleFactor is None, "You may not specify a size and rescaleFactor"
120  h, w = imageRGB[0].shape
121  if ySize is None:
122  ySize = int(xSize*h/float(w) + 0.5)
123  elif xSize is None:
124  xSize = int(ySize*w/float(h) + 0.5)
125 
126  size = (ySize, xSize) # n.b. y, x order for scipy
127  elif rescaleFactor is not None:
128  size = float(rescaleFactor) # an int is intepreted as a percentage
129  else:
130  size = None
131 
132  if size is not None:
133  try:
134  import scipy.misc
135  except ImportError as e:
136  raise RuntimeError(
137  "Unable to rescale as scipy.misc is unavailable: %s" % e)
138 
139  for i, im in enumerate(imageRGB):
140  imageRGB[i] = scipy.misc.imresize(
141  im, size, interp='bilinear', mode='F')
142 
143  return np.dstack(self._convertImagesToUint8(*imageRGB)).astype(np.uint8)
144 
145  def intensity(self, imageR, imageG, imageB):
146  """!Return the total intensity from the red, blue, and green intensities
147 
148  This is a naive computation, and may be overridden by subclasses
149  """
150  return computeIntensity(imageR, imageG, imageB)
151 
152  def mapIntensityToUint8(self, intensity):
153  """Map an intensity into the range of a uint8, [0, 255] (but not converted to uint8)"""
154  with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit
155  return np.where(intensity <= 0, 0,
156  np.where(intensity < self._uint8Max, intensity, self._uint8Max))
157 
158  def _convertImagesToUint8(self, imageR, imageG, imageB):
159  """Use the mapping to convert images imageR, imageG, and imageB to a triplet of uint8 images"""
160  imageR = imageR - self.minimum[0] # n.b. makes copy
161  imageG = imageG - self.minimum[1]
162  imageB = imageB - self.minimum[2]
163 
164  fac = self.mapIntensityToUint8(self.intensity(imageR, imageG, imageB))
165 
166  imageRGB = [imageR, imageG, imageB]
167  with np.errstate(invalid="ignore"): # suppress NAN warnings
168  for c in imageRGB:
169  c *= fac
170  # individual bands can still be < 0, even if fac isn't
171  c[c < 0] = 0
172 
173  pixmax = self._uint8Max
174  # copies -- could work row by row to minimise memory usage
175  r0, g0, b0 = imageRGB
176 
177  # n.b. np.where can't and doesn't short-circuit
178  with np.errstate(invalid='ignore', divide='ignore'):
179  for i, c in enumerate(imageRGB):
180  c = np.where(r0 > g0,
181  np.where(r0 > b0,
182  np.where(r0 >= pixmax, c*pixmax/r0, c),
183  np.where(b0 >= pixmax, c*pixmax/b0, c)),
184  np.where(g0 > b0,
185  np.where(g0 >= pixmax, c*pixmax/g0, c),
186  np.where(b0 >= pixmax, c*pixmax/b0, c))).astype(np.uint8)
187  c[c > pixmax] = pixmax
188 
189  imageRGB[i] = c
190 
191  return imageRGB
192 
193 
195  """!A linear map map of red, blue, green intensities into uint8 values"""
196 
197  def __init__(self, minimum=None, maximum=None, image=None):
198  """!A linear stretch from [minimum, maximum]; if one or both are omitted use image minimum/maximum to set them
199 
200  \param minimum Intensity that should be mapped to black (a scalar or array for R, G, B)
201  \param maximum Intensity that should be mapped to white (a scalar)
202  \param image Image to estimate minimum/maximum if not explicitly set
203  """
204 
205  if minimum is None or maximum is None:
206  assert image is not None, "You must provide an image if you don't set both minimum and maximum"
207 
208  stats = afwMath.makeStatistics(image, afwMath.MIN | afwMath.MAX)
209  if minimum is None:
210  minimum = stats.getValue(afwMath.MIN)
211  if maximum is None:
212  maximum = stats.getValue(afwMath.MAX)
213 
214  Mapping.__init__(self, minimum, image)
215  self.maximum = maximum
216 
217  if maximum is None:
218  self._range = None
219  else:
220  assert maximum - minimum != 0, "minimum and maximum values must not be equal"
221  self._range = float(maximum - minimum)
222 
223  def mapIntensityToUint8(self, intensity):
224  """Return an array which, when multiplied by an image, returns that image mapped to the range of a
225  uint8, [0, 255] (but not converted to uint8)
226 
227  The intensity is assumed to have had minimum subtracted (as that can be done per-band)
228  """
229  with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit
230  return np.where(intensity <= 0, 0,
231  np.where(intensity >= self._range,
232  self._uint8Max/intensity, self._uint8Max/self._range))
233 
234 
236  """!A mapping for a linear stretch chosen by the zscale algorithm
237  (preserving colours independent of brightness)
238 
239  x = (I - minimum)/range
240  """
241 
242  def __init__(self, image, nSamples=1000, contrast=0.25):
243  """!A linear stretch from [z1, z2] chosen by the zscale algorithm
244  \param image Image whose parameters are desired
245  \param nSamples The number of samples to use to estimate the zscale parameters
246  \param contrast The number of samples to use to estimate the zscale parameters
247  """
248 
249  if not hasattr(image, "getArray"):
250  image = afwImage.ImageF(image)
251  z1, z2 = getZScale(image, nSamples, contrast)
252 
253  LinearMapping.__init__(self, z1, z2, image)
254 
255 
257  """!A mapping for an asinh stretch (preserving colours independent of brightness)
258 
259  x = asinh(Q (I - minimum)/range)/Q
260 
261  This reduces to a linear stretch if Q == 0
262 
263  See http://adsabs.harvard.edu/abs/2004PASP..116..133L
264  """
265 
266  def __init__(self, minimum, dataRange, Q=8):
267  Mapping.__init__(self, minimum)
268 
269  # 32bit floating point machine epsilon; sys.float_info.epsilon is 64bit
270  epsilon = 1.0/2**23
271  if abs(Q) < epsilon:
272  Q = 0.1
273  else:
274  Qmax = 1e10
275  if Q > Qmax:
276  Q = Qmax
277 
278  if False:
279  self._slope = self._uint8Max/Q # gradient at origin is self._slope
280  else:
281  frac = 0.1 # gradient estimated using frac*range is _slope
282  self._slope = frac*self._uint8Max/np.arcsinh(frac*Q)
283 
284  self._soften = Q/float(dataRange)
285 
286  def mapIntensityToUint8(self, intensity):
287  """Return an array which, when multiplied by an image, returns that image mapped to the range of a
288  uint8, [0, 255] (but not converted to uint8)
289 
290  The intensity is assumed to have had minimum subtracted (as that can be done per-band)
291  """
292  with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit
293  return np.where(intensity <= 0, 0, np.arcsinh(intensity*self._soften)*self._slope/intensity)
294 
295 
297  """!A mapping for an asinh stretch, estimating the linear stretch by zscale
298 
299  x = asinh(Q (I - z1)/(z2 - z1))/Q
300 
301  See AsinhMapping
302  """
303 
304  def __init__(self, image, Q=8, pedestal=None):
305  """!
306  Create an asinh mapping from an image, setting the linear part of the stretch using zscale
307 
308  \param image The image to analyse, or a list of 3 images to be converted to an intensity image
309  \param Q The asinh softening parameter
310  \param pedestal The value, or array of 3 values, to subtract from the images; or None
311 
312  N.b. pedestal, if not None, is removed from the images when calculating the zscale
313  stretch, and added back into Mapping.minimum[]
314  """
315  try:
316  assert len(image) in (1, 3,), "Please provide 1 or 3 images"
317  except TypeError:
318  image = [image]
319 
320  if pedestal is not None:
321  try:
322  assert len(pedestal) in (
323  1, 3,), "Please provide 1 or 3 pedestals"
324  except TypeError:
325  pedestal = 3*[pedestal]
326 
327  image = list(image) # needs to be mutable
328  for i, im in enumerate(image):
329  if pedestal[i] != 0.0:
330  if hasattr(im, "getImage"):
331  im = im.getImage()
332  if hasattr(im, "getArray"):
333  im = im.getArray()
334 
335  image[i] = im - pedestal[i] # n.b. a copy
336  else:
337  pedestal = len(image)*[0.0]
338 
339  image = computeIntensity(*image)
340 
341  zscale = ZScaleMapping(image)
342  # zscale.minimum is always a triple
343  dataRange = zscale.maximum - zscale.minimum[0]
344  minimum = zscale.minimum
345 
346  for i, level in enumerate(pedestal):
347  minimum[i] += level
348 
349  AsinhMapping.__init__(self, minimum, dataRange, Q)
350  self._image = image # support self.makeRgbImage()
351 
352 
353 def makeRGB(imageR, imageG=None, imageB=None, minimum=0, dataRange=5, Q=8, fileName=None,
354  saturatedBorderWidth=0, saturatedPixelValue=None,
355  xSize=None, ySize=None, rescaleFactor=None):
356  """Make a set of three images into an RGB image using an asinh stretch and optionally write it to disk
357 
358  If saturatedBorderWidth is non-zero, replace saturated pixels with saturatedPixelValue. Note
359  that replacing saturated pixels requires that the input images be MaskedImages.
360  """
361  if imageG is None:
362  imageG = imageR
363  if imageB is None:
364  imageB = imageR
365 
366  if saturatedBorderWidth:
367  if saturatedPixelValue is None:
368  raise ValueError(
369  "saturatedPixelValue must be set if saturatedBorderWidth is set")
370  replaceSaturatedPixels(imageR, imageG, imageB,
371  saturatedBorderWidth, saturatedPixelValue)
372 
373  asinhMap = AsinhMapping(minimum, dataRange, Q)
374  rgb = asinhMap.makeRgbImage(imageR, imageG, imageB,
375  xSize=xSize, ySize=ySize, rescaleFactor=rescaleFactor)
376 
377  if fileName:
378  writeRGB(fileName, rgb)
379 
380  return rgb
381 
382 
383 def displayRGB(rgb, show=True):
384  """!Display an rgb image using matplotlib
385  \param rgb The RGB image in question
386  \param show If true, call plt.show()
387  """
388  import matplotlib.pyplot as plt
389  plt.imshow(rgb, interpolation='nearest', origin="lower")
390  if show:
391  plt.show()
392  return plt
393 
394 
395 def writeRGB(fileName, rgbImage):
396  """!Write an RGB image to disk
397  \param fileName The output file. The suffix defines the format, and must be supported by matplotlib
398  \param rgbImage The image, as made by e.g. makeRGB
399 
400  Most versions of matplotlib support png and pdf (although the eps/pdf/svg writers may be buggy,
401  possibly due an interaction with useTeX=True in the matplotlib settings).
402 
403  If your matplotlib bundles pil/pillow you should also be able to write jpeg and tiff files.
404  """
405  import matplotlib.image
406  matplotlib.image.imsave(fileName, rgbImage)
407 
408 #
409 # Support the legacy API
410 #
411 
412 
413 class asinhMappingF(object): # noqa N801
414  """!\deprecated Object used to support legacy API"""
415 
416  def __init__(self, minimum, dataRange, Q):
417  self.minimum = minimum
418  self.dataRange = dataRange
419  self.Q = Q
420 
421 
422 class _RgbImageF(object):
423  """!\deprecated Object used to support legacy API"""
424 
425  def __init__(self, imageR, imageG, imageB, mapping):
426  """!\deprecated Legacy API"""
427  asinh = AsinhMapping(mapping.minimum, mapping.dataRange, mapping.Q)
428  self.rgb = asinh.makeRgbImage(imageR, imageG, imageB)
429 
430  def write(self, fileName):
431  """!\deprecated Legacy API"""
432  writeRGB(fileName, self.rgb)
433 
434 
435 def RgbImageF(imageR, imageG, imageB, mapping):
436  """!\deprecated Legacy API"""
437  return _RgbImageF(imageR, imageG, imageB, mapping)
def __init__(self, minimum=None, image=None)
Create a mapping.
Definition: rgb.py:70
def __init__(self, minimum, dataRange, Q=8)
Definition: rgb.py:266
def __init__(self, image, Q=8, pedestal=None)
Create an asinh mapping from an image, setting the linear part of the stretch using zscale...
Definition: rgb.py:304
def __init__(self, image, nSamples=1000, contrast=0.25)
A linear stretch from [z1, z2] chosen by the zscale algorithm.
Definition: rgb.py:242
def computeIntensity(imageR, imageG=None, imageB=None)
Return a naive total intensity from the red, blue, and green intensities.
Definition: rgb.py:32
def __init__(self, imageR, imageG, imageB, mapping)
Definition: rgb.py:425
Baseclass to map red, blue, green intensities into uint8 values.
Definition: rgb.py:67
std::pair< double, double > getZScale(image::Image< T > const &image, int const nSamples=1000, double const contrast=0.25)
Calculate an IRAF/ds9-style zscaling.
void replaceSaturatedPixels(ImageT &rim, ImageT &gim, ImageT &bim, int borderWidth=2, float saturatedPixelValue=65535)
def makeRGB(imageR, imageG=None, imageB=None, minimum=0, dataRange=5, Q=8, fileName=None, saturatedBorderWidth=0, saturatedPixelValue=None, xSize=None, ySize=None, rescaleFactor=None)
Definition: rgb.py:355
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT >> image, typename std::shared_ptr< Mask< MaskPixelT >> mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT >> variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
Definition: MaskedImage.h:1268
Statistics makeStatistics(lsst::afw::math::MaskedVector< EntryT > const &mv, std::vector< WeightPixel > const &vweights, int const flags, StatisticsControl const &sctrl=StatisticsControl())
The makeStatistics() overload to handle lsst::afw::math::MaskedVector<>
Definition: Statistics.h:518
def mapIntensityToUint8(self, intensity)
Definition: rgb.py:152
A linear map map of red, blue, green intensities into uint8 values.
Definition: rgb.py:194
def displayRGB(rgb, show=True)
Display an rgb image using matplotlib.
Definition: rgb.py:383
def write(self, fileName)
Definition: rgb.py:430
def makeRgbImage(self, imageR=None, imageG=None, imageB=None, xSize=None, ySize=None, rescaleFactor=None)
Convert 3 arrays, imageR, imageG, and imageB into a numpy RGB image.
Definition: rgb.py:89
def mapIntensityToUint8(self, intensity)
Definition: rgb.py:286
A mapping for an asinh stretch, estimating the linear stretch by zscale.
Definition: rgb.py:296
A mapping for a linear stretch chosen by the zscale algorithm (preserving colours independent of brig...
Definition: rgb.py:235
A mapping for an asinh stretch (preserving colours independent of brightness)
Definition: rgb.py:256
def mapIntensityToUint8(self, intensity)
Definition: rgb.py:223
def __init__(self, minimum, dataRange, Q)
Definition: rgb.py:416
daf::base::PropertyList * list
Definition: fits.cc:819
def _convertImagesToUint8(self, imageR, imageG, imageB)
Definition: rgb.py:158
def RgbImageF(imageR, imageG, imageB, mapping)
Definition: rgb.py:435
def intensity(self, imageR, imageG, imageB)
Return the total intensity from the red, blue, and green intensities.
Definition: rgb.py:145
def writeRGB(fileName, rgbImage)
Write an RGB image to disk.
Definition: rgb.py:395
def __init__(self, minimum=None, maximum=None, image=None)
A linear stretch from [minimum, maximum]; if one or both are omitted use image minimum/maximum to set...
Definition: rgb.py:197