_fetchers.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. """Standard test images.
  2. For more images, see
  3. - http://sipi.usc.edu/database/database.php
  4. """
  5. import numpy as np
  6. import shutil
  7. from ..util.dtype import img_as_bool
  8. from ._registry import registry, registry_urls
  9. from .. import __version__
  10. import os.path as osp
  11. import os
  12. _LEGACY_DATA_DIR = osp.dirname(__file__)
  13. _DISTRIBUTION_DIR = osp.dirname(_LEGACY_DATA_DIR)
  14. try:
  15. from pooch import file_hash
  16. except ModuleNotFoundError:
  17. # Function taken from
  18. # https://github.com/fatiando/pooch/blob/master/pooch/utils.py
  19. def file_hash(fname, alg="sha256"):
  20. """
  21. Calculate the hash of a given file.
  22. Useful for checking if a file has changed or been corrupted.
  23. Parameters
  24. ----------
  25. fname : str
  26. The name of the file.
  27. alg : str
  28. The type of the hashing algorithm
  29. Returns
  30. -------
  31. hash : str
  32. The hash of the file.
  33. Examples
  34. --------
  35. >>> fname = "test-file-for-hash.txt"
  36. >>> with open(fname, "w") as f:
  37. ... __ = f.write("content of the file")
  38. >>> print(file_hash(fname))
  39. 0fc74468e6a9a829f103d069aeb2bb4f8646bad58bf146bb0e3379b759ec4a00
  40. >>> import os
  41. >>> os.remove(fname)
  42. """
  43. import hashlib
  44. if alg not in hashlib.algorithms_available:
  45. raise ValueError(f'Algorithm \'{alg}\' not available in hashlib')
  46. # Calculate the hash in chunks to avoid overloading the memory
  47. chunksize = 65536
  48. hasher = hashlib.new(alg)
  49. with open(fname, "rb") as fin:
  50. buff = fin.read(chunksize)
  51. while buff:
  52. hasher.update(buff)
  53. buff = fin.read(chunksize)
  54. return hasher.hexdigest()
  55. def _has_hash(path, expected_hash):
  56. """Check if the provided path has the expected hash."""
  57. if not osp.exists(path):
  58. return False
  59. return file_hash(path) == expected_hash
  60. def _create_image_fetcher(prefix=None):
  61. try:
  62. import pooch
  63. # older versions of Pooch don't have a __version__ attribute
  64. if not hasattr(pooch, '__version__'):
  65. retry = {}
  66. else:
  67. retry = {'retry_if_failed': 3}
  68. except ImportError:
  69. # Without pooch, fallback on the standard data directory
  70. # which for now, includes a few limited data samples
  71. return None, _LEGACY_DATA_DIR
  72. # Pooch expects a `+` to exist in development versions.
  73. # Since scikit-image doesn't follow that convention, we have to manually
  74. # remove `.dev` with a `+` if it exists.
  75. # This helps pooch understand that it should look in master
  76. # to find the required files
  77. if '+git' in __version__:
  78. skimage_version_for_pooch = __version__.replace('.dev0+git', '+git')
  79. else:
  80. skimage_version_for_pooch = __version__.replace('.dev', '+')
  81. if '+' in skimage_version_for_pooch:
  82. if prefix is not None:
  83. url = (
  84. "https://github.com/scikit-image/scikit-image/raw/"
  85. "{version}/tests/skimage/"
  86. )
  87. else:
  88. url = (
  89. "https://github.com/scikit-image/scikit-image/raw/"
  90. "{version}/src/skimage/"
  91. )
  92. else:
  93. if prefix is not None:
  94. url = (
  95. "https://github.com/scikit-image/scikit-image/raw/"
  96. "v{version}/tests/skimage/"
  97. )
  98. else:
  99. url = (
  100. "https://github.com/scikit-image/scikit-image/raw/"
  101. "v{version}/src/skimage/"
  102. )
  103. # Create a new friend to manage your sample data storage
  104. image_fetcher = pooch.create(
  105. # Pooch uses appdirs to select an appropriate directory for the cache
  106. # on each platform.
  107. # https://github.com/ActiveState/appdirs
  108. # On linux this converges to
  109. # '$HOME/.cache/scikit-image'
  110. # With a version qualifier
  111. path=pooch.os_cache("scikit-image"),
  112. base_url=url,
  113. version=skimage_version_for_pooch,
  114. version_dev="main",
  115. env="SKIMAGE_DATADIR",
  116. registry=registry,
  117. urls=registry_urls,
  118. # Note: this should read `retry_if_failed=3,`, but we generate that
  119. # dynamically at import time above, in case installed pooch is a less
  120. # recent version
  121. **retry,
  122. )
  123. data_dir = osp.join(str(image_fetcher.abspath), 'data')
  124. return image_fetcher, data_dir
  125. _image_fetcher, data_dir = _create_image_fetcher(prefix='tests')
  126. def _skip_pytest_case_requiring_pooch(data_filename):
  127. """If a test case is calling pooch, skip it.
  128. This running the test suite in environments without internet
  129. access, skipping only the tests that try to fetch external data.
  130. """
  131. # Check if pytest is currently running.
  132. # Packagers might use pytest to run the tests suite, but may not
  133. # want to run it online with pooch as a dependency.
  134. # As such, we will avoid failing the test, and silently skipping it.
  135. if 'PYTEST_CURRENT_TEST' in os.environ:
  136. # https://docs.pytest.org/en/latest/example/simple.html#pytest-current-test-environment-variable
  137. import pytest
  138. # Pytest skip raises an exception that allows the
  139. # tests to be skipped
  140. pytest.skip(f'Unable to download {data_filename}', allow_module_level=True)
  141. def _ensure_cache_dir(*, target_dir):
  142. """Prepare local cache directory if it doesn't exist already.
  143. Creates::
  144. /path/to/target_dir/
  145. └─ data/
  146. └─ README.txt
  147. """
  148. os.makedirs(osp.join(target_dir, "data"), exist_ok=True)
  149. readme_src = osp.join(_DISTRIBUTION_DIR, "data/README.txt")
  150. readme_dest = osp.join(target_dir, "data/README.txt")
  151. if not osp.exists(readme_dest):
  152. shutil.copy2(readme_src, readme_dest)
  153. def _fetch(data_filename, prefix=None):
  154. """Fetch a given data file from either the local cache or the repository.
  155. This function provides the path location of the data file given
  156. its name in the scikit-image repository. If a data file is not included in the
  157. distribution and pooch is available, it is downloaded and cached.
  158. Parameters
  159. ----------
  160. data_filename : str
  161. Name of the file in the scikit-image repository. e.g.
  162. 'restoration/camera_rl.npy'.
  163. Returns
  164. -------
  165. file_path : str
  166. Path of the local file.
  167. Raises
  168. ------
  169. KeyError:
  170. If the filename is not known to the scikit-image distribution.
  171. ModuleNotFoundError:
  172. If the filename is known to the scikit-image distribution but pooch
  173. is not installed.
  174. ConnectionError:
  175. If scikit-image is unable to connect to the internet but the
  176. dataset has not been downloaded yet.
  177. """
  178. if prefix is not None:
  179. return osp.join("tests", "skimage", data_filename)
  180. expected_hash = registry[data_filename]
  181. if _image_fetcher is None:
  182. cache_dir = osp.dirname(data_dir)
  183. else:
  184. cache_dir = str(_image_fetcher.abspath)
  185. # Case 1: the file is already cached in `data_cache_dir`
  186. cached_file_path = osp.join(cache_dir, data_filename)
  187. if _has_hash(cached_file_path, expected_hash):
  188. # Nothing to be done, file is where it is expected to be
  189. return cached_file_path
  190. # Case 2: file is present in `legacy_data_dir`
  191. legacy_file_path = osp.join(_DISTRIBUTION_DIR, data_filename)
  192. if _has_hash(legacy_file_path, expected_hash):
  193. return legacy_file_path
  194. # Case 3: file is not present locally
  195. if _image_fetcher is None:
  196. _skip_pytest_case_requiring_pooch(data_filename)
  197. raise ModuleNotFoundError(
  198. "The requested file is part of the scikit-image distribution, "
  199. "but requires the installation of an optional dependency, pooch. "
  200. "To install pooch, use your preferred python package manager. "
  201. "Follow installation instruction found at "
  202. "https://scikit-image.org/docs/stable/user_guide/install.html"
  203. )
  204. # Download the data with pooch which caches it automatically
  205. _ensure_cache_dir(target_dir=cache_dir)
  206. try:
  207. cached_file_path = _image_fetcher.fetch(data_filename)
  208. return cached_file_path
  209. except ConnectionError as err:
  210. _skip_pytest_case_requiring_pooch(data_filename)
  211. # If we decide in the future to suppress the underlying 'requests'
  212. # error, change this to `raise ... from None`. See PEP 3134.
  213. raise ConnectionError(
  214. 'Tried to download a scikit-image dataset, but no internet '
  215. 'connection is available. To avoid this message in the '
  216. 'future, try `skimage.data.download_all()` when you are '
  217. 'connected to the internet.'
  218. ) from err
  219. def download_all(directory=None):
  220. """Download all datasets for use with scikit-image offline.
  221. Scikit-image datasets are no longer shipped with the library by default.
  222. This allows us to use higher quality datasets, while keeping the
  223. library download size small.
  224. This function requires the installation of an optional dependency, pooch,
  225. to download the full dataset. Follow installation instruction found at
  226. https://scikit-image.org/docs/stable/user_guide/install.html
  227. Call this function to download all sample images making them available
  228. offline on your machine.
  229. Parameters
  230. ----------
  231. directory : path-like, optional
  232. The directory where the dataset should be stored.
  233. Raises
  234. ------
  235. ModuleNotFoundError:
  236. If pooch is not install, this error will be raised.
  237. Notes
  238. -----
  239. scikit-image will only search for images stored in the default directory.
  240. Only specify the directory if you wish to download the images to your own
  241. folder for a particular reason. You can access the location of the default
  242. data directory by inspecting the variable ``skimage.data.data_dir``.
  243. """
  244. if _image_fetcher is None:
  245. raise ModuleNotFoundError(
  246. "To download all package data, scikit-image needs an optional "
  247. "dependency, pooch."
  248. "To install pooch, follow our installation instructions found at "
  249. "https://scikit-image.org/docs/stable/user_guide/install.html"
  250. )
  251. # Consider moving this kind of logic to Pooch
  252. old_dir = _image_fetcher.path
  253. try:
  254. if directory is not None:
  255. directory = osp.expanduser(directory)
  256. _image_fetcher.path = directory
  257. _ensure_cache_dir(target_dir=_image_fetcher.path)
  258. for data_filename in _image_fetcher.registry:
  259. file_path = _fetch(data_filename)
  260. # Copy to `directory` or implicit cache if it is not already there
  261. if not file_path.startswith(str(_image_fetcher.path)):
  262. dest_path = osp.join(_image_fetcher.path, data_filename)
  263. os.makedirs(osp.dirname(dest_path), exist_ok=True)
  264. shutil.copy2(file_path, dest_path)
  265. finally:
  266. _image_fetcher.path = old_dir
  267. def lbp_frontal_face_cascade_filename():
  268. """Return the path to the XML file containing the weak classifier cascade.
  269. These classifiers were trained using LBP features. The file is part
  270. of the OpenCV repository [1]_.
  271. References
  272. ----------
  273. .. [1] OpenCV lbpcascade trained files
  274. https://github.com/opencv/opencv/tree/master/data/lbpcascades
  275. """
  276. return _fetch('data/lbpcascade_frontalface_opencv.xml')
  277. def _load(f, as_gray=False):
  278. """Load an image file located in the data directory.
  279. Parameters
  280. ----------
  281. f : string
  282. File name.
  283. as_gray : bool, optional
  284. Whether to convert the image to grayscale.
  285. Returns
  286. -------
  287. img : ndarray
  288. Image loaded from ``skimage.data_dir``.
  289. """
  290. # importing io is quite slow since it scans all the backends
  291. # we lazy import it here
  292. from ..io import imread
  293. return imread(_fetch(f), as_gray=as_gray)
  294. def camera():
  295. """Gray-level "camera" image.
  296. Can be used for segmentation and denoising examples.
  297. Returns
  298. -------
  299. camera : (512, 512) uint8 ndarray
  300. Camera image.
  301. Notes
  302. -----
  303. No copyright restrictions. CC0 by the photographer (Lav Varshney).
  304. .. versionchanged:: 0.18
  305. This image was replaced due to copyright restrictions. For more
  306. information, please see [1]_.
  307. References
  308. ----------
  309. .. [1] https://github.com/scikit-image/scikit-image/issues/3927
  310. """
  311. return _load("data/camera.png")
  312. def eagle():
  313. """A golden eagle.
  314. Suitable for examples on segmentation, Hough transforms, and corner
  315. detection.
  316. Notes
  317. -----
  318. No copyright restrictions. CC0 by the photographer (Dayane Machado).
  319. Returns
  320. -------
  321. eagle : (2019, 1826) uint8 ndarray
  322. Eagle image.
  323. """
  324. return _load("data/eagle.png")
  325. def astronaut():
  326. """Color image of the astronaut Eileen Collins.
  327. Photograph of Eileen Collins, an American astronaut. She was selected
  328. as an astronaut in 1992 and first piloted the space shuttle STS-63 in
  329. 1995. She retired in 2006 after spending a total of 38 days, 8 hours
  330. and 10 minutes in outer space.
  331. This image was downloaded from the NASA Great Images database
  332. <https://flic.kr/p/r9qvLn>`__.
  333. No known copyright restrictions, released into the public domain.
  334. Returns
  335. -------
  336. astronaut : (512, 512, 3) uint8 ndarray
  337. Astronaut image.
  338. """
  339. return _load("data/astronaut.png")
  340. def brick():
  341. """Brick wall.
  342. Returns
  343. -------
  344. brick : (512, 512) uint8 image
  345. A small section of a brick wall.
  346. Notes
  347. -----
  348. The original image was downloaded from
  349. `CC0Textures <https://cc0textures.com/view.php?tex=Bricks25>`_ and licensed
  350. under the Creative Commons CC0 License.
  351. A perspective transform was then applied to the image, prior to
  352. rotating it by 90 degrees, cropping and scaling it to obtain the final
  353. image.
  354. """
  355. """
  356. The following code was used to obtain the final image.
  357. >>> import sys; print(sys.version)
  358. >>> import platform; print(platform.platform())
  359. >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
  360. >>> import numpy; print(f'numpy version: {numpy.__version__}')
  361. >>> import imageio; print(f'imageio version {imageio.__version__}')
  362. 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21)
  363. [GCC 7.3.0]
  364. Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
  365. scikit-image version: 0.16.dev0
  366. numpy version: 1.16.4
  367. imageio version 2.4.1
  368. >>> import requests
  369. >>> import zipfile
  370. >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Bricks25/%5B2K%5DBricks25.zip'
  371. >>> r = requests.get(url)
  372. >>> with open('[2K]Bricks25.zip', 'bw') as f:
  373. ... f.write(r.content)
  374. >>> with zipfile.ZipFile('[2K]Bricks25.zip') as z:
  375. ... z.extract('Bricks25_col.jpg')
  376. >>> from numpy.linalg import inv
  377. >>> from skimage.transform import rescale, warp, rotate
  378. >>> from skimage.color import rgb2gray
  379. >>> from imageio import imread, imwrite
  380. >>> from skimage import img_as_ubyte
  381. >>> import numpy as np
  382. >>> # Obtained playing around with GIMP 2.10 with their perspective tool
  383. >>> H = inv(np.asarray([[ 0.54764, -0.00219, 0],
  384. ... [-0.12822, 0.54688, 0],
  385. ... [-0.00022, 0, 1]]))
  386. >>> brick_orig = imread('Bricks25_col.jpg')
  387. >>> brick = warp(brick_orig, H)
  388. >>> brick = rescale(brick[:1024, :1024], (0.5, 0.5, 1))
  389. >>> brick = rotate(brick, -90)
  390. >>> imwrite('brick.png', img_as_ubyte(rgb2gray(brick)))
  391. """
  392. return _load("data/brick.png", as_gray=True)
  393. def grass():
  394. """Grass.
  395. Returns
  396. -------
  397. grass : (512, 512) uint8 image
  398. Some grass.
  399. Notes
  400. -----
  401. The original image was downloaded from
  402. `DeviantArt <https://www.deviantart.com/linolafett/art/Grass-01-434853879>`__
  403. and licensed under the Creative Commons CC0 License.
  404. The downloaded image was cropped to include a region of ``(512, 512)``
  405. pixels around the top left corner, converted to grayscale, then to uint8
  406. prior to saving the result in PNG format.
  407. """
  408. """
  409. The following code was used to obtain the final image.
  410. >>> import sys; print(sys.version)
  411. >>> import platform; print(platform.platform())
  412. >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
  413. >>> import numpy; print(f'numpy version: {numpy.__version__}')
  414. >>> import imageio; print(f'imageio version {imageio.__version__}')
  415. 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21)
  416. [GCC 7.3.0]
  417. Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
  418. scikit-image version: 0.16.dev0
  419. numpy version: 1.16.4
  420. imageio version 2.4.1
  421. >>> import requests
  422. >>> import zipfile
  423. >>> url = 'https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/a407467e-4ff0-49f1-923f-c9e388e84612/d76wfef-2878b78d-5dce-43f9-be36-26ec9bc0df3b.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2E0MDc0NjdlLTRmZjAtNDlmMS05MjNmLWM5ZTM4OGU4NDYxMlwvZDc2d2ZlZi0yODc4Yjc4ZC01ZGNlLTQzZjktYmUzNi0yNmVjOWJjMGRmM2IuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.98hIcOTCqXWQ67Ec5bM5eovKEn2p91mWB3uedH61ynI'
  424. >>> r = requests.get(url)
  425. >>> with open('grass_orig.jpg', 'bw') as f:
  426. ... f.write(r.content)
  427. >>> grass_orig = imageio.imread('grass_orig.jpg')
  428. >>> grass = skimage.img_as_ubyte(skimage.color.rgb2gray(grass_orig[:512, :512]))
  429. >>> imageio.imwrite('grass.png', grass)
  430. """
  431. return _load("data/grass.png", as_gray=True)
  432. def gravel():
  433. """Gravel
  434. Returns
  435. -------
  436. gravel : (512, 512) uint8 image
  437. Grayscale gravel sample.
  438. Notes
  439. -----
  440. The original image was downloaded from
  441. `CC0Textures <https://cc0textures.com/view.php?tex=Gravel04>`__ and
  442. licensed under the Creative Commons CC0 License.
  443. The downloaded image was then rescaled to ``(1024, 1024)``, then the
  444. top left ``(512, 512)`` pixel region was cropped prior to converting the
  445. image to grayscale and uint8 data type. The result was saved using the
  446. PNG format.
  447. """
  448. """
  449. The following code was used to obtain the final image.
  450. >>> import sys; print(sys.version)
  451. >>> import platform; print(platform.platform())
  452. >>> import skimage; print(f'scikit-image version: {skimage.__version__}')
  453. >>> import numpy; print(f'numpy version: {numpy.__version__}')
  454. >>> import imageio; print(f'imageio version {imageio.__version__}')
  455. 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21)
  456. [GCC 7.3.0]
  457. Linux-5.0.0-20-generic-x86_64-with-debian-buster-sid
  458. scikit-image version: 0.16.dev0
  459. numpy version: 1.16.4
  460. imageio version 2.4.1
  461. >>> import requests
  462. >>> import zipfile
  463. >>> url = 'https://cdn.struffelproductions.com/file/cc0textures/Gravel04/%5B2K%5DGravel04.zip'
  464. >>> r = requests.get(url)
  465. >>> with open('[2K]Gravel04.zip', 'bw') as f:
  466. ... f.write(r.content)
  467. >>> with zipfile.ZipFile('[2K]Gravel04.zip') as z:
  468. ... z.extract('Gravel04_col.jpg')
  469. >>> from skimage.transform import resize
  470. >>> gravel_orig = imageio.imread('Gravel04_col.jpg')
  471. >>> gravel = resize(gravel_orig, (1024, 1024))
  472. >>> gravel = skimage.img_as_ubyte(skimage.color.rgb2gray(gravel[:512, :512]))
  473. >>> imageio.imwrite('gravel.png', gravel)
  474. """
  475. return _load("data/gravel.png", as_gray=True)
  476. def text():
  477. """Gray-level "text" image used for corner detection.
  478. Notes
  479. -----
  480. This image was downloaded from Wikipedia
  481. <https://en.wikipedia.org/wiki/File:Corner.png>`__.
  482. No known copyright restrictions, released into the public domain.
  483. Returns
  484. -------
  485. text : (172, 448) uint8 ndarray
  486. Text image.
  487. """
  488. return _load("data/text.png")
  489. def checkerboard():
  490. """Checkerboard image.
  491. Checkerboards are often used in image calibration, since the
  492. corner-points are easy to locate. Because of the many parallel
  493. edges, they also visualise distortions particularly well.
  494. Returns
  495. -------
  496. checkerboard : (200, 200) uint8 ndarray
  497. Checkerboard image.
  498. """
  499. return _load("data/chessboard_GRAY.png")
  500. def cells3d():
  501. """3D fluorescence microscopy image of cells.
  502. The returned data is a 3D multichannel array with dimensions provided in
  503. ``(z, c, y, x)`` order. Each voxel has a size of ``(0.29 0.26 0.26)``
  504. micrometer. Channel 0 contains cell membranes, channel 1 contains nuclei.
  505. Returns
  506. -------
  507. cells3d: (60, 2, 256, 256) uint16 ndarray
  508. The volumetric images of cells taken with an optical microscope.
  509. Notes
  510. -----
  511. The data for this was provided by the Allen Institute for Cell Science.
  512. It has been downsampled by a factor of 4 in the row and column dimensions
  513. to reduce computational time.
  514. The microscope reports the following voxel spacing in microns:
  515. * Original voxel size is ``(0.290, 0.065, 0.065)``.
  516. * Scaling factor is ``(1, 4, 4)`` in each dimension.
  517. * After rescaling the voxel size is ``(0.29 0.26 0.26)``.
  518. """
  519. return _load("data/cells3d.tif")
  520. def human_mitosis():
  521. """Image of human cells undergoing mitosis.
  522. Returns
  523. -------
  524. human_mitosis: (512, 512) uint8 ndarray
  525. Data of human cells undergoing mitosis taken during the preparation
  526. of the manuscript in [1]_.
  527. Notes
  528. -----
  529. Copyright David Root. Licensed under CC-0 [2]_.
  530. References
  531. ----------
  532. .. [1] Moffat J, Grueneberg DA, Yang X, Kim SY, Kloepfer AM, Hinkle G,
  533. Piqani B, Eisenhaure TM, Luo B, Grenier JK, Carpenter AE, Foo SY,
  534. Stewart SA, Stockwell BR, Hacohen N, Hahn WC, Lander ES,
  535. Sabatini DM, Root DE (2006) A lentiviral RNAi library for human and
  536. mouse genes applied to an arrayed viral high-content screen. Cell,
  537. 124(6):1283-98 / :DOI: `10.1016/j.cell.2006.01.040` PMID 16564017
  538. .. [2] GitHub licensing discussion
  539. https://github.com/CellProfiler/examples/issues/41
  540. """
  541. return _load('data/mitosis.tif')
  542. def cell():
  543. """Cell floating in saline.
  544. This is a quantitative phase image retrieved from a digital hologram using
  545. the Python library ``qpformat``. The image shows a cell with high phase
  546. value, above the background phase.
  547. Because of a banding pattern artifact in the background, this image is a
  548. good test of thresholding algorithms. The pixel spacing is 0.107 µm.
  549. These data were part of a comparison between several refractive index
  550. retrieval techniques for spherical objects as part of [1]_.
  551. This image is CC0, dedicated to the public domain. You may copy, modify, or
  552. distribute it without asking permission.
  553. Returns
  554. -------
  555. cell : (660, 550) uint8 array
  556. Image of a cell.
  557. References
  558. ----------
  559. .. [1] Paul Müller, Mirjam Schürmann, Salvatore Girardo, Gheorghe Cojoc,
  560. and Jochen Guck. "Accurate evaluation of size and refractive index
  561. for spherical objects in quantitative phase imaging." Optics Express
  562. 26(8): 10729-10743 (2018). :DOI:`10.1364/OE.26.010729`
  563. """
  564. return _load('data/cell.png')
  565. def coins():
  566. """Greek coins from Pompeii.
  567. This image shows several coins outlined against a gray background.
  568. It is especially useful in, e.g. segmentation tests, where
  569. individual objects need to be identified against a background.
  570. The background shares enough grey levels with the coins that a
  571. simple segmentation is not sufficient.
  572. Notes
  573. -----
  574. This image was downloaded from the
  575. `Brooklyn Museum Collection
  576. <https://www.brooklynmuseum.org/opencollection/archives/image/51611>`__.
  577. No known copyright restrictions.
  578. Returns
  579. -------
  580. coins : (303, 384) uint8 ndarray
  581. Coins image.
  582. """
  583. return _load("data/coins.png")
  584. def kidney():
  585. """Mouse kidney tissue.
  586. This biological tissue on a pre-prepared slide was imaged with confocal
  587. fluorescence microscopy (Nikon C1 inverted microscope).
  588. Image shape is (16, 512, 512, 3). That is 512x512 pixels in X-Y,
  589. 16 image slices in Z, and 3 color channels
  590. (emission wavelengths 450nm, 515nm, and 605nm, respectively).
  591. Real-space voxel size is 1.24 microns in X-Y, and 1.25 microns in Z.
  592. Data type is unsigned 16-bit integers.
  593. Notes
  594. -----
  595. This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in
  596. 2018.
  597. License: CC0
  598. Returns
  599. -------
  600. kidney : (16, 512, 512, 3) uint16 ndarray
  601. Kidney 3D multichannel image.
  602. """
  603. return _load("data/kidney.tif")
  604. def lily():
  605. """Lily of the valley plant stem.
  606. This plant stem on a pre-prepared slide was imaged with confocal
  607. fluorescence microscopy (Nikon C1 inverted microscope).
  608. Image shape is (922, 922, 4). That is 922x922 pixels in X-Y,
  609. with 4 color channels.
  610. Real-space voxel size is 1.24 microns in X-Y.
  611. Data type is unsigned 16-bit integers.
  612. Notes
  613. -----
  614. This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in
  615. 2018.
  616. License: CC0
  617. Returns
  618. -------
  619. lily : (922, 922, 4) uint16 ndarray
  620. Lily 2D multichannel image.
  621. """
  622. return _load("data/lily.tif")
  623. def logo():
  624. """Scikit-image logo, a RGBA image.
  625. Returns
  626. -------
  627. logo : (500, 500, 4) uint8 ndarray
  628. Logo image.
  629. """
  630. return _load("data/logo.png")
  631. def microaneurysms():
  632. """Gray-level "microaneurysms" image.
  633. Detail from an image of the retina (green channel).
  634. The image is a crop of image 07_dr.JPG from the
  635. High-Resolution Fundus (HRF) Image Database:
  636. https://www5.cs.fau.de/research/data/fundus-images/
  637. Notes
  638. -----
  639. No copyright restrictions. CC0 given by owner (Andreas Maier).
  640. Returns
  641. -------
  642. microaneurysms : (102, 102) uint8 ndarray
  643. Retina image with lesions.
  644. References
  645. ----------
  646. .. [1] Budai, A., Bock, R, Maier, A., Hornegger, J.,
  647. Michelson, G. (2013). Robust Vessel Segmentation in Fundus
  648. Images. International Journal of Biomedical Imaging, vol. 2013,
  649. 2013.
  650. :DOI:`10.1155/2013/154860`
  651. """
  652. return _load("data/microaneurysms.png")
  653. def moon():
  654. """Surface of the moon.
  655. This low-contrast image of the surface of the moon is useful for
  656. illustrating histogram equalization and contrast stretching.
  657. Returns
  658. -------
  659. moon : (512, 512) uint8 ndarray
  660. Moon image.
  661. """
  662. return _load("data/moon.png")
  663. def page():
  664. """Scanned page.
  665. This image of printed text is useful for demonstrations requiring uneven
  666. background illumination.
  667. Returns
  668. -------
  669. page : (191, 384) uint8 ndarray
  670. Page image.
  671. """
  672. return _load("data/page.png")
  673. def horse():
  674. """Black and white silhouette of a horse.
  675. This image was downloaded from
  676. `openclipart <http://openclipart.org/detail/158377/horse-by-marauder>`
  677. No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)).
  678. Returns
  679. -------
  680. horse : (328, 400) bool ndarray
  681. Horse image.
  682. """
  683. return img_as_bool(_load("data/horse.png", as_gray=True))
  684. def clock():
  685. """Motion blurred clock.
  686. This photograph of a wall clock was taken while moving the camera in an
  687. approximately horizontal direction. It may be used to illustrate
  688. inverse filters and deconvolution.
  689. Released into the public domain by the photographer (Stefan van der Walt).
  690. Returns
  691. -------
  692. clock : (300, 400) uint8 ndarray
  693. Clock image.
  694. """
  695. return _load("data/clock_motion.png")
  696. def immunohistochemistry():
  697. """Immunohistochemical (IHC) staining with hematoxylin counterstaining.
  698. This picture shows colonic glands where the IHC expression of FHL2 protein
  699. is revealed with DAB. Hematoxylin counterstaining is applied to enhance the
  700. negative parts of the tissue.
  701. This image was acquired at the Center for Microscopy And Molecular Imaging
  702. (CMMI).
  703. No known copyright restrictions.
  704. Returns
  705. -------
  706. immunohistochemistry : (512, 512, 3) uint8 ndarray
  707. Immunohistochemistry image.
  708. """
  709. return _load("data/ihc.png")
  710. def chelsea():
  711. """Chelsea the cat.
  712. An example with texture, prominent edges in horizontal and diagonal
  713. directions, as well as features of differing scales.
  714. Notes
  715. -----
  716. No copyright restrictions. CC0 by the photographer (Stefan van der Walt).
  717. Returns
  718. -------
  719. chelsea : (300, 451, 3) uint8 ndarray
  720. Chelsea image.
  721. """
  722. return _load("data/chelsea.png")
  723. # Define an alias for chelsea that is more descriptive.
  724. cat = chelsea
  725. def coffee():
  726. """Coffee cup.
  727. This photograph is courtesy of Pikolo Espresso Bar.
  728. It contains several elliptical shapes as well as varying texture (smooth
  729. porcelain to coarse wood grain).
  730. Notes
  731. -----
  732. No copyright restrictions. CC0 by the photographer (Rachel Michetti).
  733. Returns
  734. -------
  735. coffee : (400, 600, 3) uint8 ndarray
  736. Coffee image.
  737. """
  738. return _load("data/coffee.png")
  739. def hubble_deep_field():
  740. """Hubble eXtreme Deep Field.
  741. This photograph contains the Hubble Telescope's farthest ever view of
  742. the universe. It can be useful as an example for multi-scale
  743. detection.
  744. Notes
  745. -----
  746. This image was downloaded from
  747. `HubbleSite
  748. <http://hubblesite.org/newscenter/archive/releases/2012/37/image/a/>`__.
  749. The image was captured by NASA and `may be freely used in the public domain
  750. <http://www.nasa.gov/audience/formedia/features/MP_Photo_Guidelines.html>`_.
  751. Returns
  752. -------
  753. hubble_deep_field : (872, 1000, 3) uint8 ndarray
  754. Hubble deep field image.
  755. """
  756. return _load("data/hubble_deep_field.jpg")
  757. def retina():
  758. """Human retina.
  759. This image of a retina is useful for demonstrations requiring circular
  760. images.
  761. Notes
  762. -----
  763. This image was downloaded from
  764. `wikimedia <https://commons.wikimedia.org/wiki/File:Fundus_photograph_of_normal_left_eye.jpg>`.
  765. This file is made available under the Creative Commons CC0 1.0 Universal
  766. Public Domain Dedication.
  767. References
  768. ----------
  769. .. [1] Häggström, Mikael (2014). "Medical gallery of Mikael Häggström 2014".
  770. WikiJournal of Medicine 1 (2). :DOI:`10.15347/wjm/2014.008`.
  771. ISSN 2002-4436. Public Domain
  772. Returns
  773. -------
  774. retina : (1411, 1411, 3) uint8 ndarray
  775. Retina image in RGB.
  776. """
  777. return _load("data/retina.jpg")
  778. def shepp_logan_phantom():
  779. """Shepp Logan Phantom.
  780. References
  781. ----------
  782. .. [1] L. A. Shepp and B. F. Logan, "The Fourier reconstruction of a head
  783. section," in IEEE Transactions on Nuclear Science, vol. 21,
  784. no. 3, pp. 21-43, June 1974. :DOI:`10.1109/TNS.1974.6499235`
  785. Returns
  786. -------
  787. phantom : (400, 400) float64 image
  788. Image of the Shepp-Logan phantom in grayscale.
  789. """
  790. return _load("data/phantom.png", as_gray=True)
  791. def colorwheel():
  792. """Color Wheel.
  793. Returns
  794. -------
  795. colorwheel : (370, 371, 3) uint8 image
  796. A colorwheel.
  797. """
  798. return _load("data/color.png")
  799. def palisades_of_vogt():
  800. """Return image sequence of in-vivo tissue showing the palisades of Vogt.
  801. In the human eye, the palisades of Vogt are normal features of the corneal
  802. limbus, which is the border between the cornea and the sclera (i.e., the
  803. white of the eye).
  804. In the image sequence, there are some dark spots due to the presence of
  805. dust on the reference mirror.
  806. Returns
  807. -------
  808. palisades_of_vogt: (60, 1440, 1440) uint16 ndarray
  809. Notes
  810. -----
  811. See info under `in-vivo-cornea-spots.tif` at
  812. https://gitlab.com/scikit-image/data/-/blob/master/README.md#data.
  813. """
  814. return _load('data/palisades_of_vogt.tif')
  815. def rocket():
  816. """Launch photo of DSCOVR on Falcon 9 by SpaceX.
  817. This is the launch photo of Falcon 9 carrying DSCOVR lifted off from
  818. SpaceX's Launch Complex 40 at Cape Canaveral Air Force Station, FL.
  819. Notes
  820. -----
  821. This image was downloaded from
  822. `SpaceX Photos
  823. <https://www.flickr.com/photos/spacexphotos/16511594820/in/photostream/>`__.
  824. The image was captured by SpaceX and `released in the public domain
  825. <http://arstechnica.com/tech-policy/2015/03/elon-musk-puts-spacex-photos-into-the-public-domain/>`_.
  826. Returns
  827. -------
  828. rocket : (427, 640, 3) uint8 ndarray
  829. Rocket image.
  830. """
  831. return _load("data/rocket.jpg")
  832. def stereo_motorcycle():
  833. """Rectified stereo image pair with ground-truth disparities.
  834. The two images are rectified such that every pixel in the left image has
  835. its corresponding pixel on the same scanline in the right image. That means
  836. that both images are warped such that they have the same orientation but a
  837. horizontal spatial offset (baseline). The ground-truth pixel offset in
  838. column direction is specified by the included disparity map.
  839. The two images are part of the Middlebury 2014 stereo benchmark. The
  840. dataset was created by Nera Nesic, Porter Westling, Xi Wang, York Kitajima,
  841. Greg Krathwohl, and Daniel Scharstein at Middlebury College. A detailed
  842. description of the acquisition process can be found in [1]_.
  843. The images included here are down-sampled versions of the default exposure
  844. images in the benchmark. The images are down-sampled by a factor of 4 using
  845. the function `skimage.transform.downscale_local_mean`. The calibration data
  846. in the following and the included ground-truth disparity map are valid for
  847. the down-sampled images::
  848. Focal length: 994.978px
  849. Principal point x: 311.193px
  850. Principal point y: 254.877px
  851. Principal point dx: 31.086px
  852. Baseline: 193.001mm
  853. Returns
  854. -------
  855. img_left : (500, 741, 3) uint8 ndarray
  856. Left stereo image.
  857. img_right : (500, 741, 3) uint8 ndarray
  858. Right stereo image.
  859. disp : (500, 741, 3) float ndarray
  860. Ground-truth disparity map, where each value describes the offset in
  861. column direction between corresponding pixels in the left and the right
  862. stereo images. E.g. the corresponding pixel of
  863. ``img_left[10, 10 + disp[10, 10]]`` is ``img_right[10, 10]``.
  864. NaNs denote pixels in the left image that do not have ground-truth.
  865. Notes
  866. -----
  867. The original resolution images, images with different exposure and
  868. lighting, and ground-truth depth maps can be found at the Middlebury
  869. website [2]_.
  870. References
  871. ----------
  872. .. [1] D. Scharstein, H. Hirschmueller, Y. Kitajima, G. Krathwohl, N.
  873. Nesic, X. Wang, and P. Westling. High-resolution stereo datasets
  874. with subpixel-accurate ground truth. In German Conference on Pattern
  875. Recognition (GCPR 2014), Muenster, Germany, September 2014.
  876. .. [2] http://vision.middlebury.edu/stereo/data/scenes2014/
  877. """
  878. filename = _fetch("data/motorcycle_disp.npz")
  879. # np.load of npz file holds onto open file handle.
  880. with np.load(filename) as data:
  881. disp = data['arr_0']
  882. return (_load("data/motorcycle_left.png"), _load("data/motorcycle_right.png"), disp)
  883. def lfw_subset():
  884. """Subset of data from the LFW dataset.
  885. This database is a subset of the LFW database containing:
  886. * 100 faces
  887. * 100 non-faces
  888. The full dataset is available at [2]_.
  889. Returns
  890. -------
  891. images : (200, 25, 25) uint8 ndarray
  892. 100 first images are faces and subsequent 100 are non-faces.
  893. Notes
  894. -----
  895. The faces were randomly selected from the LFW dataset and the non-faces
  896. were extracted from the background of the same dataset. The cropped ROIs
  897. have been resized to a 25 x 25 pixels.
  898. References
  899. ----------
  900. .. [1] Huang, G., Mattar, M., Lee, H., & Learned-Miller, E. G. (2012).
  901. Learning to align from scratch. In Advances in Neural Information
  902. Processing Systems (pp. 764-772).
  903. .. [2] http://vis-www.cs.umass.edu/lfw/
  904. """
  905. return np.load(_fetch('data/lfw_subset.npy'))
  906. def skin():
  907. """Microscopy image of dermis and epidermis (skin layers).
  908. Hematoxylin and eosin stained slide at 10x of normal epidermis and dermis
  909. with a benign intradermal nevus.
  910. Notes
  911. -----
  912. This image requires an Internet connection the first time it is called,
  913. and to have the ``pooch`` package installed, in order to fetch the image
  914. file from the scikit-image datasets repository.
  915. The source of this image is
  916. https://en.wikipedia.org/wiki/File:Normal_Epidermis_and_Dermis_with_Intradermal_Nevus_10x.JPG
  917. The image was released in the public domain by its author Kilbad.
  918. Returns
  919. -------
  920. skin : (960, 1280, 3) RGB image of uint8
  921. """
  922. return _load('data/skin.jpg')
  923. def nickel_solidification():
  924. """Image sequence of synchrotron x-radiographs showing the rapid
  925. solidification of a nickel alloy sample.
  926. Returns
  927. -------
  928. nickel_solidification: (11, 384, 512) uint16 ndarray
  929. Notes
  930. -----
  931. See info under `nickel_solidification.tif` at
  932. https://gitlab.com/scikit-image/data/-/blob/master/README.md#data.
  933. """
  934. return _load('data/solidification.tif')
  935. def protein_transport():
  936. """Microscopy image sequence with fluorescence tagging of proteins
  937. re-localizing from the cytoplasmic area to the nuclear envelope.
  938. Returns
  939. -------
  940. protein_transport: (15, 2, 180, 183) uint8 ndarray
  941. Notes
  942. -----
  943. See info under `NPCsingleNucleus.tif` at
  944. https://gitlab.com/scikit-image/data/-/blob/master/README.md#data.
  945. """
  946. return _load('data/protein_transport.tif')
  947. def brain():
  948. """Subset of data from the University of North Carolina Volume Rendering
  949. Test Data Set.
  950. The full dataset is available at [1]_.
  951. Returns
  952. -------
  953. image : (10, 256, 256) uint16 ndarray
  954. Notes
  955. -----
  956. The 3D volume consists of 10 layers from the larger volume.
  957. References
  958. ----------
  959. .. [1] https://graphics.stanford.edu/data/voldata/
  960. """
  961. return _load("data/brain.tiff")
  962. def vortex():
  963. """Case B1 image pair from the first PIV challenge.
  964. Returns
  965. -------
  966. image0, image1 : (512, 512) grayscale images
  967. A pair of images featuring synthetic moving particles.
  968. Notes
  969. -----
  970. This image was licensed as CC0 by its author, Prof. Koji Okamoto, with
  971. thanks to Prof. Jun Sakakibara, who maintains the PIV Challenge site.
  972. References
  973. ----------
  974. .. [1] Particle Image Velocimetry (PIV) Challenge site
  975. http://pivchallenge.org
  976. .. [2] 1st PIV challenge Case B: http://pivchallenge.org/pub/index.html#b
  977. """
  978. return (
  979. _load('data/pivchallenge-B-B001_1.tif'),
  980. _load('data/pivchallenge-B-B001_2.tif'),
  981. )