SpiderImagePlugin.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #
  2. # The Python Imaging Library.
  3. #
  4. # SPIDER image file handling
  5. #
  6. # History:
  7. # 2004-08-02 Created BB
  8. # 2006-03-02 added save method
  9. # 2006-03-13 added support for stack images
  10. #
  11. # Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
  12. # Copyright (c) 2004 by William Baxter.
  13. # Copyright (c) 2004 by Secret Labs AB.
  14. # Copyright (c) 2004 by Fredrik Lundh.
  15. #
  16. ##
  17. # Image plugin for the Spider image format. This format is used
  18. # by the SPIDER software, in processing image data from electron
  19. # microscopy and tomography.
  20. ##
  21. #
  22. # SpiderImagePlugin.py
  23. #
  24. # The Spider image format is used by SPIDER software, in processing
  25. # image data from electron microscopy and tomography.
  26. #
  27. # Spider home page:
  28. # https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
  29. #
  30. # Details about the Spider image format:
  31. # https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
  32. #
  33. import os
  34. import struct
  35. import sys
  36. from . import Image, ImageFile
  37. def isInt(f):
  38. try:
  39. i = int(f)
  40. if f - i == 0:
  41. return 1
  42. else:
  43. return 0
  44. except (ValueError, OverflowError):
  45. return 0
  46. iforms = [1, 3, -11, -12, -21, -22]
  47. # There is no magic number to identify Spider files, so just check a
  48. # series of header locations to see if they have reasonable values.
  49. # Returns no. of bytes in the header, if it is a valid Spider header,
  50. # otherwise returns 0
  51. def isSpiderHeader(t):
  52. h = (99,) + t # add 1 value so can use spider header index start=1
  53. # header values 1,2,5,12,13,22,23 should be integers
  54. for i in [1, 2, 5, 12, 13, 22, 23]:
  55. if not isInt(h[i]):
  56. return 0
  57. # check iform
  58. iform = int(h[5])
  59. if iform not in iforms:
  60. return 0
  61. # check other header values
  62. labrec = int(h[13]) # no. records in file header
  63. labbyt = int(h[22]) # total no. of bytes in header
  64. lenbyt = int(h[23]) # record length in bytes
  65. if labbyt != (labrec * lenbyt):
  66. return 0
  67. # looks like a valid header
  68. return labbyt
  69. def isSpiderImage(filename):
  70. with open(filename, "rb") as fp:
  71. f = fp.read(92) # read 23 * 4 bytes
  72. t = struct.unpack(">23f", f) # try big-endian first
  73. hdrlen = isSpiderHeader(t)
  74. if hdrlen == 0:
  75. t = struct.unpack("<23f", f) # little-endian
  76. hdrlen = isSpiderHeader(t)
  77. return hdrlen
  78. class SpiderImageFile(ImageFile.ImageFile):
  79. format = "SPIDER"
  80. format_description = "Spider 2D image"
  81. _close_exclusive_fp_after_loading = False
  82. def _open(self):
  83. # check header
  84. n = 27 * 4 # read 27 float values
  85. f = self.fp.read(n)
  86. try:
  87. self.bigendian = 1
  88. t = struct.unpack(">27f", f) # try big-endian first
  89. hdrlen = isSpiderHeader(t)
  90. if hdrlen == 0:
  91. self.bigendian = 0
  92. t = struct.unpack("<27f", f) # little-endian
  93. hdrlen = isSpiderHeader(t)
  94. if hdrlen == 0:
  95. msg = "not a valid Spider file"
  96. raise SyntaxError(msg)
  97. except struct.error as e:
  98. msg = "not a valid Spider file"
  99. raise SyntaxError(msg) from e
  100. h = (99,) + t # add 1 value : spider header index starts at 1
  101. iform = int(h[5])
  102. if iform != 1:
  103. msg = "not a Spider 2D image"
  104. raise SyntaxError(msg)
  105. self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
  106. self.istack = int(h[24])
  107. self.imgnumber = int(h[27])
  108. if self.istack == 0 and self.imgnumber == 0:
  109. # stk=0, img=0: a regular 2D image
  110. offset = hdrlen
  111. self._nimages = 1
  112. elif self.istack > 0 and self.imgnumber == 0:
  113. # stk>0, img=0: Opening the stack for the first time
  114. self.imgbytes = int(h[12]) * int(h[2]) * 4
  115. self.hdrlen = hdrlen
  116. self._nimages = int(h[26])
  117. # Point to the first image in the stack
  118. offset = hdrlen * 2
  119. self.imgnumber = 1
  120. elif self.istack == 0 and self.imgnumber > 0:
  121. # stk=0, img>0: an image within the stack
  122. offset = hdrlen + self.stkoffset
  123. self.istack = 2 # So Image knows it's still a stack
  124. else:
  125. msg = "inconsistent stack header values"
  126. raise SyntaxError(msg)
  127. if self.bigendian:
  128. self.rawmode = "F;32BF"
  129. else:
  130. self.rawmode = "F;32F"
  131. self._mode = "F"
  132. self.tile = [("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))]
  133. self._fp = self.fp # FIXME: hack
  134. @property
  135. def n_frames(self):
  136. return self._nimages
  137. @property
  138. def is_animated(self):
  139. return self._nimages > 1
  140. # 1st image index is zero (although SPIDER imgnumber starts at 1)
  141. def tell(self):
  142. if self.imgnumber < 1:
  143. return 0
  144. else:
  145. return self.imgnumber - 1
  146. def seek(self, frame):
  147. if self.istack == 0:
  148. msg = "attempt to seek in a non-stack file"
  149. raise EOFError(msg)
  150. if not self._seek_check(frame):
  151. return
  152. self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
  153. self.fp = self._fp
  154. self.fp.seek(self.stkoffset)
  155. self._open()
  156. # returns a byte image after rescaling to 0..255
  157. def convert2byte(self, depth=255):
  158. (minimum, maximum) = self.getextrema()
  159. m = 1
  160. if maximum != minimum:
  161. m = depth / (maximum - minimum)
  162. b = -m * minimum
  163. return self.point(lambda i, m=m, b=b: i * m + b).convert("L")
  164. # returns a ImageTk.PhotoImage object, after rescaling to 0..255
  165. def tkPhotoImage(self):
  166. from . import ImageTk
  167. return ImageTk.PhotoImage(self.convert2byte(), palette=256)
  168. # --------------------------------------------------------------------
  169. # Image series
  170. # given a list of filenames, return a list of images
  171. def loadImageSeries(filelist=None):
  172. """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
  173. if filelist is None or len(filelist) < 1:
  174. return
  175. imglist = []
  176. for img in filelist:
  177. if not os.path.exists(img):
  178. print(f"unable to find {img}")
  179. continue
  180. try:
  181. with Image.open(img) as im:
  182. im = im.convert2byte()
  183. except Exception:
  184. if not isSpiderImage(img):
  185. print(img + " is not a Spider image file")
  186. continue
  187. im.info["filename"] = img
  188. imglist.append(im)
  189. return imglist
  190. # --------------------------------------------------------------------
  191. # For saving images in Spider format
  192. def makeSpiderHeader(im):
  193. nsam, nrow = im.size
  194. lenbyt = nsam * 4 # There are labrec records in the header
  195. labrec = int(1024 / lenbyt)
  196. if 1024 % lenbyt != 0:
  197. labrec += 1
  198. labbyt = labrec * lenbyt
  199. nvalues = int(labbyt / 4)
  200. if nvalues < 23:
  201. return []
  202. hdr = []
  203. for i in range(nvalues):
  204. hdr.append(0.0)
  205. # NB these are Fortran indices
  206. hdr[1] = 1.0 # nslice (=1 for an image)
  207. hdr[2] = float(nrow) # number of rows per slice
  208. hdr[3] = float(nrow) # number of records in the image
  209. hdr[5] = 1.0 # iform for 2D image
  210. hdr[12] = float(nsam) # number of pixels per line
  211. hdr[13] = float(labrec) # number of records in file header
  212. hdr[22] = float(labbyt) # total number of bytes in header
  213. hdr[23] = float(lenbyt) # record length in bytes
  214. # adjust for Fortran indexing
  215. hdr = hdr[1:]
  216. hdr.append(0.0)
  217. # pack binary data into a string
  218. return [struct.pack("f", v) for v in hdr]
  219. def _save(im, fp, filename):
  220. if im.mode[0] != "F":
  221. im = im.convert("F")
  222. hdr = makeSpiderHeader(im)
  223. if len(hdr) < 256:
  224. msg = "Error creating Spider header"
  225. raise OSError(msg)
  226. # write the SPIDER header
  227. fp.writelines(hdr)
  228. rawmode = "F;32NF" # 32-bit native floating point
  229. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
  230. def _save_spider(im, fp, filename):
  231. # get the filename extension and register it with Image
  232. ext = os.path.splitext(filename)[1]
  233. Image.register_extension(SpiderImageFile.format, ext)
  234. _save(im, fp, filename)
  235. # --------------------------------------------------------------------
  236. Image.register_open(SpiderImageFile.format, SpiderImageFile)
  237. Image.register_save(SpiderImageFile.format, _save_spider)
  238. if __name__ == "__main__":
  239. if len(sys.argv) < 2:
  240. print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
  241. sys.exit()
  242. filename = sys.argv[1]
  243. if not isSpiderImage(filename):
  244. print("input image must be in Spider format")
  245. sys.exit()
  246. with Image.open(filename) as im:
  247. print("image: " + str(im))
  248. print("format: " + str(im.format))
  249. print("size: " + str(im.size))
  250. print("mode: " + str(im.mode))
  251. print("max, min: ", end=" ")
  252. print(im.getextrema())
  253. if len(sys.argv) > 2:
  254. outfile = sys.argv[2]
  255. # perform some image operation
  256. im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  257. print(
  258. f"saving a flipped version of {os.path.basename(filename)} "
  259. f"as {outfile} "
  260. )
  261. im.save(outfile, SpiderImageFile.format)