GNU Astronomy Utilities


Next: , Previous: , Up: Library demo programs   [Contents][Index]


10.4.1 Library demo - reading a FITS image

The following simple program demonstrates how to read a FITS image into memory and use the void *array pointer in of Generic data container (gal_data_t). For easy linking/compilation of this program along with a first run see BuildProgram. Before running, also change the filename and hdu variable values to specify an existing FITS file and/or extension/HDU.

This is just intended to demonstrate how to use the array pointer of gal_data_t. Hence it doesn’t do important sanity checks, for example in real datasets you may also have blank pixels. In such cases, this program will return a NaN value (see Blank pixels). So for general statistical information of a dataset, it is much better to use Gnuastro’s Statistics program which can deal with blank pixels any many other issues in a generic dataset.

#include <stdio.h>
#include <stdlib.h>
#include <gnuastro/fits.h> /* includes gnuastro's data.h and type.h */
#include <gnuastro/statistics.h>

int
main(void)
{
  size_t i;
  float *farray;
  double sum=0.0f;
  gal_data_t *image;
  char *filename="img.fits", *hdu="1";


  /* Read `img.fits' (HDU: 1) as a float32 array. */
  image=gal_fits_img_read_to_type(filename, hdu, GAL_TYPE_FLOAT32, -1);


  /* Use the allocated space as a single precision floating
   * point array (recall that `image->array' has `void *'
   * type, so it is not directly usable. */
  farray=image->array;


  /* Calculate the sum of all the values. */
  for(i=0; i<image->size; ++i)
    sum += farray[i];


  /* Report the sum. */
  printf("Sum of values in %s (hdu %s) is: %f\n",
         filename, hdu, sum);


  /* Clean up and return. */
  gal_data_free(image);
  return EXIT_SUCCESS;
}