pythonnumpyopencvastropyfits

Conversion uint8 to int16


I'm trying to convert a uint8 image to int16 to be saved in fit format. The img5 display correctly but after the conversion to int16, the image is just gray.

img5 = img1Reg.copy()
cv2.imshow("img5", img5)

integer_array = img5.astype(np.int16)

cv2.imshow("integer_array", integer_array)

hdr_primary = fits.Header()
n = np.zeros((801, 1201), dtype=np.int16)
primary_hdu = fits.PrimaryHDU(integer_array, header=hdr_primary)
hdu_list = fits.HDUList([primary_hdu])
hdu_list.writeto('my_file.fit', overwrite=True)

I try several things but the most successful was using the normalized function but the image don't show any contrast, looks flat and the background is not black anymore (astro image).

img_normalized = cv2.normalize(img5, None, 0, 32000, cv2.NORM_MINMAX, dtype=cv2.CV_32F)
integer_array = img_normalized.astype(np.int16)

Is there anyway I could get sharp/black background as per img5 after converting to int16? Any help would be appreciated.


Solution

  • Use:

    integer_array = (img5.astype(np.float32)/255.0*65535.0-32768.0).astype(np.int16)
    

    That will scale properly your 0,255 range (uint8) to the -32768,32767 (int16) range.