mirror of
https://github.com/wassname/scikit-image.git
synced 2026-06-30 01:57:21 +08:00
b6dcf3c336
Update Travis build to use Anaconda Travis updates and fixes More travis fixes Another travis attempt Revert changes Use PIL and Pillow Refactor travis into 4 different builds Fix activation error Remove explicit mpl in build_versions.py Make matplotlib an explicit requirement Rearrange travis Make pillow a hard requirement Try again to make Pillow optional Fix bash syntax error Fix bash syntax error Bump required cython version More rearrangments Remove mpl from build_versions, rearrange travis Fix version check Make matplotlib explicit again Conda install into test env Check for proper install Allow tests to skip if networkx is not available Allow tests to skip if networkx is not available Try swapping pillow for matplotlib Allow tests to pass when matplotlib is not present Remove matplotlib from build_versions Print PIL version Get pillow from PIP Allow tests to skip if matplotlib is not present. Allow tests to skip if networkx is not present. travis fix Remove unused mpl import that caused test error Use nose-cov and do not run doctests without optional libs Bump required numpy version and fix nose calls Make overlay test repeatable bump numpy version again Move low-end numpy to python 2.7 Play with minimum versions Add version requirements and use functions Add version requirements and use functions Allow require to skip a test More implementation of require decorator Update require decorator and clean up tests Only use requires decorator when needed Fix python3 error in version_requirements Fix build errors Fix handling of require with tests More fixes for require handler Use latest miniconda Fix more build errors Fix another dict comprehension and travis file. Fix missing imports Fix dictionary again Fix import warning Fix last failing test on 2.6 Skip doc examples on python2.6 Do not run doctests on python2.6 Fix typo in travis.yml Make numpy-1.6 compatibility changes Use numpy-1.6 in travis python2.6 Add tests for version requirements Fix line noise in PR Add additional io plugins Fix simpleitk test. Fix python 3 error in freeimage_plugin. Install imread in Travis. Put matplotlib settings in XDG recommended directory Fix formatting in travis yml Fix formatting in travis yml Make sure to close PIL file atexit Fix name of apt package xcftools Fix pil fp closing Fix matplotlibrc creation Only download SimpleITK on py2x, run coverage on py27 Fix travis yml syntax error Run coveralls on py2.7 Install SimpleITK on py3.3 and run coverage on py3.3 Make simpleitk install quiet Use standard nose and clean up incantation Fix travis yml syntax error Put in miniconda workout for libc error. Fix imread plugin. Fix travis syntax Remove unused import Remove miniconda libpng in favor of system png Fix imread install and move libm removal to after optional pkg install. Fix png header copy in travis yml Another attempt to use png headers Debug freeimage Add jpeg library for freeimage and debug imread. More debug for imread and freeimage More freeimage and imread debugging More debugging Use correct paths for test env Make sure imread is tied to libpng15 Add a TODO note for simpleitk test causing error. Fix typo in yml Cleanup and add more comments to travis yml Update comment Try and add 3.2 support. Docstring formatting Add more travis comments. Try numpy 1.6 on python 2.7 Fix travis syntax error Rename CONDA to ENV for clarity Alias python on python 3.2 Use python 3.2 as the system python Clean up libfreeimage install Fix order on py3.2 pre_install Move old numpy back to py26 Use the appropriate python calls. Debug 3.2 build. Update comment Fix syntax error Another fix for syntax error. Install scipy after downloading import tools More debugging for py32 Do not install conda on py3.2 (duh) Fix typo in travis yml Fix py32 qt install, separate pyfits and imread to find error Fix syntax error and front-load option lib check for debug pyfits is not supported in py3.2, try imread now imread is also not supported on py3.2 install imread before pyfits to show relationship with libs Make pip builds quiet Minor formatting to retrigger build Allow simpleitk to fail to download without breaking the build Use travis_retry for SimpleITK See what breaks when we keep libm in Now remove libm again
141 lines
3.8 KiB
Python
141 lines
3.8 KiB
Python
__all__ = ['imread']
|
|
|
|
import numpy as np
|
|
|
|
try:
|
|
from PIL import Image
|
|
except ImportError:
|
|
raise ImportError("The Python Image Library could not be found. "
|
|
"Please refer to "
|
|
"https://pypi.python.org/pypi/Pillow/ (or "
|
|
"http://pypi.python.org/pypi/PIL/) "
|
|
"for further instructions.")
|
|
|
|
from skimage.util import img_as_ubyte
|
|
|
|
from six import string_types
|
|
|
|
|
|
def imread(fname, dtype=None):
|
|
"""Load an image from file.
|
|
|
|
"""
|
|
im = Image.open(fname)
|
|
fp = im.fp
|
|
if im.mode == 'P':
|
|
if _palette_is_grayscale(im):
|
|
im = im.convert('L')
|
|
else:
|
|
im = im.convert('RGB')
|
|
elif im.mode == '1':
|
|
im = im.convert('L')
|
|
elif im.mode.startswith('I;16'):
|
|
shape = im.size
|
|
dtype = '>u2' if im.mode.endswith('B') else '<u2'
|
|
im = np.fromstring(im.tostring(), dtype)
|
|
im.shape = shape[::-1]
|
|
elif 'A' in im.mode:
|
|
im = im.convert('RGBA')
|
|
im = np.array(im, dtype=dtype)
|
|
fp.close()
|
|
return im
|
|
|
|
|
|
def _palette_is_grayscale(pil_image):
|
|
"""Return True if PIL image in palette mode is grayscale.
|
|
|
|
Parameters
|
|
----------
|
|
pil_image : PIL image
|
|
PIL Image that is in Palette mode.
|
|
|
|
Returns
|
|
-------
|
|
is_grayscale : bool
|
|
True if all colors in image palette are gray.
|
|
"""
|
|
assert pil_image.mode == 'P'
|
|
# get palette as an array with R, G, B columns
|
|
palette = np.asarray(pil_image.getpalette()).reshape((256, 3))
|
|
# Not all palette colors are used; unused colors have junk values.
|
|
start, stop = pil_image.getextrema()
|
|
valid_palette = palette[start:stop]
|
|
# Image is grayscale if channel differences (R - G and G - B)
|
|
# are all zero.
|
|
return np.allclose(np.diff(valid_palette), 0)
|
|
|
|
|
|
def imsave(fname, arr, format_str=None):
|
|
"""Save an image to disk.
|
|
|
|
Parameters
|
|
----------
|
|
fname : str or file-like object
|
|
Name of destination file.
|
|
arr : ndarray of uint8 or float
|
|
Array (image) to save. Arrays of data-type uint8 should have
|
|
values in [0, 255], whereas floating-point arrays must be
|
|
in [0, 1].
|
|
format_str: str
|
|
Format to save as, this is defaulted to PNG if using a file-like
|
|
object; this will be derived from the extension if fname is a string
|
|
|
|
Notes
|
|
-----
|
|
Currently, only 8-bit precision is supported.
|
|
|
|
"""
|
|
arr = np.asarray(arr).squeeze()
|
|
|
|
if arr.ndim not in (2, 3):
|
|
raise ValueError("Invalid shape for image array: %s" % arr.shape)
|
|
|
|
if arr.ndim == 3:
|
|
if arr.shape[2] not in (3, 4):
|
|
raise ValueError("Invalid number of channels in image array.")
|
|
|
|
# Image is floating point, assume in [0, 1]
|
|
if np.issubdtype(arr.dtype, float):
|
|
arr = arr * 255
|
|
|
|
arr = arr.astype(np.uint8)
|
|
|
|
if arr.ndim == 2:
|
|
mode = 'L'
|
|
|
|
elif arr.shape[2] in (3, 4):
|
|
mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]]
|
|
|
|
# Force all integers to bytes
|
|
arr = arr.astype(np.uint8)
|
|
|
|
# default to PNG if file-like object
|
|
if not isinstance(fname, string_types) and format_str is None:
|
|
format_str = "PNG"
|
|
|
|
try:
|
|
img = Image.frombytes(mode, (arr.shape[1], arr.shape[0]),
|
|
arr.tostring())
|
|
except AttributeError:
|
|
img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]),
|
|
arr.tostring())
|
|
|
|
img.save(fname, format=format_str)
|
|
|
|
|
|
def imshow(arr):
|
|
"""Display an image, using PIL's default display command.
|
|
|
|
Parameters
|
|
----------
|
|
arr : ndarray
|
|
Image to display. Images of dtype float are assumed to be in
|
|
[0, 1]. Images of dtype uint8 are in [0, 255].
|
|
|
|
"""
|
|
Image.fromarray(img_as_ubyte(arr)).show()
|
|
|
|
|
|
def _app_show():
|
|
pass
|