Search code examples
pythonopencvastropyfits

How can I resolve the NaN values generated by cv2.cvtcolor when trying to work with a FITS file?


I am using the CASTLES dataset of strong lensing events and attempting to classify images of galaxies as lensing events or not.

When I check for any NaN values in the FITS image itself, I cannot find any:

    img_g = fits.open(os.path.join(path, os.listdir(path)[0]))
    img = img_g[0].data

    print(np.any(np.isnan(img))) --> (False)

But when I attempt to format the image into the proper number of color channels, I get the following:

  pic = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    for i in pic[0]:
      if np.any(np.isnan(i)):
        print(i) --> [nan, nan, nan]

In addition, NaN values pop up when I am trying to resize the image:

    pic = cv2.resize(img,(256,256))
    print(np.any(np.isnan(pic))) --> (True)

Can anyone explain to me what I am doing wrong or if there is any way to remove these NaN values while preserving the image? I will provide more information if necessary.


Solution

  • There ARE no color channels. Those are grayscale images. I downloaded the set to check. All 137 images are grayscale. If you're going to false color them, it's up to you to do the transformation.

    Followup

    You can't just convert these images to color. It doesn't make sense. I looked at one sample file, and the values ranged from -0.0289 to +0.224. If I give you a value of 0.18, what color is that? If I give you -0.02, what color is that?

    Here's a way to visualize these files, using a 2D plot:

    from astropy.io import fits
    import numpy as np
    import matplotlib.pyplot as plt
    
    f = fits.open('q256.fits')
    img = f[0].data
    
    plt.imshow(img,interpolation='none')
    plt.show()
    

    If I cd Castles/B2319/FIT/NIC2H and run that script, I get this: enter image description here

    but that is an artifact of matplotlib applying a colormap. If that's what you want, YOU have to do the color mapping. OpenCV cannot do that.