luispedro / mahotas

Computer Vision in Python
https://mahotas.rtfd.io
Other
839 stars 147 forks source link

Make mahotas work on Python 2.6 to 3.3 without 2to3 #15

Closed cgohlke closed 11 years ago

cgohlke commented 12 years ago

Looking at the output of 2to3, the mahotas code could be made compatible with Python 2.6 to 3.3 with few changes. Most changes are xrange->range. A few import, print and raise statements need to be updated.

This patch works for me on win-amd64, Python 2.6 to 3.3. I could work on a pull request later if there is interest.

diff --git a/mahotas/__init__.py b/mahotas/__init__.py
index 09a3b8f..1315571 100644
--- a/mahotas/__init__.py
+++ b/mahotas/__init__.py
@@ -5,6 +5,9 @@ Mahotas

 A package for computer vision in Python.
 '''
+
+from __future__ import print_function
+
 try:
     from .bbox import bbox, croptobbox
     from .center_of_mass import center_of_mass
@@ -25,14 +28,14 @@ try:

     from .tests import run as test

-    from mahotas_version import __version__
+    from .mahotas_version import __version__

-    import features
-    import morph
-    import segmentation
-except ImportError, e:
+    from . import features
+    from . import morph
+    from . import segmentation
+except ImportError as e:
     import sys
-    print >>sys.stderr, '''\
+    print('''\
 Could not import submodules (exact error was: %s).

 There are many reasons for this error the most common one is that you have
@@ -41,7 +44,7 @@ installed them (using `python setup.py install`) and then proceeded to test
 mahotas **without changing the current directory**.

 Try installing and then changing to another directory before importing mahotas.
-''' % e
+''' % e, file=sys.stderr)

diff --git a/mahotas/convolve.py b/mahotas/convolve.py
index 64c2826..4c08792 100644
--- a/mahotas/convolve.py
+++ b/mahotas/convolve.py
@@ -324,7 +324,7 @@ def gaussian_filter(array, sigma, order=0, mode='reflect', cval=0., out=None, ou
     sigmas = _normalize_sequence(array, sigma, 'gaussian_filter')
     output[...] = array[...]
     noutput = None
-    for axis in xrange(array.ndim):
+    for axis in range(array.ndim):
         sigma = sigmas[axis]
         order = orders[axis]
         noutput = gaussian_filter1d(output, sigma, axis, order, mode, cval, noutput)
@@ -342,7 +342,7 @@ def _wavelet_array(f, inline, func):

 def _wavelet_center_compute(oshape, border=0, dtype=None, cval=0.0):
-    for c in xrange(1, 16+border):
+    for c in range(1, 16+border):
         nshape = 2**(np.floor(np.log2(oshape))+c)
         delta = nshape - oshape
         delta //= 2
@@ -448,7 +448,7 @@ def haar(f, preserve_energy=True, inline=False):
         f /= 2.0
     return f

-_daubechies_codes = [('D%s' % ci) for ci in xrange(2,21,2)]
+_daubechies_codes = [('D%s' % ci) for ci in range(2,21,2)]
 def daubechies(f, code, inline=False):
     '''
     filtered = daubechies(f, code, inline=False)
diff --git a/mahotas/features/surf.py b/mahotas/features/surf.py
index c195a31..cf1b782 100644
--- a/mahotas/features/surf.py
+++ b/mahotas/features/surf.py
@@ -3,6 +3,7 @@
 #
 # License: MIT (see COPYING file)

+
 from __future__ import division
 import numpy as np
 from . import _surf
@@ -217,7 +218,9 @@ def show_surf(f, spoints, values=None, colors=None):
         x0 = int(x) - size//2
         x1 = x + size
         y1 = y + size
-        def rotate_around((p0,p1),(c0,c1), a):
+        def rotate_around(p, c, a):
+            (p0, p1) = p
+            (c0, c1) = c
             d0 = p0-c0
             d1 = p1 - c1
             d0,d1 = rotate(d0,d1,a)
diff --git a/mahotas/features/texture.py b/mahotas/features/texture.py
index 8f9ea11..448c06a 100644
--- a/mahotas/features/texture.py
+++ b/mahotas/features/texture.py
@@ -76,7 +76,7 @@ def haralick(f, ignore_zeros=False, preserve_haralick_bug=False, compute_14th_fe
     px_plus_y = np.empty(2*fm1, np.double)
     px_minus_y = np.empty(fm1, np.double)

-    for dir in xrange(nr_dirs):
+    for dir in range(nr_dirs):
         cooccurence(f, dir, cmat, symmetric=True)
         if ignore_zeros:
             cmat[0] = 0
@@ -222,7 +222,7 @@ def cooccurence(f, direction, output=None, symmetric=True):
     if len(f.shape) == 2:
         assert direction in (0,1,2,3), 'mahotas.texture.cooccurence: `direction` %s is not in range(4).' % direction
     elif len(f.shape) == 3:
-        assert direction in xrange(13), 'mahotas.texture.cooccurence: `direction` %s is not in range(13).' % direction
+        assert direction in range(13), 'mahotas.texture.cooccurence: `direction` %s is not in range(13).' % direction
     else:
         raise ValueError('mahotas.texture.cooccurence: cannot handle images of %s dimensions.' % len(f.shape))

diff --git a/mahotas/features/zernike.py b/mahotas/features/zernike.py
index 41825f4..9ce8888 100644
--- a/mahotas/features/zernike.py
+++ b/mahotas/features/zernike.py
@@ -83,11 +83,11 @@ def zernike_moments(im, radius, degree=8, cm=None):
     An.real = (Xn/Dn)
     An.imag = (Yn/Dn)

-    Ans = [An**p for p in xrange(2,degree+2)]
+    Ans = [An**p for p in range(2,degree+2)]
     Ans.insert(0, An) # An**1
     Ans.insert(0, np.ones_like(An)) # An**0
-    for n in xrange(degree+1):
-        for l in xrange(n+1):
+    for n in range(degree+1):
+        for l in range(n+1):
             if (n-l)%2 == 0:
                 z = _zernike.znl(Dn, Ans[l], frac_center, n, l)
                 zvalues.append(abs(z))
diff --git a/mahotas/io/__init__.py b/mahotas/io/__init__.py
index 3f0e640..ae2946a 100644
--- a/mahotas/io/__init__.py
+++ b/mahotas/io/__init__.py
@@ -33,7 +33,7 @@ try:
         from imread import imread, imsave
     except:
         from .freeimage import imread, imsave
-except OSError, e:
+except OSError as e:
     _error_message %= e
     imread = error_imread
     imsave = error_imsave
diff --git a/mahotas/labeled.py b/mahotas/labeled.py
index 6c66e7f..a45bc92 100644
--- a/mahotas/labeled.py
+++ b/mahotas/labeled.py
@@ -3,6 +3,7 @@
 # 
 # LICENSE: MIT

+
 from __future__ import division
 import numpy as np
 from .morph import get_structuring_elem
@@ -71,8 +72,8 @@ def remove_bordering(im, rsize=1, out=None, output=None):
         Subset of ``labeled``
     '''
     invalid = set()
-    index = [slice(None,None,None) for _ in xrange(im.ndim)]
-    for dim in xrange(im.ndim):
+    index = [slice(None,None,None) for _ in range(im.ndim)]
+    for dim in range(im.ndim):
         for bordering in (
                     slice(rsize),
                     slice(-rsize, None)
diff --git a/mahotas/morph.py b/mahotas/morph.py
index e9c73ce..4dff545 100644
--- a/mahotas/morph.py
+++ b/mahotas/morph.py
@@ -85,7 +85,7 @@ def get_structuring_elem(A,Bc):
     Bc = np.zeros((3,)*len(A.shape), dtype=A.dtype)
     centre = np.ones(len(A.shape))
     # This is pretty slow, but this should be a tiny array, so who cares
-    for i in xrange(Bc.size):
+    for i in range(Bc.size):
         pos = np.unravel_index(i, Bc.shape)
         pos -= centre
         if np.sum(np.abs(pos)) <= max1:
diff --git a/mahotas/polygon.py b/mahotas/polygon.py
index b44b6d5..4eef063 100644
--- a/mahotas/polygon.py
+++ b/mahotas/polygon.py
@@ -51,7 +51,7 @@ def line(p0, p1, canvas, color=1):
     error = dx/2.
     y = y0
     ystep = (+1 if y0 < y1 else -1)
-    for x in xrange(x0,x1+1):
+    for x in range(x0,x1+1):
         if steep:
             canvas[x,y] = color
         else:
@@ -83,7 +83,7 @@ def fill_polygon(polygon, canvas, color=1):
     min_y = min(y for y,x in polygon)
     max_y = max(y for y,x in polygon)
     polygon = [(float(y),float(x)) for y,x in polygon]
-    for y in xrange(min_y, max_y+1):
+    for y in range(min_y, max_y+1):
         nodes = []
         j = -1
         for i,p in enumerate(polygon):
diff --git a/mahotas/tests/test_euler.py b/mahotas/tests/test_euler.py
index d9e44bb..c77581e 100644
--- a/mahotas/tests/test_euler.py
+++ b/mahotas/tests/test_euler.py
@@ -3,9 +3,9 @@ from mahotas.euler import euler, _euler_lookup4, _euler_lookup8
 from nose.tools import raises

 def test_lookup():
-    Q1 = [np.array(q, np.bool) for q in [[0,0],[1,0]], [[0,0],[0,1]], [[0,1],[0,0]], [[1,0],[0,0]] ]
+    Q1 = [np.array(q, np.bool) for q in ([[0,0],[1,0]], [[0,0],[0,1]], [[0,1],[0,0]], [[1,0],[0,0]]) ]
     Q2 =  [(~q) for q in Q1]
-    Q3 = [np.array(q, np.bool) for q in [[0,1],[1,0]], [[1,0],[0,1]] ]
+    Q3 = [np.array(q, np.bool) for q in ([[0,1],[1,0]], [[1,0],[0,1]]) ]

     def _value(q, lookup):
         q = q.ravel()
diff --git a/mahotas/thresholding.py b/mahotas/thresholding.py
index ae26137..bd7c5de 100644
--- a/mahotas/thresholding.py
+++ b/mahotas/thresholding.py
@@ -75,7 +75,7 @@ def otsu(img, ignore_zeros=False):
     best = nB[0]*nO[0]*(mu_B-mu_O)*(mu_B-mu_O)
     bestT = 0

-    for T in xrange(1, Ng):
+    for T in range(1, Ng):
         if nB[T] == 0: continue
         if nO[T] == 0: break
         mu_B = (mu_B*nB[T-1] + T*hist[T]) / nB[T]
luispedro commented 12 years ago

I am not sure whether someone is still using 2.5, which is why I didn't do this myself.

cgohlke commented 12 years ago

OK. FWIW, on Windows with msvc compilers, I was never able to build mahotas for Python 2.5.

luispedro commented 11 years ago

FYI, I just committed something very similar (more hand-written, though).

I think it is Python 2.5 compatible: it uses stderr.write instead of print and sys.exc_info() to get the exception instead of of except type as name.