SpiderImagePlugin.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. import os
  34. import struct
  35. import sys
  36. from PIL 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. raise SyntaxError("not a valid Spider file")
  96. except struct.error as e:
  97. raise SyntaxError("not a valid Spider file") from e
  98. h = (99,) + t # add 1 value : spider header index starts at 1
  99. iform = int(h[5])
  100. if iform != 1:
  101. raise SyntaxError("not a Spider 2D image")
  102. self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
  103. self.istack = int(h[24])
  104. self.imgnumber = int(h[27])
  105. if self.istack == 0 and self.imgnumber == 0:
  106. # stk=0, img=0: a regular 2D image
  107. offset = hdrlen
  108. self._nimages = 1
  109. elif self.istack > 0 and self.imgnumber == 0:
  110. # stk>0, img=0: Opening the stack for the first time
  111. self.imgbytes = int(h[12]) * int(h[2]) * 4
  112. self.hdrlen = hdrlen
  113. self._nimages = int(h[26])
  114. # Point to the first image in the stack
  115. offset = hdrlen * 2
  116. self.imgnumber = 1
  117. elif self.istack == 0 and self.imgnumber > 0:
  118. # stk=0, img>0: an image within the stack
  119. offset = hdrlen + self.stkoffset
  120. self.istack = 2 # So Image knows it's still a stack
  121. else:
  122. raise SyntaxError("inconsistent stack header values")
  123. if self.bigendian:
  124. self.rawmode = "F;32BF"
  125. else:
  126. self.rawmode = "F;32F"
  127. self.mode = "F"
  128. self.tile = [("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))]
  129. self.__fp = self.fp # FIXME: hack
  130. @property
  131. def n_frames(self):
  132. return self._nimages
  133. @property
  134. def is_animated(self):
  135. return self._nimages > 1
  136. # 1st image index is zero (although SPIDER imgnumber starts at 1)
  137. def tell(self):
  138. if self.imgnumber < 1:
  139. return 0
  140. else:
  141. return self.imgnumber - 1
  142. def seek(self, frame):
  143. if self.istack == 0:
  144. raise EOFError("attempt to seek in a non-stack file")
  145. if not self._seek_check(frame):
  146. return
  147. self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
  148. self.fp = self.__fp
  149. self.fp.seek(self.stkoffset)
  150. self._open()
  151. # returns a byte image after rescaling to 0..255
  152. def convert2byte(self, depth=255):
  153. (minimum, maximum) = self.getextrema()
  154. m = 1
  155. if maximum != minimum:
  156. m = depth / (maximum - minimum)
  157. b = -m * minimum
  158. return self.point(lambda i, m=m, b=b: i * m + b).convert("L")
  159. # returns a ImageTk.PhotoImage object, after rescaling to 0..255
  160. def tkPhotoImage(self):
  161. from PIL import ImageTk
  162. return ImageTk.PhotoImage(self.convert2byte(), palette=256)
  163. def _close__fp(self):
  164. try:
  165. if self.__fp != self.fp:
  166. self.__fp.close()
  167. except AttributeError:
  168. pass
  169. finally:
  170. self.__fp = None
  171. # --------------------------------------------------------------------
  172. # Image series
  173. # given a list of filenames, return a list of images
  174. def loadImageSeries(filelist=None):
  175. """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
  176. if filelist is None or len(filelist) < 1:
  177. return
  178. imglist = []
  179. for img in filelist:
  180. if not os.path.exists(img):
  181. print(f"unable to find {img}")
  182. continue
  183. try:
  184. with Image.open(img) as im:
  185. im = im.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 OSError("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: python3 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. with Image.open(filename) as im:
  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. f"saving a flipped version of {os.path.basename(filename)} "
  263. f"as {outfile} "
  264. )
  265. im.save(outfile, SpiderImageFile.format)