In [7]:
from __future__ import division
%pylab inline
from scipy import ndimage
img = imread('MP.tif')[...,0]
Use with:
def f(var1, var2, ...):
# do something with variables
interact(f, var1=(start,stop,step), var2=True, var3=3, ...)
See using interact for more.
In [17]:
from IPython.html.widgets import interact
In [2]:
def gimshow(img, size=(12,12), title=''):
"Shows grayscale image."
figure(figsize=size)
plt.title(title)
imshow(img, cmap='gray')
In [1]:
def histshow(img):
"Shows a histogram figure of image."
hist = np.bincount(img.flatten())
figure()
title('Levels in image')
xlim((0, hist.size))
plot(hist)
showhist = histshow
Histogram equalization algoritm, for improving detail in image.
In [4]:
def equalization(img):
"Return histogram equaliated image."
hist = np.bincount(img.flatten())
cdf = (hist / img.size).cumsum()
equal_img = np.zeros(img.shape, dtype=np.uint8)
for level in range(1,256): # exclude zeroes
if hist[level] == 0: continue # short cut
mask = (img == level)
equal_img[mask] = cdf[level] * 255
return equal_img
Function which smooth image with convolution.
Some fractions are impossible to store accurate in binary (and also other number systems). Here is one example:
$1/9 = (0.1111...)_{10}$ $ = (0.000111000111...)_2$ $ = (0.1)_3$
Which is the normalization used for 3x3 mask. Since np.convolute is linear, a rounding error will prevail. Therefor we add 1e-12 to all cells accomodate for this, assuming steps (normalize constant) are far above 1e-12.
In [6]:
def smooth(img, size=3):
"""
Smooths image by convolution. Default mask is 3x3.
Variables
---------
img : ndarray
Input image to smooth.
size : int
Size of square smoothing mask. Should be 2n+1.
Returns
-------
result : ndarray
Smoothed image.
"""
mask = np.ones((size,size))
mask /= mask.sum() #normalize
return ndimage.convolve(img+1e-12, mask).astype(np.uint8)
As defined in 2.6-10 and 2.6-11 in GW page 79.
In [6]:
def scale(img):
"Scales intensities in image to span whole image."
s = np.copy(img).astype(np.float)
s -= s.min()
s *= 255 / s.max()
return s.astype(np.uint8)