MISC remove unused imports, some pep8 corrections.

This commit is contained in:
Andreas Mueller
2012-09-27 20:01:45 +01:00
parent 359e7703cc
commit 6c59e04714
28 changed files with 97 additions and 104 deletions
-2
View File
@@ -3,8 +3,6 @@
import numpy as np
from . import _template
from skimage.util.dtype import convert
def match_template(image, template, pad_input=False):
"""Match a template to an image using normalized correlation.
+2 -4
View File
@@ -2,9 +2,7 @@
Methods to characterize image textures.
"""
import math
import numpy as np
from scipy import ndimage
from ._texture import _glcm_loop, _local_binary_pattern
@@ -236,8 +234,8 @@ def local_binary_pattern(image, P, R, method='default'):
image : (N, M) array
Graylevel image.
P : int
Number of circularly symmetric neighbour set points (quantization of the
angular space).
Number of circularly symmetric neighbour set points (quantization of
the angular space).
R : float
Radius of circle (spatial resolution of the operator).
method : {'default', 'ror', 'uniform', 'var'}
+3 -2
View File
@@ -170,7 +170,8 @@ def _tv_denoise_2d(im, weight=50, eps=2.e-4, n_iter_max=200):
E_previous = E
i += 1
return out
def tv_denoise(im, weight=50, eps=2.e-4, n_iter_max=200):
"""
Perform total-variation denoising on 2-d and 3-d images
@@ -248,4 +249,4 @@ def tv_denoise(im, weight=50, eps=2.e-4, n_iter_max=200):
else:
raise ValueError('only 2-d and 3-d images may be denoised with this '
'function')
return out
return out
+4 -5
View File
@@ -2,7 +2,6 @@ import numpy as np
from numpy.testing import run_module_suite
from skimage import filter, data, color
from skimage import img_as_uint, img_as_ubyte
class TestTvDenoise():
@@ -35,13 +34,13 @@ class TestTvDenoise():
# lena image
lena = color.rgb2gray(data.lena())[:256, :256]
int_lena = np.multiply(lena, 255).astype(np.uint8)
assert np.max(int_lena) > 1
assert np.max(int_lena) > 1
denoised_int_lena = filter.tv_denoise(int_lena, weight=60.0)
# test if the value range of output float data is within [0.0:1.0]
assert denoised_int_lena.dtype == np.float
assert np.max(denoised_int_lena) <= 1.0
assert np.min(denoised_int_lena) >= 0.0
assert np.min(denoised_int_lena) >= 0.0
def test_tv_denoise_3d(self):
"""
Apply the TV denoising algorithm on a 3D image representing
@@ -56,7 +55,7 @@ class TestTvDenoise():
mask[mask > 255] = 255
res = filter.tv_denoise(mask.astype(np.uint8), weight=100)
assert res.dtype == np.float
assert res.std() * 255 < mask.std()
assert res.std() * 255 < mask.std()
# test wrong number of dimensions
a = np.random.random((8, 8, 8, 8))
+1 -1
View File
@@ -1,4 +1,4 @@
from ._mcp import MCP, MCP_Geometric, make_offsets
from ._mcp import MCP, MCP_Geometric
def route_through_array(array, start, end, fully_connected=True,
-1
View File
@@ -1,4 +1,3 @@
import numpy as np
from numpy.testing import *
import time
-1
View File
@@ -1,6 +1,5 @@
__all__ = ['imread', 'imread_collection']
import numpy as np
import skimage.io as io
try:
-2
View File
@@ -1,7 +1,5 @@
__all__ = ['imread']
import numpy as np
try:
import osgeo.gdal as gdal
except ImportError:
+1 -2
View File
@@ -1,6 +1,5 @@
from .util import prepare_for_display, window_manager, GuiLockError
from .util import prepare_for_display, window_manager
import numpy as np
import sys
# We try to aquire the gui lock first or else the gui import might
# trample another GUI's PyOS_InputHook.
+1 -5
View File
@@ -14,13 +14,9 @@ The skivi module is not meant to be used directly.
Use skimage.io.imshow(img, fancy=True)'''
from textwrap import dedent
import numpy as np
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import (QApplication, QMainWindow, QImage, QPixmap,
QLabel, QWidget, QVBoxLayout, QSlider,
QPainter, QColor, QFrame, QLayoutItem)
from PyQt4.QtGui import QMainWindow, QImage, QPixmap, QLabel, QWidget, QFrame
from .q_color_mixer import MixerPanel
from .q_histogram import QuadHistogram
-1
View File
@@ -1,7 +1,6 @@
from numpy.testing import *
import numpy as np
import skimage.io._plugins._colormixer as cm
from skimage.io._plugins._histograms import histograms
+4 -5
View File
@@ -19,18 +19,18 @@ class TestPrepareForDisplay:
assert x[3, 2, 0] == 255
def test_colour(self):
x = prepare_for_display(np.random.random((10, 10, 3)))
prepare_for_display(np.random.random((10, 10, 3)))
def test_alpha(self):
x = prepare_for_display(np.random.random((10, 10, 4)))
prepare_for_display(np.random.random((10, 10, 4)))
@raises(ValueError)
def test_wrong_dimensionality(self):
x = prepare_for_display(np.random.random((10, 10, 1, 1)))
prepare_for_display(np.random.random((10, 10, 1, 1)))
@raises(ValueError)
def test_wrong_depth(self):
x = prepare_for_display(np.random.random((10, 10, 5)))
prepare_for_display(np.random.random((10, 10, 5)))
class TestWindowManager:
@@ -48,7 +48,6 @@ class TestWindowManager:
self.callback_called = True
def test_callback(self):
cb = lambda x: x
self.wm.register_callback(self.callback)
self.wm.add_window('window')
self.wm.remove_window('window')
+1 -3
View File
@@ -1,7 +1,5 @@
import numpy as np
from nose.tools import *
from numpy.testing import assert_array_equal, assert_array_almost_equal, \
assert_equal, run_module_suite
from numpy.testing import assert_equal, run_module_suite
from tempfile import NamedTemporaryFile
import os
-1
View File
@@ -53,7 +53,6 @@ def approximate_polygon(coords, tolerance):
segment_coords = coords[start + 1:end, :]
segment_dists = dists[start + 1:end]
# check whether to take perpendicular or euclidean distance with
# inner product of vectors
+4 -4
View File
@@ -159,15 +159,15 @@ def regionprops(label_image, properties=['Area', 'Centroid'],
`pi/2` in counter-clockwise direction.
* Perimeter : float
Perimeter of object which approximates the contour as a line through
the centers of border pixels using a 4-connectivity.
Perimeter of object which approximates the contour as a line
through the centers of border pixels using a 4-connectivity.
* Solidity : float
Ratio of pixels in the region to pixels of the convex hull image.
* WeightedCentralMoments : (3, 3) ndarray
Central moments (translation invariant) of intensity image up to 3rd
order.
Central moments (translation invariant) of intensity image up to
3rd order.
wmu_ji = sum{ array(x, y) * (x - x_c)^j * (y - y_c)^i }
@@ -2,7 +2,7 @@ import numpy as np
from numpy.testing import assert_equal
from skimage.measure import structural_similarity as ssim
import scipy.optimize as opt
def test_ssim_patch_range():
N = 51
@@ -12,6 +12,7 @@ def test_ssim_patch_range():
assert(ssim(X, Y, win_size=N) < 0.1)
assert_equal(ssim(X, X, win_size=N), 1)
def test_ssim_image():
N = 100
X = (np.random.random((N, N)) * 255).astype(np.uint8)
@@ -38,6 +39,7 @@ def test_ssim_image():
## assert(np.all(opt.check_grad(func, grad, Y) < 0.05))
def test_ssim_dtype():
N = 30
X = np.random.random((N, N))
+1 -1
View File
@@ -1,7 +1,7 @@
__all__ = ['convex_hull_image']
import numpy as np
from ._pnpoly import points_inside_poly, grid_points_inside_poly
from ._pnpoly import grid_points_inside_poly
from ._convex_hull import possible_hull
-1
View File
@@ -6,7 +6,6 @@
__docformat__ = 'restructuredtext en'
import warnings
import numpy as np
from skimage import img_as_ubyte
from . import cmorph
-1
View File
@@ -191,4 +191,3 @@ def reconstruction(seed, mask, method='dilation', selem=None, offset=None):
rec_img = value_map[value_rank[:image_stride]]
rec_img.shape = np.array(seed.shape) + 2 * padding
return rec_img[inside_slices]
+22 -19
View File
@@ -35,7 +35,7 @@ class TestSkeletonize():
def test_skeletonize_all_foreground(self):
im = np.ones((3, 4))
result = skeletonize(im)
skeletonize(im)
def test_skeletonize_single_point(self):
im = np.zeros((5, 5), np.uint8)
@@ -110,6 +110,7 @@ class TestSkeletonize():
[0, 0, 0, 0, 0, 0]], dtype=np.uint8)
assert np.all(result == expected)
class TestMedialAxis():
def test_00_00_zeros(self):
'''Test skeletonize on an array of all zeros'''
@@ -130,15 +131,16 @@ class TestMedialAxis():
# The result should be four diagonals from the
# corners, meeting in a horizontal line
#
expected = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,1,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,1,1,1,1,1,1,1,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,1,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]], bool)
expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
bool)
result = medial_axis(image)
assert np.all(result == expected)
result, distance = medial_axis(image, return_distance=True)
@@ -149,15 +151,16 @@ class TestMedialAxis():
image = np.zeros((9, 15), bool)
image[1:-1, 1:-1] = True
image[4, 4:-4] = False
expected = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,1,1,1,1,1,1,1,1,1,1,1,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,1,1,1,1,1,1,1,1,1,1,1,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],bool)
expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
bool)
result = medial_axis(image)
assert np.all(result == expected)
@@ -1,5 +1,5 @@
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
from numpy.testing import assert_array_equal
from skimage.segmentation import clear_border
+7 -8
View File
@@ -269,8 +269,8 @@ class AffineTransform(ProjectiveTransform):
for param in (scale, rotation, shear, translation))
if params and matrix is not None:
raise ValueError("You cannot specify the transformation matrix and "
"the implicit parameters at the same time.")
raise ValueError("You cannot specify the transformation matrix and"
" the implicit parameters at the same time.")
elif matrix is not None:
if matrix.shape != (3, 3):
raise ValueError("Invalid shape of transformation matrix.")
@@ -287,9 +287,9 @@ class AffineTransform(ProjectiveTransform):
sx, sy = scale
self._matrix = np.array([
[sx * math.cos(rotation), - sy * math.sin(rotation + shear), 0],
[sx * math.sin(rotation), sy * math.cos(rotation + shear), 0],
[ 0, 0, 1]
[sx * math.cos(rotation), -sy * math.sin(rotation + shear), 0],
[sx * math.sin(rotation), sy * math.cos(rotation + shear), 0],
[ 0, 0, 1]
])
self._matrix[0:2, 2] = translation
else:
@@ -366,7 +366,6 @@ class PiecewiseAffineTransform(ProjectiveTransform):
affine.estimate(dst[tri, :], src[tri, :])
self.inverse_affines.append(affine)
def __call__(self, coords):
"""Apply forward transformation.
@@ -992,7 +991,7 @@ def warp(image, inverse_map=None, map_args={}, output_shape=None, order=1,
if orig_ndim == 2:
out = out[..., 0]
if out is None: # use ndimage.map_coordinates
if out is None: # use ndimage.map_coordinates
if output_shape is None:
output_shape = ishape
@@ -1018,5 +1017,5 @@ def warp(image, inverse_map=None, map_args={}, output_shape=None, order=1,
if clipped.shape[0] == 1 or clipped.shape[1] == 1:
return clipped
else: # remove singleton dim introduced by atleast_3d
else: # remove singleton dim introduced by atleast_3d
return clipped.squeeze()
+1 -1
View File
@@ -130,7 +130,7 @@ def test_warp_coords_example():
assert 3 == image.shape[2]
tform = SimilarityTransform(translation=(0, -10))
coords = warp_coords(tform, (30, 30, 3))
warped_image1 = map_coordinates(image[:, :, 0], coords[:2])
map_coordinates(image[:, :, 0], coords[:2])
if __name__ == "__main__":
+1 -2
View File
@@ -1,7 +1,7 @@
import numpy as np
from numpy.testing import assert_equal, assert_raises
from skimage import img_as_int, img_as_float, \
img_as_uint, img_as_ubyte, img_as_bool
img_as_uint, img_as_ubyte
from skimage.util.dtype import convert
@@ -92,7 +92,6 @@ def test_bool():
img8 = np.zeros((10, 10), np.bool8)
img_[1, 1] = True
img8[1, 1] = True
funcs = (img_as_float, img_as_int, img_as_ubyte, img_as_uint, img_as_bool)
for (func, dt) in [(img_as_int, np.int16),
(img_as_float, np.float64),
(img_as_uint, np.uint16),
+31 -22
View File
@@ -9,6 +9,7 @@ __all__ = ['LineProfile']
#TODO: Extract line tool and add it to a new `canvastools` subpackage.
class LineProfile(PlotPlugin):
"""Plugin to compute interpolated intensity under a scan line on an image.
@@ -59,7 +60,7 @@ class LineProfile(PlotPlugin):
self.ax.set_ylim(self.limits)
h, w = image.shape
self._init_end_pts = np.array([[w/3, h/2], [2*w/3, h/2]])
self._init_end_pts = np.array([[w / 3, h / 2], [2 * w / 3, h / 2]])
self.end_pts = self._init_end_pts.copy()
x, y = np.transpose(self.end_pts)
@@ -99,14 +100,16 @@ class LineProfile(PlotPlugin):
return end_pts, profile
def on_scroll(self, event):
if not event.inaxes: return
if not event.inaxes:
return
if event.button == 'up':
self._thicken_scan_line()
elif event.button == 'down':
self._shrink_scan_line()
def on_key_press(self, event):
if not event.inaxes: return
if not event.inaxes:
return
elif event.key == '+':
self._thicken_scan_line()
elif event.key == '-':
@@ -142,19 +145,25 @@ class LineProfile(PlotPlugin):
return ind
def on_mouse_press(self, event):
if event.button != 1: return
if event.inaxes==None: return
if event.button != 1:
return
if event.inaxes == None:
return
self._active_pt = self.get_pt_under_cursor(event)
def on_mouse_release(self, event):
if event.button != 1: return
if event.button != 1:
return
self._active_pt = None
def on_move(self, event):
if event.button != 1: return
if self._active_pt is None: return
if not self.image_viewer.ax.in_axes(event): return
x,y = event.xdata, event.ydata
if event.button != 1:
return
if self._active_pt is None:
return
if not self.image_viewer.ax.in_axes(event):
return
x, y = event.xdata, event.ydata
self.line_changed(x, y)
def reset(self):
@@ -206,33 +215,33 @@ def profile_line(img, end_pts, linewidth=1):
is the ceil of the computed length of the scan line.
"""
point1, point2 = end_pts
x1, y1 = point1 = np.asarray(point1, dtype = float)
x2, y2 = point2 = np.asarray(point2, dtype = float)
x1, y1 = point1 = np.asarray(point1, dtype=float)
x2, y2 = point2 = np.asarray(point2, dtype=float)
dx, dy = point2 - point1
# Quick calculation if perfectly horizontal or vertical (remove?)
if x1 == x2:
pixels = img[min(y1, y2) : max(y1, y2)+1,
x1 - linewidth / 2 : x1 + linewidth / 2 + 1]
intensities = pixels.mean(axis = 1)
pixels = img[min(y1, y2): max(y1, y2) + 1,
x1 - linewidth / 2: x1 + linewidth / 2 + 1]
intensities = pixels.mean(axis=1)
return intensities
elif y1 == y2:
pixels = img[y1 - linewidth / 2 : y1 + linewidth / 2 + 1,
min(x1, x2) : max(x1, x2)+1]
intensities = pixels.mean(axis = 0)
pixels = img[y1 - linewidth / 2: y1 + linewidth / 2 + 1,
min(x1, x2): max(x1, x2) + 1]
intensities = pixels.mean(axis=0)
return intensities
theta = np.arctan2(dy,dx)
a = dy/dx
theta = np.arctan2(dy, dx)
a = dy / dx
b = y1 - a * x1
length = np.hypot(dx, dy)
line_x = np.linspace(min(x1, x2), max(x1, x2), np.ceil(length))
line_y = line_x * a + b
y_width = abs(linewidth * np.cos(theta)/2)
y_width = abs(linewidth * np.cos(theta) / 2)
perp_ys = np.array([np.linspace(yi - y_width,
yi + y_width, linewidth) for yi in line_y])
perp_xs = - a * perp_ys + (line_x + a * line_y)[:, np.newaxis]
perp_xs = - a * perp_ys + (line_x + a * line_y)[:, np.newaxis]
perp_lines = np.array([perp_ys, perp_xs])
pixels = ndi.map_coordinates(img, perp_lines)
+5 -3
View File
@@ -7,7 +7,7 @@ try:
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
except ImportError:
FigureCanvasQTAgg = object # hack to prevent nosetest and autodoc errors
FigureCanvasQTAgg = object # hack to prevent nosetest and autodoc errors
LinearSegmentedColormap = object
print("Could not import matplotlib -- skimage.viewer not available.")
@@ -33,6 +33,7 @@ def init_qtapp():
if QApp is None:
QApp = QtGui.QApplication([])
def start_qtapp():
"""Start Qt mainloop"""
QApp.exec_()
@@ -100,8 +101,9 @@ class LinearColormap(LinearSegmentedColormap):
segmented_data : dict
Dictionary of 'red', 'green', 'blue', and (optionally) 'alpha' values.
Each color key contains a list of `x`, `y` tuples. `x` must increase
monotonically from 0 to 1 and corresponds to input values for a mappable
object (e.g. an image). `y` corresponds to the color intensity.
monotonically from 0 to 1 and corresponds to input values for a
mappable object (e.g. an image). `y` corresponds to the color
intensity.
"""
def __init__(self, name, segmented_data, **kwargs):
+3 -4
View File
@@ -5,7 +5,7 @@ try:
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QMainWindow
except ImportError:
QMainWindow = object # hack to prevent nosetest and autodoc errors
QMainWindow = object # hack to prevent nosetest and autodoc errors
print("Could not import PyQt4 -- skimage.viewer not available.")
from skimage.util.dtype import dtype_range
@@ -16,7 +16,6 @@ from ..widgets import Slider
__all__ = ['ImageViewer', 'CollectionViewer']
class ImageCanvas(utils.MatplotlibCanvas):
"""Canvas for displaying images."""
def __init__(self, parent, image, **kwargs):
@@ -233,7 +232,7 @@ class CollectionViewer(ImageViewer):
first_image = image_collection[0]
super(CollectionViewer, self).__init__(first_image)
slider_kws = dict(value=0, low=0, high=self.num_images-1)
slider_kws = dict(value=0, low=0, high=self.num_images - 1)
slider_kws['update_on'] = update_on
slider_kws['callback'] = self.update_index
slider_kws['value_type'] = 'int'
@@ -254,7 +253,7 @@ class CollectionViewer(ImageViewer):
# clip index value to collection limits
index = max(index, 0)
index = min(index, self.num_images-1)
index = min(index, self.num_images - 1)
self.index = index
self.slider.val = index
+1 -1
View File
@@ -21,7 +21,7 @@ try:
from PyQt4 import QtCore
from PyQt4.QtGui import QWidget
except ImportError:
QWidget = object # hack to prevent nosetest and autodoc errors
QWidget = object # hack to prevent nosetest and autodoc errors
print("Could not import PyQt4 -- skimage.viewer not available.")
from ..utils import RequiredAttr