FitsImagePlugin.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # FITS file handling
  6. #
  7. # Copyright (c) 1998-2003 by Fredrik Lundh
  8. #
  9. # See the README file for information on usage and redistribution.
  10. #
  11. import math
  12. from . import Image, ImageFile
  13. def _accept(prefix):
  14. return prefix[:6] == b"SIMPLE"
  15. class FitsImageFile(ImageFile.ImageFile):
  16. format = "FITS"
  17. format_description = "FITS"
  18. def _open(self):
  19. headers = {}
  20. while True:
  21. header = self.fp.read(80)
  22. if not header:
  23. msg = "Truncated FITS file"
  24. raise OSError(msg)
  25. keyword = header[:8].strip()
  26. if keyword == b"END":
  27. break
  28. value = header[8:].split(b"/")[0].strip()
  29. if value.startswith(b"="):
  30. value = value[1:].strip()
  31. if not headers and (not _accept(keyword) or value != b"T"):
  32. msg = "Not a FITS file"
  33. raise SyntaxError(msg)
  34. headers[keyword] = value
  35. naxis = int(headers[b"NAXIS"])
  36. if naxis == 0:
  37. msg = "No image data"
  38. raise ValueError(msg)
  39. elif naxis == 1:
  40. self._size = 1, int(headers[b"NAXIS1"])
  41. else:
  42. self._size = int(headers[b"NAXIS1"]), int(headers[b"NAXIS2"])
  43. number_of_bits = int(headers[b"BITPIX"])
  44. if number_of_bits == 8:
  45. self._mode = "L"
  46. elif number_of_bits == 16:
  47. self._mode = "I"
  48. # rawmode = "I;16S"
  49. elif number_of_bits == 32:
  50. self._mode = "I"
  51. elif number_of_bits in (-32, -64):
  52. self._mode = "F"
  53. # rawmode = "F" if number_of_bits == -32 else "F;64F"
  54. offset = math.ceil(self.fp.tell() / 2880) * 2880
  55. self.tile = [("raw", (0, 0) + self.size, offset, (self.mode, 0, -1))]
  56. # --------------------------------------------------------------------
  57. # Registry
  58. Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
  59. Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])