/imageio/functions.py

https://bitbucket.org/grizzlynyo/imageio
Python | 454 lines | 329 code | 21 blank | 104 comment | 16 complexity | 1cf92ae59e74f6e3580f80035e482183 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, imageio contributers
  3. # imageio is distributed under the terms of the (new) BSD License.
  4. """
  5. These functions are the main interface for the imageio user. They
  6. provide a common interface to read and save image data for a large
  7. variety of formats. All read and save functions accept keyword
  8. arguments, which are passed on to the format that does the actual work.
  9. To see what keyword arguments are supported by a specific format, use
  10. the imageio.help function.
  11. Functions for reading
  12. ---------------------
  13. * imageio.imread - read an image from the specified uri
  14. * imageio.mimread - read a series of images from the specified uri
  15. * imageio.volread - read a volume from the specified uri
  16. * imageio.mvolsave - save a series of volumes to the specified uri
  17. Functions for saving
  18. --------------------
  19. * imageio.imsave - save an image to the specified uri
  20. * imageio.mimsave - save a series of images to the specified uri
  21. * imageio.volsave - save a volume to the specified uri
  22. * imageio.mvolread - read a series of volumes from the specified uri
  23. More control
  24. ------------
  25. For a larger degree of control, imageio provides the functions
  26. imageio.read and imageio.save. They respectively return an
  27. imageio.Format.Reader and an imageio.Format.Writer object, which can
  28. be used to read/save data and meta data in a more controlled manner.
  29. This also allows specific scientific formats to be exposed in a way
  30. that best suits that file-format.
  31. """
  32. import sys
  33. import os
  34. import numpy as np
  35. import imageio
  36. from imageio import formats
  37. from imageio import base
  38. # Taken from six.py
  39. PY3 = sys.version_info[0] == 3
  40. if PY3:
  41. string_types = str,
  42. text_type = str
  43. binary_type = bytes
  44. else:
  45. string_types = basestring,
  46. text_type = unicode
  47. binary_type = str
  48. def help(name=None):
  49. """ help(name=None)
  50. Print the documentation of the format specified by name, or a list
  51. of supported formats if name is omitted.
  52. The specified name can be the name of a format, a filename extension,
  53. or a full filename.
  54. See also the :doc:`formats page <formats>`.
  55. """
  56. if not name:
  57. print(formats)
  58. else:
  59. print(formats[name])
  60. # todo: implement inforead function?
  61. ## Base functions that return a reader/writer
  62. def read(uri, format=None, expect=None, **kwargs):
  63. """ read(uri, format=None, expect=None, **kwargs)
  64. Returns a reader object which can be used to read data and info
  65. from the specified file.
  66. Parameters
  67. ----------
  68. uri : {str, bytes}
  69. The resource to load the image from. This can be a normal
  70. filename, a file in a zipfile, an http/ftp address, a file
  71. object, or the raw bytes.
  72. format : str
  73. The format to use to read the file. By default imageio selects
  74. the appropriate for you based on the filename and its contents.
  75. expect : {imageio.EXPECT_IM, imageio.EXPECT_MIM, imageio.EXPECT_VOL}
  76. Used to give the reader a hint on what the user expects. Optional.
  77. Further keyword arguments are passed to the reader. See imageio.help
  78. to see what arguments are available for a particular format.
  79. """
  80. # Create request object
  81. request = imageio.request.ReadRequest(uri, expect, **kwargs)
  82. # Get format
  83. if format is not None:
  84. format = formats[format]
  85. else:
  86. format = formats.search_read_format(request)
  87. if format is None:
  88. raise ValueError('Could not find a format to read the specified file.')
  89. # Return its reader object
  90. return format.read(request)
  91. def save(uri, format=None, expect=None, **kwargs):
  92. """ save(uri, format=None, expect=None, **kwargs)
  93. Returns a writer object which can be used to save data and info
  94. to the specified file.
  95. Parameters
  96. ----------
  97. uri : str
  98. The resource to save the image to. This can be a normal
  99. filename, a file in a zipfile, or imageio.RETURN_BYTES, in which
  100. case the raw bytes are returned.
  101. format : str
  102. The format to use to read the file. By default imageio selects
  103. the appropriate for you based on the filename.
  104. expect : {imageio.EXPECT_IM, imageio.EXPECT_MIM, imageio.EXPECT_VOL}
  105. Used to give the writer a hint on what kind of data to expect. Optional.
  106. Further keyword arguments are passed to the reader. See imageio.help
  107. to see what arguments are available for a particular format.
  108. """
  109. # Create request object
  110. request = imageio.request.WriteRequest(uri, expect, **kwargs)
  111. # Get format
  112. if format is not None:
  113. format = formats[format]
  114. else:
  115. format = formats.search_save_format(request)
  116. if format is None:
  117. raise ValueError('Could not find a format to save the specified file.')
  118. # Return its writer object
  119. return format.save(request)
  120. ## Images
  121. def imread(uri, format=None, **kwargs):
  122. """ imread(uri, format=None, **kwargs)
  123. Reads an image from the specified file. Returns a numpy array, which
  124. comes with a dict of meta data at its 'meta' attribute.
  125. Parameters
  126. ----------
  127. uri : {str, bytes}
  128. The resource to load the image from. This can be a normal
  129. filename, a file in a zipfile, an http/ftp address, a file
  130. object, or the raw bytes.
  131. format : str
  132. The format to use to read the file. By default imageio selects
  133. the appropriate for you based on the filename and its contents.
  134. Further keyword arguments are passed to the reader. See imageio.help
  135. to see what arguments are available for a particular format.
  136. """
  137. # Get reader and read first
  138. reader = read(uri, format, imageio.EXPECT_IM, **kwargs)
  139. with reader:
  140. return reader.get_data(0)
  141. # todo: add meta attribbute to easily provide meta data
  142. # now, the only way to give meta data is via the imageio.Image class
  143. def imsave(uri, im, format=None, **kwargs):
  144. """ imsave(uri, im, format=None, **kwargs)
  145. Save an image to the specified file.
  146. Parameters
  147. ----------
  148. uri : str
  149. The resource to save the image to. This can be a normal
  150. filename, a file in a zipfile, or imageio.RETURN_BYTES, in which
  151. case the raw bytes are returned.
  152. im : numpy.ndarray
  153. The image data. Must be NxM, NxMx3 or NxMx4.
  154. format : str
  155. The format to use to read the file. By default imageio selects
  156. the appropriate for you based on the filename and its contents.
  157. Further keyword arguments are passed to the reader. See imageio.help
  158. to see what arguments are available for a particular format.
  159. """
  160. # Test image
  161. if isinstance(im, np.ndarray):
  162. if im.ndim == 2:
  163. pass
  164. elif im.ndim == 3 and im.shape[2] in [3,4]:
  165. pass
  166. else:
  167. raise ValueError('Image must be 2D (grayscale, RGB, or RGBA).')
  168. else:
  169. raise ValueError('Image must be a numpy array.')
  170. # Get writer and write first
  171. writer = save(uri, format, imageio.EXPECT_IM, **kwargs)
  172. with writer:
  173. writer.append_data(im)
  174. # Return a result if there is any
  175. return writer.request.get_result()
  176. ## Multiple images
  177. def mimread(uri, format=None, **kwargs):
  178. """ mimread(uri, format=None, **kwargs)
  179. Reads multiple images from the specified file. Returns a list of
  180. numpy arrays, each with a dict of meta data at its 'meta' attribute.
  181. Parameters
  182. ----------
  183. uri : {str, bytes}
  184. The resource to load the images from. This can be a normal
  185. filename, a file in a zipfile, an http/ftp address, a file
  186. object, or the raw bytes.
  187. format : str
  188. The format to use to read the file. By default imageio selects
  189. the appropriate for you based on the filename and its contents.
  190. Further keyword arguments are passed to the reader. See imageio.help
  191. to see what arguments are available for a particular format.
  192. """
  193. # Get reader and read all
  194. reader = read(uri, format, imageio.EXPECT_MIM, **kwargs)
  195. with reader:
  196. return [im for im in reader]
  197. def mimsave(uri, ims, format=None, **kwargs):
  198. """ mimsave(uri, ims, format=None, **kwargs)
  199. Save multiple images to the specified file.
  200. Parameters
  201. ----------
  202. uri : str
  203. The resource to save the images to. This can be a normal
  204. filename, a file in a zipfile, or imageio.RETURN_BYTES, in which
  205. case the raw bytes are returned.
  206. ims : sequence of numpy arrays
  207. The image data. Each array must be NxM, NxMx3 or NxMx4.
  208. format : str
  209. The format to use to read the file. By default imageio selects
  210. the appropriate for you based on the filename and its contents.
  211. Further keyword arguments are passed to the reader. See imageio.help
  212. to see what arguments are available for a particular format.
  213. """
  214. # Get writer
  215. writer = save(uri, format, imageio.EXPECT_MIM, **kwargs)
  216. with writer:
  217. # Iterate over images (ims may be a generator)
  218. for im in ims:
  219. # Test image
  220. if isinstance(im, np.ndarray):
  221. if im.ndim == 2:
  222. pass
  223. elif im.ndim == 3 and im.shape[2] in [3,4]:
  224. pass
  225. else:
  226. raise ValueError('Image must be 2D (grayscale, RGB, or RGBA).')
  227. else:
  228. raise ValueError('Image must be a numpy array.')
  229. # Add image
  230. writer.append_data(im)
  231. # Return a result if there is any
  232. return writer.request.get_result()
  233. ## Volumes
  234. def volread(uri, format=None, **kwargs):
  235. """ volread(uri, format=None, **kwargs)
  236. Reads a volume from the specified file. Returns a numpy array, which
  237. comes with a dict of meta data at its 'meta' attribute.
  238. Parameters
  239. ----------
  240. uri : {str, bytes}
  241. The resource to load the volume from. This can be a normal
  242. filename, a file in a zipfile, an http/ftp address, a file
  243. object, or the raw bytes.
  244. format : str
  245. The format to use to read the file. By default imageio selects
  246. the appropriate for you based on the filename and its contents.
  247. Further keyword arguments are passed to the reader. See imageio.help
  248. to see what arguments are available for a particular format.
  249. """
  250. # Get reader and read first
  251. reader = read(uri, format, imageio.EXPECT_VOL, **kwargs)
  252. with reader:
  253. return reader.get_data(0)
  254. def volsave(uri, im, format, **kwargs):
  255. """ volsave(uri, vol, format=None, **kwargs)
  256. Save a volume to the specified file.
  257. Parameters
  258. ----------
  259. uri : str
  260. The resource to save the image to. This can be a normal
  261. filename, a file in a zipfile, or imageio.RETURN_BYTES, in which
  262. case the raw bytes are returned.
  263. vol : numpy.ndarray
  264. The image data. Must be NxMxL (or NxMxLxK if each voxel is a tuple).
  265. format : str
  266. The format to use to read the file. By default imageio selects
  267. the appropriate for you based on the filename and its contents.
  268. Further keyword arguments are passed to the reader. See imageio.help
  269. to see what arguments are available for a particular format.
  270. """
  271. # Test image
  272. if isinstance(im, np.ndarray):
  273. if im.ndim == 3:
  274. pass
  275. elif im.ndim == 4 and im.shape[3] < 32: # How large can a tuple be?
  276. pass
  277. else:
  278. raise ValueError('Image must be 3D, or 4D if each voxel is a tuple.')
  279. else:
  280. raise ValueError('Image must be a numpy array.')
  281. # Get writer and write first
  282. writer = save(uri, format, imageio.EXPECT_VOL, **kwargs)
  283. with writer:
  284. writer.append_data(im)
  285. # Return a result if there is any
  286. return writer.request.get_result()
  287. ## Multiple volumes
  288. def mvolread(uri, format, **kwargs):
  289. """ mvolread(uri, format=None, **kwargs)
  290. Reads multiple volumes from the specified file. Returns a list of
  291. numpy arrays, each with a dict of meta data at its 'meta' attribute.
  292. Parameters
  293. ----------
  294. uri : {str, bytes}
  295. The resource to load the volumes from. This can be a normal
  296. filename, a file in a zipfile, an http/ftp address, a file
  297. object, or the raw bytes.
  298. format : str
  299. The format to use to read the file. By default imageio selects
  300. the appropriate for you based on the filename and its contents.
  301. Further keyword arguments are passed to the reader. See imageio.help
  302. to see what arguments are available for a particular format.
  303. """
  304. # Get reader and read all
  305. reader = read(uri, format, imageio.EXPECT_MVOL **kwargs)
  306. with reader:
  307. return [im for im in reader]
  308. def mvolsave(uri, ims, format, **kwargs):
  309. """ mvolsave(uri, vols, format=None, **kwargs)
  310. Save multiple volumes to the specified file.
  311. Parameters
  312. ----------
  313. uri : str
  314. The resource to save the volumes to. This can be a normal
  315. filename, a file in a zipfile, or imageio.RETURN_BYTES, in which
  316. case the raw bytes are returned.
  317. ims : sequence of numpy arrays
  318. The image data. Each array must be NxMxL (or NxMxLxK if each
  319. voxel is a tuple).
  320. format : str
  321. The format to use to read the file. By default imageio selects
  322. the appropriate for you based on the filename and its contents.
  323. Further keyword arguments are passed to the reader. See imageio.help
  324. to see what arguments are available for a particular format.
  325. """
  326. # Get writer
  327. writer = save(uri, format, imageio.EXPECT_MVOL, **kwargs)
  328. with writer:
  329. # Iterate over images (ims may be a generator)
  330. for im in ims:
  331. # Test image
  332. if isinstance(im, np.ndarray):
  333. if im.ndim == 3:
  334. pass
  335. elif im.ndim == 4 and im.shape[3] < 32: # How large can a tuple be?
  336. pass
  337. else:
  338. raise ValueError('Image must be 3D, or 4D if each voxel is a tuple.')
  339. else:
  340. raise ValueError('Image must be a numpy array.')
  341. # Add image
  342. writer.append_data(im)
  343. # Return a result if there is any
  344. return writer.request.get_result()