SpiderImagePlugin.py 9.2 KB

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