#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Documentation: http://docs.astropy.org/en/stable/io/fits/index.html

import argparse
from astropy.io import fits

import PIL.Image as pil_img # PIL.Image is a module not a class...


# SAVE THE IMAGE ##############################################################

def save(img, output_file_path):
    """
    img is the image and it should be a 2D numpy array with values in the range [0,255].
    """
    if img.ndim != 2:
        raise Exception("The input image should be a 2D numpy array.")

    # Save
    mode = "L"                           # "L" = grayscale mode
    pil_image = pil_img.new(mode, img.shape)

    # WARNING: nested list and 2D numpy arrays are silently rejected!!!
    #          data *must* be a list or a 1D numpy array!
    pil_image.putdata(img.flatten())
    pil_image.save(output_file_path)


if __name__ == "__main__":

    # PARSE OPTIONS ###########################################################

    parser = argparse.ArgumentParser(description="Convert FITS files to PNG images")
    parser.add_argument("filearg", nargs=1, metavar="FILE", help="the FITS file to convert")
    args = parser.parse_args()
    file_path = args.filearg[0]

    # READ DATA ###############################################################

    # Open the FITS file
    hdu_list = fits.open(file_path)

    for hdu_index, hdu in enumerate(hdu_list):
        img = hdu.data   # "hdu.data" is a Numpy Array

        if img.ndim == 2:

            # If there are only one image (img is an 2D array)
            save(img, "out_hdu{}.png".format(hdu_index))

        elif img.ndim == 3:

            # If there is more than one image (img is an 3D array)
            for img_index, img in enumerate(img):
                save(img, "out_hdu{}_{}.png".format(hdu_index, img_index))

    # Close the FITS file
    hdu_list.close()


@@ -224,16 +224,35 @@
 lass...%0A
+import numpy as np%0A
 %0A%0A# SAVE
@@ -356,16 +356,44 @@
 ile_path
+, min_val=None, max_val=None
 ):%0A    %22
@@ -484,24 +484,121 @@
 0,255%5D.%0A
+    min_val and max_val are normalization parameters (the minimum and maximum value of a pixel).%0A
     %22%22%22%0A
     if i
@@ -585,24 +585,25 @@
 l).%0A    %22%22%22%0A
+%0A
     if img.n
@@ -688,19 +688,8 @@
 %22)%0A%0A
-    # Save%0A
     
@@ -794,16 +794,401 @@
 shape)%0A%0A
+    # Normalize values ################%0A    # (FITS pixels value are unbounded but PNG pixels value are in range %5B0,255%5D)%0A    if min_val == None:%0A        min_val = img.min()%0A    if max_val == None:%0A        max_val = img.max()%0A%0A    img = img.astype(np.float32)%0A    img -= min_val%0A    img /= max_val%0A    img *= 255%0A    img = img.astype(np.uint8)%0A%0A    # Save ############################%0A
     # WA

Add a normalization step.