From 5d276146ee8762569888976145cefc0360cd79a9 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 10 Feb 2012 15:34:26 -0800 Subject: [PATCH 01/10] BUG: Fix FreeImage tests. --- skimage/io/{_plugins => tests}/test_freeimage.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) rename skimage/io/{_plugins => tests}/test_freeimage.py (67%) diff --git a/skimage/io/_plugins/test_freeimage.py b/skimage/io/tests/test_freeimage.py similarity index 67% rename from skimage/io/_plugins/test_freeimage.py rename to skimage/io/tests/test_freeimage.py index 8ecf0aa9..4cbf9830 100644 --- a/skimage/io/_plugins/test_freeimage.py +++ b/skimage/io/tests/test_freeimage.py @@ -1,25 +1,32 @@ import os import skimage as si import skimage.io as sio -import skimage.io._plugins.freeimage_plugin as fi from numpy.testing import * +from numpy.testing.decorators import skipif +try: + import skimage.io._plugins.freeimage_plugin as fi + FI_available = True +except OSError: + FI_available = False +@skipif(not FI_available) def test_read(): sio.use_plugin('freeimage', 'imread') img = sio.imread(os.path.join(si.data_dir, 'color.png')) assert img.shape == (370, 371, 3) assert all(img[274,135] == [0, 130, 253]) +@skipif(not FI_available) def test_metadata(): meta = fi.read_metadata(os.path.join(si.data_dir, 'multipage.tif')) - assert meta[('EXIF_MAIN', 'BitsPerSample')] == 8 + assert meta[('EXIF_MAIN', 'Orientation')] == 1 assert meta[('EXIF_MAIN', 'Software')].startswith('ImageMagick') meta = fi.read_multipage_metadata(os.path.join(si.data_dir, 'multipage.tif')) assert len(meta) == 2 - assert meta[0][('EXIF_MAIN', 'BitsPerSample')] == 8 + assert meta[0][('EXIF_MAIN', 'Orientation')] == 1 assert meta[1][('EXIF_MAIN', 'Software')].startswith('ImageMagick') From 0f750372878e369c77e8f87dad1b1d6f200e5c91 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 10 Feb 2012 02:53:29 -0800 Subject: [PATCH 02/10] DOC: Add FreeImage as optional dependency. --- DEPENDS.txt | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/DEPENDS.txt b/DEPENDS.txt index b8942556..2792870b 100644 --- a/DEPENDS.txt +++ b/DEPENDS.txt @@ -11,9 +11,9 @@ examples in the documentation. Known build errors ------------------ On Windows, the error ``Error:unable to find vcvarsall.bat`` means that -distutils is not correctly configured to use the C compiler. Edit (create +distutils is not correctly configured to use the C compiler. Modify (or create, if not existing) the configuration file ``distutils.cfg`` (located for -example at ``C:\Python26\Lib\distutils\distutils.cfg``) to be:: +example at ``C:\Python26\Lib\distutils\distutils.cfg``) to contain:: [build] compiler=mingw32 @@ -21,13 +21,16 @@ example at ``C:\Python26\Lib\distutils\distutils.cfg``) to be:: Usage Requirements ------------------ -* `Scipy `_ +* `Scipy `__ Optional Requirements --------------------- You can use this scikit with the basic requirements listed above, but some functionality is only available with the following installed: -`PyQt4 `_ - The `qt` plugin that provides ``imshow(x, fancy=True)`` and `skivi`. +`PyQt4 `__ + The ``qt`` plugin that provides ``imshow(x, fancy=True)`` and `skivi`. +`FreeImage `__ + The ``freeimage`` plugin provides support for reading various types of + image file formats, including multi-page TIFFs. From 96af068860ad7ac0cc65c12c31c66dc7b74c5ba0 Mon Sep 17 00:00:00 2001 From: Brian Holt Date: Fri, 10 Feb 2012 18:16:49 +0000 Subject: [PATCH 03/10] added HOG example --- doc/examples/plot_hog.py | 105 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 doc/examples/plot_hog.py diff --git a/doc/examples/plot_hog.py b/doc/examples/plot_hog.py new file mode 100644 index 00000000..da82cd83 --- /dev/null +++ b/doc/examples/plot_hog.py @@ -0,0 +1,105 @@ +r''' +=============================== +Histogram of Oriented Gradients +=============================== + +The Histogram of Oriented Gradient (HOG) feature descriptor is popular +for object detection +`__. + +In the following example, we compute the HOG descriptor and display +a visualisation. + +Algorithm overview +------------------ + +Compute a Histogram of Oriented Gradients (HOG) by + 1) (optional) global image normalisation + 2) computing the gradient image in x and y + 3) computing gradient histograms + 3) normalising across blocks + 4) flattening into a feature vector + +The first stage applies an optional global image normalisation +equalisation that is designed to reduce the influence of illumination +effects. In practice we use gamma (power law) compression, either +computing the square root or the log of each colour channel. +Image texture strength is typically proportional to the local surface +illumination so this compression helps to reduce the effects of local +shadowing and illumination variations. + +The second stage computes first order image gradients. These capture +contour, silhouette and some texture information, while providing +further resistance to illumination variations. The locally dominant +colour channel is used, which provides colour invariance to a large +extent. Variant methods may also include second order image derivatives, +which act as primitive bar detectors - a useful feature for capturing, +e.g. bar like structures in bicycles and limbs in humans. + +The third stage aims to produce an encoding that is sensitive to +local image content while remaining resistant to small changes in +pose or appearance. The adopted method pools gradient orientation +information locally in the same way as the SIFT [Lowe 2004] +feature. The image window is divided into small spatial regions, +called "cells". For each cell we accumulate a local 1-D histogram +of gradient or edge orientations over all the pixels in the +cell. This combined cell-level 1-D histogram forms the basic +"orientation histogram" representation. Each orientation histogram +divides the gradient angle range into a fixed number of +predetermined bins. The gradient magnitudes of the pixels in the +cell are used to vote into the orientation histogram. + +The fourth stage computes normalisation, which takes local groups of +cells and contrast normalises their overall responses before passing +to next stage. Normalisation introduces better invariance to illumination, +shadowing, and edge contrast. It is performed by accumulating a measure +of local histogram "energy" over local groups of cells that we call +"blocks". The result is used to normalise each cell in the block. +Typically each individual cell is shared between several blocks, but +its normalisations are block dependent and thus different. The cell +thus appears several times in the final output vector with different +normalisations. This may seem redundant but it improves the performance. +We refer to the normalised block descriptors as Histogram of Oriented +Gradient (HOG) descriptors. + +The final step collects the HOG descriptors from all blocks of a dense +overlapping grid of blocks covering the detection window into a combined +feature vector for use in the window classifier. + +References +---------- + +.. [1] Dalal, N and Triggs, B, Histograms of Oriented Gradients for + Human Detection, IEEE Computer Society Conference on Computer + Vision and Pattern Recognition 2005 San Diego, CA, USA +''' + +from scikits.image.feature import hog +from scikits.image import data +from scikits.image.color import rgb2grey + +import numpy as np +import matplotlib.pyplot as plt + + +# Construct test image + +image = data.lena() + +# HOG + +grey = rgb2grey(image) + +fd, hog_image = hog(grey, orientations=8, pixels_per_cell=(16, 16), + cells_per_block=(1, 1), visualise=True) + +plt.figure(figsize=(12, 5)) + +plt.subplot(121) +plt.imshow(grey, cmap=plt.cm.gray) +plt.title('Input image') + +plt.subplot(122) +plt.imshow(hog_image, cmap=plt.cm.gray) +plt.title('Histogram of Oriented Gradients') +plt.show() From 8f7a2c0743f299502c5820085c619b2ae73f7920 Mon Sep 17 00:00:00 2001 From: Brian Holt Date: Fri, 10 Feb 2012 18:27:25 +0000 Subject: [PATCH 04/10] pep8 --- doc/examples/plot_hog.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/doc/examples/plot_hog.py b/doc/examples/plot_hog.py index da82cd83..444e5965 100644 --- a/doc/examples/plot_hog.py +++ b/doc/examples/plot_hog.py @@ -4,10 +4,10 @@ Histogram of Oriented Gradients =============================== The Histogram of Oriented Gradient (HOG) feature descriptor is popular -for object detection +for object detection `__. -In the following example, we compute the HOG descriptor and display +In the following example, we compute the HOG descriptor and display a visualisation. Algorithm overview @@ -19,7 +19,7 @@ Compute a Histogram of Oriented Gradients (HOG) by 3) computing gradient histograms 3) normalising across blocks 4) flattening into a feature vector - + The first stage applies an optional global image normalisation equalisation that is designed to reduce the influence of illumination effects. In practice we use gamma (power law) compression, either @@ -27,7 +27,7 @@ computing the square root or the log of each colour channel. Image texture strength is typically proportional to the local surface illumination so this compression helps to reduce the effects of local shadowing and illumination variations. - + The second stage computes first order image gradients. These capture contour, silhouette and some texture information, while providing further resistance to illumination variations. The locally dominant @@ -64,7 +64,7 @@ Gradient (HOG) descriptors. The final step collects the HOG descriptors from all blocks of a dense overlapping grid of blocks covering the detection window into a combined -feature vector for use in the window classifier. +feature vector for use in the window classifier. References ---------- @@ -81,7 +81,6 @@ from scikits.image.color import rgb2grey import numpy as np import matplotlib.pyplot as plt - # Construct test image image = data.lena() From 072202a2ea71f3de0dae0d56bcb6fda7b4b543f3 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 10 Feb 2012 14:51:29 -0800 Subject: [PATCH 05/10] DOC: Import hog from skimage instead of scikits-image. Rescale the output histogram to be more visible. --- doc/examples/plot_hog.py | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/doc/examples/plot_hog.py b/doc/examples/plot_hog.py index 444e5965..2bb830f2 100644 --- a/doc/examples/plot_hog.py +++ b/doc/examples/plot_hog.py @@ -74,31 +74,27 @@ References Vision and Pattern Recognition 2005 San Diego, CA, USA ''' -from scikits.image.feature import hog -from scikits.image import data -from scikits.image.color import rgb2grey +from skimage.feature import hog +from skimage import data, color, exposure import numpy as np import matplotlib.pyplot as plt -# Construct test image +image = color.rgb2gray(data.lena()) -image = data.lena() - -# HOG - -grey = rgb2grey(image) - -fd, hog_image = hog(grey, orientations=8, pixels_per_cell=(16, 16), +fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualise=True) plt.figure(figsize=(12, 5)) -plt.subplot(121) -plt.imshow(grey, cmap=plt.cm.gray) +plt.subplot(121).set_axis_off() +plt.imshow(image, cmap=plt.cm.gray) plt.title('Input image') -plt.subplot(122) -plt.imshow(hog_image, cmap=plt.cm.gray) +# Rescale histogram for better display +hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.03)) + +plt.subplot(122).set_axis_off() +plt.imshow(hog_image_rescaled, cmap=plt.cm.gray) plt.title('Histogram of Oriented Gradients') plt.show() From 7ac612e017cb85541441be8c88e8aba51751b251 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 10 Feb 2012 15:04:58 -0800 Subject: [PATCH 06/10] DOC: Fix formatting typos in HoG example. --- doc/examples/plot_hog.py | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/doc/examples/plot_hog.py b/doc/examples/plot_hog.py index 2bb830f2..8d11f24c 100644 --- a/doc/examples/plot_hog.py +++ b/doc/examples/plot_hog.py @@ -3,9 +3,9 @@ r''' Histogram of Oriented Gradients =============================== -The Histogram of Oriented Gradient (HOG) feature descriptor is popular -for object detection -`__. +The `Histogram of Oriented Gradient +`__ (HOG) feature +descriptor [1]_ is popular for object detection. In the following example, we compute the HOG descriptor and display a visualisation. @@ -14,11 +14,12 @@ Algorithm overview ------------------ Compute a Histogram of Oriented Gradients (HOG) by - 1) (optional) global image normalisation - 2) computing the gradient image in x and y - 3) computing gradient histograms - 3) normalising across blocks - 4) flattening into a feature vector + + 1. (optional) global image normalisation + 2. computing the gradient image in x and y + 3. computing gradient histograms + 4. normalising across blocks + 5. flattening into a feature vector The first stage applies an optional global image normalisation equalisation that is designed to reduce the influence of illumination @@ -39,7 +40,7 @@ e.g. bar like structures in bicycles and limbs in humans. The third stage aims to produce an encoding that is sensitive to local image content while remaining resistant to small changes in pose or appearance. The adopted method pools gradient orientation -information locally in the same way as the SIFT [Lowe 2004] +information locally in the same way as the SIFT [2]_ feature. The image window is divided into small spatial regions, called "cells". For each cell we accumulate a local 1-D histogram of gradient or edge orientations over all the pixels in the @@ -69,9 +70,13 @@ feature vector for use in the window classifier. References ---------- -.. [1] Dalal, N and Triggs, B, Histograms of Oriented Gradients for - Human Detection, IEEE Computer Society Conference on Computer - Vision and Pattern Recognition 2005 San Diego, CA, USA +.. [1] Dalal, N. and Triggs, B., "Histograms of Oriented Gradients for + Human Detection," IEEE Computer Society Conference on Computer + Vision and Pattern Recognition, 2005, San Diego, CA, USA. + +.. [2] David G. Lowe, "Distinctive image features from scale-invariant + keypoints," International Journal of Computer Vision, 60, 2 (2004), + pp. 91-110. ''' from skimage.feature import hog @@ -85,14 +90,14 @@ image = color.rgb2gray(data.lena()) fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualise=True) -plt.figure(figsize=(12, 5)) +plt.figure(figsize=(10, 5)) plt.subplot(121).set_axis_off() plt.imshow(image, cmap=plt.cm.gray) plt.title('Input image') # Rescale histogram for better display -hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.03)) +hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) plt.subplot(122).set_axis_off() plt.imshow(hog_image_rescaled, cmap=plt.cm.gray) From 99ac9e44ff7ecafdd4adae7231c22c4254f0aaa2 Mon Sep 17 00:00:00 2001 From: Zach Pincus Date: Tue, 7 Feb 2012 17:40:33 -0500 Subject: [PATCH 07/10] ENH: load libfreeimage based on case-insensitive libname prefixes --- skimage/io/_plugins/freeimage_plugin.py | 106 ++++++++++-------------- 1 file changed, 42 insertions(+), 64 deletions(-) diff --git a/skimage/io/_plugins/freeimage_plugin.py b/skimage/io/_plugins/freeimage_plugin.py index 664b32af..74564d0c 100644 --- a/skimage/io/_plugins/freeimage_plugin.py +++ b/skimage/io/_plugins/freeimage_plugin.py @@ -5,45 +5,8 @@ import os import os.path from numpy.compat import asbytes -def _load_library(libname, libdir): - """Try to load a libray with the base name 'libname' from the - directory 'libdir', checking for various common shared-lib file - extensions. Uses windll to load libaries on windows machines, and - cdll to load libraries on other platforms. - Returns (library, errors), where library may or may not be None, and - errors is a dict, potentially empty, mapping filenames to the ctypes - errors raised trying to load those filenames. Non-extant paths are NOT - added to the error dict.""" - ext = os.path.splitext(libname)[1] - if not ext: - # Try to load library with platform-specific name, otherwise - # default to libname.[so|pyd]. Sometimes, these files are built - # erroneously on non-linux platforms. - libname_ext = ['%s.so' % libname, '%s.pyd' % libname] - if sys.platform == 'win32': # 'win32' is returned even on 64-bit win - libname_ext.insert(0, '%s.dll' % libname) - elif sys.platform == 'darwin': - libname_ext.insert(0, '%s.dylib' % libname) - else: - libname_ext = [libname] - - library = None - errors = {} - lib_paths = [os.path.join(libdir, ln) for ln in libname_ext] - lib_paths = [lp for lp in lib_paths if os.path.exists(lp)] - if sys.platform == 'win32': - loader = ctypes.windll - else: - loader = ctypes.cdll - for lp in lib_paths: - try: - library = loader[lp] - except Exception, e: - errors[lp] = e - return library, errors - -def load_freeimage(): +def _generate_candidate_libs(): lib_dirs = [os.path.dirname(__file__), '/lib', '/usr/lib', @@ -52,47 +15,62 @@ def load_freeimage(): os.path.join(sys.prefix, 'lib'), os.path.join(sys.prefix, 'DLLs') ] - if 'HOME' in os.environ: lib_dirs.append(os.path.join(os.environ['HOME'], 'lib')) - lib_dirs = [ld for ld in lib_dirs if os.path.exists(ld)] + + lib_names = ['libfreeimage', 'freeimage'] # should be lower-case! + # Attempt to find libraries of that name in the given directory + # (case-insensitive and without regard for extension) + lib_paths = [] + for lib_dir in lib_dirs: + for lib_name in lib_names: + files = os.listdir(lib_dir) + lib_paths += [os.path.join(libdir, lib) for lib in files + if lib.lower().startswith(lib_name)] + lib_paths = [lp for lp in lib_paths if os.path.exists(lp)] + # also include bare library names that ctypes might be able to find + lib_paths.extend(['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', + 'libfreeimage.so.3']) + return lib_dirs, lib_paths +def load_freeimage(): + if sys.platform == 'win32': + loader = ctypes.windll + functype = ctypes.WINFUNCTYPE + else: + loader = ctypes.cdll + functype = ctypes.CFUNCTYPE + freeimage = None errors = {} - for d in lib_dirs: - for libname in ('freeimage', 'FreeImage', - 'libfreeimage', 'libFreeImage'): - freeimage, new_errors = _load_library(libname, d) - if freeimage: - break - errors.update(new_errors) - if freeimage: + lib_dirs, lib_paths = _generate_candidate_libs() + for lib in lib_paths: + try: + freeimage = loader.LoadLibrary(lib) break + except Exception, e: + errors[lp] = e - if freeimage: - if sys.platform == 'win32': - functype = ctypes.WINFUNCTYPE - else: - functype = ctypes.CFUNCTYPE - - @functype(None, ctypes.c_int, ctypes.c_char_p) - def error_handler(fif, message): - raise RuntimeError('FreeImage error: %s' % message) - - freeimage.FreeImage_SetOutputMessage(error_handler) - - elif errors: - # No freeimage library found, but load-errors reported + if errors: + # No freeimage library loaded, but load-errors reported for some + # candidate libs err_txt = ['%s:\n%s'%(pl, err.message) for pl, err in errors.items()] raise OSError('One or more FreeImage libraries were found, but could ' 'not be loaded due to the following errors:\n'+ '\n\n'.join(err_txt)) - else: - # No potential libraries found + elif freeimage is None: + # No errors, because no potential libraries found at all! raise OSError('Could not find a FreeImage library in any of:\n'+ '\n'.join(lib_dirs)) + + # FreeImage found + @functype(None, ctypes.c_int, ctypes.c_char_p) + def error_handler(fif, message): + raise RuntimeError('FreeImage error: %s' % message) + + freeimage.FreeImage_SetOutputMessage(error_handler) return freeimage _FI = load_freeimage() From 6a31ea8508a834c8116b5dd9624f375303698a38 Mon Sep 17 00:00:00 2001 From: Zach Pincus Date: Fri, 10 Feb 2012 09:49:01 -0500 Subject: [PATCH 08/10] BUG: Make it work actually... --- skimage/io/_plugins/freeimage_plugin.py | 63 +++++++++++++++---------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/skimage/io/_plugins/freeimage_plugin.py b/skimage/io/_plugins/freeimage_plugin.py index 74564d0c..f8ccf5d2 100644 --- a/skimage/io/_plugins/freeimage_plugin.py +++ b/skimage/io/_plugins/freeimage_plugin.py @@ -6,7 +6,8 @@ import os.path from numpy.compat import asbytes -def _generate_candidate_libs(): +def _generate_candidate_libs(): + # look for likely library files in the following dirs: lib_dirs = [os.path.dirname(__file__), '/lib', '/usr/lib', @@ -18,20 +19,19 @@ def _generate_candidate_libs(): if 'HOME' in os.environ: lib_dirs.append(os.path.join(os.environ['HOME'], 'lib')) lib_dirs = [ld for ld in lib_dirs if os.path.exists(ld)] - + lib_names = ['libfreeimage', 'freeimage'] # should be lower-case! - # Attempt to find libraries of that name in the given directory + # Now attempt to find libraries of that name in the given directory # (case-insensitive and without regard for extension) lib_paths = [] for lib_dir in lib_dirs: for lib_name in lib_names: files = os.listdir(lib_dir) - lib_paths += [os.path.join(libdir, lib) for lib in files - if lib.lower().startswith(lib_name)] + lib_paths += [os.path.join(lib_dir, lib) for lib in files + if lib.lower().startswith(lib_name) and not + os.path.splitext(lib)[1] in ('.py', '.pyc', '.ini')] lib_paths = [lp for lp in lib_paths if os.path.exists(lp)] - # also include bare library names that ctypes might be able to find - lib_paths.extend(['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', - 'libfreeimage.so.3']) + return lib_dirs, lib_paths def load_freeimage(): @@ -43,27 +43,40 @@ def load_freeimage(): functype = ctypes.CFUNCTYPE freeimage = None - errors = {} - lib_dirs, lib_paths = _generate_candidate_libs() - for lib in lib_paths: + errors = [] + # First try a few bare library names that ctypes might be able to find + # in the default locations for each platform. Win DLL names don't need the + # extension, but other platforms do. + for lib in ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', + 'libfreeimage.so.3']: try: freeimage = loader.LoadLibrary(lib) break - except Exception, e: - errors[lp] = e + except: + pass + # Don't generate an error for any not-found bare libs + + if freeimage is None: + lib_dirs, lib_paths = _generate_candidate_libs() + for lib in lib_paths: + try: + freeimage = loader.LoadLibrary(lib) + break + except Exception, e: + errors.append((lib, e)) - if errors: - # No freeimage library loaded, but load-errors reported for some - # candidate libs - err_txt = ['%s:\n%s'%(pl, err.message) for pl, err in errors.items()] - raise OSError('One or more FreeImage libraries were found, but could ' - 'not be loaded due to the following errors:\n'+ - '\n\n'.join(err_txt)) - - elif freeimage is None: - # No errors, because no potential libraries found at all! - raise OSError('Could not find a FreeImage library in any of:\n'+ - '\n'.join(lib_dirs)) + if freeimage is None: + if errors: + # No freeimage library loaded, and load-errors reported for some + # candidate libs + err_txt = ['%s:\n%s'%(l, e.message) for l, e in errors] + raise OSError('One or more FreeImage libraries were found, but ' + 'could not be loaded due to the following errors:\n'+ + '\n\n'.join(err_txt)) + else: + # No errors, because no potential libraries found at all! + raise OSError('Could not find a FreeImage library in any of:\n'+ + '\n'.join(lib_dirs)) # FreeImage found @functype(None, ctypes.c_int, ctypes.c_char_p) From f2321d0441cd23abcad8a9736b238a62850bae93 Mon Sep 17 00:00:00 2001 From: Zach Pincus Date: Fri, 10 Feb 2012 17:45:37 -0500 Subject: [PATCH 09/10] STY: Clarify logic of code for FreeImage loading. --- skimage/io/_plugins/freeimage_plugin.py | 26 ++++++++++++------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/skimage/io/_plugins/freeimage_plugin.py b/skimage/io/_plugins/freeimage_plugin.py index f8ccf5d2..1e95300f 100644 --- a/skimage/io/_plugins/freeimage_plugin.py +++ b/skimage/io/_plugins/freeimage_plugin.py @@ -47,23 +47,21 @@ def load_freeimage(): # First try a few bare library names that ctypes might be able to find # in the default locations for each platform. Win DLL names don't need the # extension, but other platforms do. - for lib in ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', - 'libfreeimage.so.3']: + bare_libs = ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', + 'libfreeimage.so.3'] + lib_dirs, lib_paths = _generate_candidate_libs() + lib_paths = bare_libs + lib_paths + for lib in lib_paths: try: freeimage = loader.LoadLibrary(lib) break - except: - pass - # Don't generate an error for any not-found bare libs - - if freeimage is None: - lib_dirs, lib_paths = _generate_candidate_libs() - for lib in lib_paths: - try: - freeimage = loader.LoadLibrary(lib) - break - except Exception, e: - errors.append((lib, e)) + except Exception, e: + if lib not in bare_libs: + # Don't record errors when it couldn't load the library from + # a bare name -- this fails often, and doesn't provide any + # useful debugging information anyway, beyond "couldn't find + # library..." + errors.append((lib, e)) if freeimage is None: if errors: From b127f6053380c8a9fc34bfe1b4e1f9edfb779c6c Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Fri, 10 Feb 2012 15:08:03 -0800 Subject: [PATCH 10/10] STY: Whitespace cleanup. --- skimage/io/_plugins/freeimage_plugin.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/skimage/io/_plugins/freeimage_plugin.py b/skimage/io/_plugins/freeimage_plugin.py index 1e95300f..5f5343c0 100644 --- a/skimage/io/_plugins/freeimage_plugin.py +++ b/skimage/io/_plugins/freeimage_plugin.py @@ -6,7 +6,7 @@ import os.path from numpy.compat import asbytes -def _generate_candidate_libs(): +def _generate_candidate_libs(): # look for likely library files in the following dirs: lib_dirs = [os.path.dirname(__file__), '/lib', @@ -19,7 +19,7 @@ def _generate_candidate_libs(): if 'HOME' in os.environ: lib_dirs.append(os.path.join(os.environ['HOME'], 'lib')) lib_dirs = [ld for ld in lib_dirs if os.path.exists(ld)] - + lib_names = ['libfreeimage', 'freeimage'] # should be lower-case! # Now attempt to find libraries of that name in the given directory # (case-insensitive and without regard for extension) @@ -31,7 +31,7 @@ def _generate_candidate_libs(): if lib.lower().startswith(lib_name) and not os.path.splitext(lib)[1] in ('.py', '.pyc', '.ini')] lib_paths = [lp for lp in lib_paths if os.path.exists(lp)] - + return lib_dirs, lib_paths def load_freeimage(): @@ -41,13 +41,13 @@ def load_freeimage(): else: loader = ctypes.cdll functype = ctypes.CFUNCTYPE - + freeimage = None errors = [] # First try a few bare library names that ctypes might be able to find - # in the default locations for each platform. Win DLL names don't need the + # in the default locations for each platform. Win DLL names don't need the # extension, but other platforms do. - bare_libs = ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', + bare_libs = ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so', 'libfreeimage.so.3'] lib_dirs, lib_paths = _generate_candidate_libs() lib_paths = bare_libs + lib_paths @@ -75,12 +75,12 @@ def load_freeimage(): # No errors, because no potential libraries found at all! raise OSError('Could not find a FreeImage library in any of:\n'+ '\n'.join(lib_dirs)) - + # FreeImage found @functype(None, ctypes.c_int, ctypes.c_char_p) def error_handler(fif, message): raise RuntimeError('FreeImage error: %s' % message) - + freeimage.FreeImage_SetOutputMessage(error_handler) return freeimage