示例#1
0
def genkml(fitsfile=None,
           imagefile=None,
           input_image_origin_is_lower_left=False):
    max_side_length = 3000
    # Check for an input image.
    if not imagefile:
        print "Error: no input imagefile was given"
        print "Type '%s --help' for more information" % argv[0]
        sys.exit(2)
    elif not os.path.exists(imagefile):
        print "Error: file '%s' doesn't exist" % imagefile
        sys.exit(2)
    # Read the WCS.
    sys.stdout.write("Reading WCS from %s... " % fitsfile)
    sys.stdout.flush()
    fitslib.fits_simple_verify(fitsfile)
    fits = pyfits.open(fitsfile)
    try:
        header = fits[0].header
        wcs = wcslib.WcsProjection(header)
    finally:
        fits.close()
    sys.stdout.write("done\n")
    # Set the various warping options and warp the input image.
    image = Image.open(imagefile)
    projection = SkyProjection(image, wcs)
    projection.backgroundColor = (0, 0, 0, 0)
    projection.maxSideLength = max_side_length
    if input_image_origin_is_lower_left:
        projection.inputImageOrigin = ImageOrigin.LOWER_LEFT
    else:
        projection.inputImageOrigin = ImageOrigin.UPPER_LEFT
    sys.stdout.write("Warping image... ")
    sys.stdout.flush()
    start = time.time()
    projected_image = projection.warpImage()
    stop = time.time()
    sys.stdout.write("done in %f sec\n" % (stop - start))
    # Write warped image to file.
    name, ext = os.path.splitext(imagefile)
    projected_imagefile = "%s_warped.png" % name
    sys.stdout.write("Writing warped image to %s... " % projected_imagefile)
    sys.stdout.flush()
    projected_image.save(projected_imagefile)
    sys.stdout.write("done\n")
    # Write bounding box to KML file.
    kmlname = fitsfile[0:-4] + 'kml'
    bounding_box = projection.boundingBox
    f = open(kmlname, "w")
    try:
        f.write(bounding_box.toKml(projected_imagefile))
    finally:
        f.close()
    sys.stdout.write("done\n")
def genkml(fitsfile=None,imagefile=None,input_image_origin_is_lower_left = False):
    max_side_length = 3000
    # Check for an input image.
    if not imagefile:
        print "Error: no input imagefile was given"
        print "Type '%s --help' for more information" % argv[0]
        sys.exit(2)
    elif not os.path.exists(imagefile):
        print "Error: file '%s' doesn't exist" % imagefile
        sys.exit(2)
    # Read the WCS.
    sys.stdout.write("Reading WCS from %s... " % fitsfile)
    sys.stdout.flush()
    fitslib.fits_simple_verify(fitsfile)
    fits = pyfits.open(fitsfile)
    try:
        header = fits[0].header
        wcs = wcslib.WcsProjection(header)
    finally:
        fits.close()
    sys.stdout.write("done\n")
    # Set the various warping options and warp the input image.
    image = Image.open(imagefile)
    projection = SkyProjection(image, wcs)
    projection.backgroundColor = (0, 0, 0, 0)
    projection.maxSideLength = max_side_length
    if input_image_origin_is_lower_left:
        projection.inputImageOrigin = ImageOrigin.LOWER_LEFT
    else:
        projection.inputImageOrigin = ImageOrigin.UPPER_LEFT
    sys.stdout.write("Warping image... ")
    sys.stdout.flush()
    start = time.time()
    projected_image = projection.warpImage()
    stop = time.time()
    sys.stdout.write("done in %f sec\n" % (stop - start))
    # Write warped image to file.
    name, ext = os.path.splitext(imagefile)
    projected_imagefile = "%s_warped.png" % name
    sys.stdout.write("Writing warped image to %s... " % projected_imagefile)
    sys.stdout.flush()
    projected_image.save(projected_imagefile)
    sys.stdout.write("done\n")
    # Write bounding box to KML file.
    kmlname = fitsfile[0:-4]+'kml'
    bounding_box = projection.boundingBox   
    f = open(kmlname, "w")
    try:
        f.write(bounding_box.toKml(projected_imagefile))
    finally:
        f.close()
    sys.stdout.write("done\n")
示例#3
0
def main(argv):
    if len(argv) != 2:
        print "Usage: %s <FITS file>" % os.path.basename(argv[0])
        sys.exit(2)

    fitsfile = argv[1]
    if not os.path.exists(fitsfile):
        print "Error: file '%s' doesn't exist" % fitsfile
        sys.exit(2)

    name, ext = os.path.splitext(fitsfile)
    print "Extacting extensions from '%s'... " % fitsfile
    fitslib.fits_simple_verify(fitsfile)
    fits = pyfits.open(fitsfile)

    for i, hdu in enumerate(fits):
        new_fitsfile = "%s_ext_%d.fits" % (name, i)

        # Write out the new file
        pyfits.writeto(new_fitsfile, hdu.data, hdu.header)
        print "Wrote extension %d to %s" % (i, new_fitsfile)

    fits.close()
示例#4
0
def main(argv):
  if len(argv) != 2:
    print "Usage: %s <FITS file>" % os.path.basename(argv[0])
    sys.exit(2)

  fitsfile = argv[1]
  if not os.path.exists(fitsfile):
    print "Error: file '%s' doesn't exist" % fitsfile
    sys.exit(2)

  name, ext = os.path.splitext(fitsfile)
  print "Extacting extensions from '%s'... " % fitsfile
  fitslib.fits_simple_verify(fitsfile)
  fits = pyfits.open(fitsfile)

  for i, hdu in enumerate(fits):
    new_fitsfile = "%s_ext_%d.fits" % (name, i)

    # Write out the new file
    pyfits.writeto(new_fitsfile, hdu.data, hdu.header)
    print "Wrote extension %d to %s" % (i, new_fitsfile)

  fits.close()
示例#5
0
                print "Error: invalid value '%s' for %s" % (arg, opt)
                sys.exit(2)

    # Check for an input image.
    if not imagefile:
        print "Error: no input imagefile was given"
        print "Type '%s --help' for more information" % argv[0]
        sys.exit(2)
    elif not os.path.exists(imagefile):
        print "Error: file '%s' doesn't exist" % imagefile
        sys.exit(2)

    # Determine if the input image is a FITS file.
    is_fits_file = True
    try:
        fitslib.fits_simple_verify(imagefile)
    except (IOError, ValueError, EOFError):
        is_fits_file = False
        if not fitsfile:
            print "Error: no FITS file input for --fitsfile"
            sys.exit(2)

    # Convert input FITS images to raster format if the --fitsfile option has
    # not been given.
    if is_fits_file and not fitsfile:
        sys.stdout.write("Converting input FITS image to raster format... ")
        sys.stdout.flush()
        image = fitsimage.FitsImage(imagefile)
        sys.stdout.write("done\n")
        fitsfile = imagefile
        # This should always be True for fitsimage conversions.
示例#6
0
def FITSParse(fitsFile, orderbyField='', hdu=1, surveyName=''):
    """
  Parse a FITS file into a list of FITSPoint instances that contain
  placemark data for each object.
  """

    fitslib.fits_simple_verify(fitsFile)
    hduList = pyfits.open(fitsFile)

    if len(surveyName) == 0:
        surveyName = os.path.basename(fitsFile).split('.')[0]

    cols = hduList[hdu].columns
    if not cols:
        return

    raTag, raIndex, decTag, decIndex = parseFitsColumns(cols)

    if raIndex != -1 and decIndex != -1:
        print 'Found possibilities for RA and DEC in header: %s, %s' % (raTag,
                                                                        decTag)
    else:
        print "Didn't find either both RA and DEC equivalent in header."
        return

    tbData = hduList[1].data

    if len(orderbyField) > 0:
        print "Re-sorting FITS data using '" + orderbyField.upper(
        ) + "' field."
        tmpCol = tbData.field(orderbyField)
        idx = tmpCol.argsort()
        tbData = tbData[idx]

    fitsObjectList = []

    objCounter = 0
    for objData in tbData:
        fitsObject = SimplePlacemark()

        ra = objData.field(raIndex)
        dec = objData.field(decIndex)

        raGeo = ra - 180.0
        decGeo = dec

        fitsObject.SetLongitude(raGeo)
        fitsObject.SetLatitude(decGeo)

        (ra_str, dec_str, iauName) = objIAUName(surveyName, ra, dec)

        fitsObject.SetName(iauName)

        description = []

        description.append(
            "<table width='300' cellspacing='0' cellpadding='0'>")

        idx = 0
        for colNames in cols.names:
            if idx == raIndex:
                description.append("<tr><td align='center'>" + colNames +
                                   "</td><td align='center'>" + ra_str +
                                   "</td></tr>\n")
            elif idx == decIndex:
                description.append("<tr><td align='center'>" + colNames +
                                   "</td><td align='center'>" + dec_str +
                                   "</td></tr>\n")
            else:
                description.append("<tr><td align='center'>" + colNames +
                                   "</td><td align='center'>" +
                                   str(objData.field(colNames)) +
                                   "</td></tr>\n")
            idx = idx + 1

        description.append('</table>\n')

        description = ''.join(description)
        fitsObject.SetDescription(description)

        fitsObject.SetStyleUrl('#FitsPoint')

        objCounter = objCounter + 1
        if objCounter % 10000 == 0:
            print '%i/%i objects...' % (objCounter, len(tbData))

        fitsObjectList.append(fitsObject)

    return fitsObjectList
示例#7
0
def FitsImage(fitsfile, contrast="zscale", contrast_opts={}, scale="linear",
              scale_opts={}):

    """
    Constructor-like function that returns a Python Imaging Library (PIL)
    Image object.  This allows extremely easy and powerful manipulation of
    FITs files as images.  The contrast is automatically adjusted using the
    zscale algorithm (see zscale_range() above).

    Input:  fitsfile      -- a FITS image filename
            contrast      -- the algorithm for determining the min/max
                             values in the FITS pixel data to use when
                             compressing the dynamic range of the FITS
                             data to something visible by the eye, either
                             "zscale" or "percentile"
            contrast_opts -- options for the contrast algorithm, see
                             the optional args of [contrast]_range()
                             for what to name the keys
            scale         -- how to scale the pixel values between the
                             min/max values from the contrast
                             algorithm when converting to a a raster
                             format, either "linear" or "arcsinh"
            scale_opts    -- options for the scaling algorithm, currently
                             only "nonlinearity" is supported for arcsinh,
                             which has a default value of 3
    """

    if contrast not in ("zscale", "percentile"):
        raise ValueError("invalid contrast algorithm '%s'" % contrast)
    if scale not in ("linear", "arcsinh"):
        raise ValueError("invalid scale value '%s'" % scale)

    # open the fits file and read the image data and size
    fitslib.fits_simple_verify(fitsfile)
    fits = pyfits.open(fitsfile)

    try:
        hdr = fits[0].header
        xsize = hdr["NAXIS1"]
        ysize = hdr["NAXIS2"]
        fits_data = fits[0].data
    finally:
        fits.close()
    
    # compute the proper scaling for the image
    if contrast == "zscale":
        contrast_value = contrast_opts.get("contrast", 0.25)
        num_points = contrast_opts.get("num_points", 600)
        num_per_row = contrast_opts.get("num_per_row", 120)
        zmin, zmax = zscale_range(fits_data, contrast=contrast_value,
                                  num_points=num_points,
                                  num_per_row=num_per_row)
    elif contrast == "percentile":
        min_percent = contrast_opts.get("min_percent", 3.0)
        max_percent = contrast_opts.get("max_percent", 99.0)
        num_points = contrast_opts.get("num_points", 5000)
        num_per_row = contrast_opts.get("num_per_row", 250)
        zmin, zmax = percentile_range(fits_data, min_percent=min_percent,
                                      max_percent=max_percent,
                                      num_points=num_points,
                                      num_per_row=num_per_row)

    # set all points less than zmin to zmin and points greater than
    # zmax to zmax
    fits_data = numpy.where(fits_data > zmin, fits_data, zmin)
    fits_data = numpy.where(fits_data < zmax, fits_data, zmax)

    if scale == "linear":
        scaled_data = (fits_data - zmin) * (255.0 / (zmax - zmin)) + 0.5
    elif scale == "arcsinh":
        # nonlinearity sets the range over which we sample values of the
        # asinh function; values near 0 are linear and values near infinity
        # are logarithmic
        nonlinearity = scale_opts.get("nonlinearity", 3.0)
        nonlinearity = max(nonlinearity, 0.001)
        max_asinh = cmath.asinh(nonlinearity).real
        scaled_data = (255.0 / max_asinh) * \
                      (numpy.arcsinh((fits_data - zmin) * \
                                     (nonlinearity / (zmax - zmin))))

    # convert to 8 bit unsigned int ("b" in numpy)
    #scaled_data = scaled_data.astype("b")
    
    # create the image
    print 'hi'
    image = Image.frombuffer("L", (xsize, ysize), scaled_data, "raw", "L", 0, 0)
    return image
示例#8
0
        print "Error: invalid value '%s' for %s" % (arg, opt)
        sys.exit(2)

  # Check for an input image.
  if not imagefile:
    print "Error: no input imagefile was given"
    print "Type '%s --help' for more information" % argv[0]
    sys.exit(2)
  elif not os.path.exists(imagefile):
    print "Error: file '%s' doesn't exist" % imagefile
    sys.exit(2)

  # Determine if the input image is a FITS file.
  is_fits_file = True
  try:
    fitslib.fits_simple_verify(imagefile)
  except (IOError, ValueError, EOFError):
    is_fits_file = False
    if not fitsfile:
      print "Error: no FITS file input for --fitsfile"
      sys.exit(2)

  # Convert input FITS images to raster format if the --fitsfile option has
  # not been given.
  if is_fits_file and not fitsfile:
    sys.stdout.write("Converting input FITS image to raster format... ")
    sys.stdout.flush()
    image = fitsimage.FitsImage(imagefile)
    sys.stdout.write("done\n")
    fitsfile = imagefile    
    # This should always be True for fitsimage conversions.