Exemple #1
0
 def __init__(self, image=[[0.0]]):
     from scipy import signal, misc
     import numpy as np
     self.img = np.array(image)
     dim = len(image.shape)
     derfilt = np.array([1.0, -2, 1.0], dtype=np.float32)
     if dim == 3:
         for sl1 in range(image.shape[2]):
             ck = signal.cspline2d(self.img[:, :, sl1].copy(), 8.0)
             self.img[:, :, sl1] = (signal.sepfir2d(ck, derfilt, [1]) +
                                    signal.sepfir2d(ck, [1], derfilt))
     if dim == 4:
         for sl1 in range(image.shape[2]):
             for sl2 in range(image.shape[3]):
                 ck = signal.cspline2d(self.img[:, :, sl1, sl2].copy(), 8.0)
                 self.img[:, :, sl1,
                          sl2] = (signal.sepfir2d(ck, derfilt, [1]) +
                                  signal.sepfir2d(ck, [1], derfilt))
     if dim == 5:
         for sl1 in range(image.shape[2]):
             for sl2 in range(image.shape[3]):
                 for sl3 in range(image.shape[4]):
                     ck = signal.cspline2d(
                         self.img[:, :, sl1, sl2, sl3].copy(), 8.0)
                     self.img[:, :, sl1, sl2,
                              sl3] = (signal.sepfir2d(ck, derfilt, [1]) +
                                      signal.sepfir2d(ck, [1], derfilt))
Exemple #2
0
def laplace_interp(image,
                   splineimage=None,
                   direction='vertical',
                   splinesmooth=1.0):

    if splineimage is None:
        splineimage = signal.cspline2d(image, splinesmooth)

    laplacian = np.zeros([3, 3], dtype='float32')
    laplacian[1, 1] = -2.0
    if direction in ("diagonal1", "diagonalleft"):
        laplacian[0, 0] = 1.0
        laplacian[2, 2] = 1.0
    elif direction in ("diagonal2", "diagonalright"):
        laplacian[2, 0] = 1.0
        laplacian[0, 2] = 1.0
    elif direction == 'vertical':
        laplacian[1, 0] = 1.0
        laplacian[1, 2] = 1.0
    elif direction == 'horizontal':
        laplacian[0, 1] = 1.0
        laplacian[2, 1] = 1.0

    filtered_image = signal.convolve2d(splineimage,
                                       laplacian,
                                       mode='same',
                                       boundary='symm')

    # edges have no curvature
    filtered_image[0, :] = 0.0
    filtered_image[-1, :] = 0.0
    filtered_image[:, 0] = 0.0
    filtered_image[:, -1] = 0.0

    return filtered_image
def TestLaws( mgnames, NJ = 100 ):

    # create laws filters
    filts = texture.BuildLawsFilters()
    # allocate for jets
    NI = len( mgnames ) # number of images
    jets = np.zeros( (NJ*NI, 25 ))
    # for each image
    for i in xrange( NI ):
        # load
        # correlate
        #corrs = BruteCorrelate( data, filts )
        data = mgnames[i]+0
        corrs = map( lambda x: correlate2d( data, x ), filts )
        for j in range( 25 ):
            corrs[i] = cspline2d( abs(corrs[i]), 200 )
        corrs = np.array( corrs )
        # extract random jets
        V,H = data.shape
        vs = range( V )
        hs = range( H )
        np.random.shuffle( vs ); np.random.shuffle( hs )
        for j in range( NJ ):
            jets[i*NJ + j] = corrs[:,vs[j], hs[j] ]
    # k-means clustering
    clust, mmb = kmeans.KMeans( NI, jets )
    #return jets
    cffs,evecs = pca.PCA(clust,3)
    cffs = pca.Map2PCA(clust,evecs)
    gnu.Save('Laws_results.txt',cffs)
    return clust,cffs
Exemple #4
0
def TestLaws(mgnames, NJ=100):

    # create laws filters
    filts = texture.BuildLawsFilters()
    # allocate for jets
    NI = len(mgnames)  # number of images
    jets = np.zeros((NJ * NI, 25))
    # for each image
    for i in xrange(NI):
        # load
        # correlate
        #corrs = BruteCorrelate( data, filts )
        data = mgnames[i] + 0
        corrs = map(lambda x: correlate2d(data, x), filts)
        for j in range(25):
            corrs[i] = cspline2d(abs(corrs[i]), 200)
        corrs = np.array(corrs)
        # extract random jets
        V, H = data.shape
        vs = range(V)
        hs = range(H)
        np.random.shuffle(vs)
        np.random.shuffle(hs)
        for j in range(NJ):
            jets[i * NJ + j] = corrs[:, vs[j], hs[j]]
    # k-means clustering
    clust, mmb = kmeans.KMeans(NI, jets)
    #return jets
    cffs, evecs = pca.PCA(clust, 3)
    cffs = pca.Map2PCA(clust, evecs)
    gnu.Save('Laws_results.txt', cffs)
    return clust, cffs
Exemple #5
0
def laplace_interp(image, splineimage=None, direction='vertical', splinesmooth=1.0):

    if splineimage is None:
        splineimage = signal.cspline2d(image,splinesmooth)
    
    laplacian = np.zeros([3,3],dtype='float32')
    laplacian[1,1] = -2.0
    if direction in ("diagonal1","diagonalleft"):
        laplacian[0,0] = 1.0
        laplacian[2,2] = 1.0
    elif direction in ("diagonal2","diagonalright"):
        laplacian[2,0] = 1.0
        laplacian[0,2] = 1.0
    elif direction == 'vertical':
        laplacian[1,0] = 1.0
        laplacian[1,2] = 1.0
    elif direction == 'horizontal':
        laplacian[0,1] = 1.0
        laplacian[2,1] = 1.0

    filtered_image = signal.convolve2d(splineimage,laplacian,mode='same',boundary='symm')

    # edges have no curvature
    filtered_image[0,:] = 0.0
    filtered_image[-1,:] = 0.0
    filtered_image[:,0] = 0.0
    filtered_image[:,-1] = 0.0

    return filtered_image
def filter_grid(grid, input_filter, min_value=0, size=5):
    result = None
    if input_filter == "edge":
        ck = signal.cspline2d(grid, 8.0)
        laplacian = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], float32)
        result = signal.convolve2d(ck, laplacian, mode="same", boundary="symm")
    elif input_filter == "bulge":
        ck = signal.cspline2d(grid, 8.0)
        laplacian = array([[0, 1, 0], [1, -3.9, 1], [0, 1, 0]], float32)
        grid1 = signal.convolve2d(ck, laplacian, mode="same", boundary="symm")
        grid1 = absolute(grid1)
        result = grid * 0.1 + grid1
    elif input_filter == "nearby":  # this is just a boolean filter
        mask = ones((size, size))
        edge = signal.convolve2d(grid, mask, mode="same", boundary="symm")
        result = edge > (min_value * mask.size)
    return result
Exemple #7
0
def max_curvature(image, splinesmooth=2.0):

    splineimage = signal.cspline2d(image, splinesmooth)
    curvarr = np.array([
        laplace_interp(image, splineimage, direction=D)
        for D in ['vertical', 'horizontal', 'diagonal1', 'diagonal2']
    ]) * -1.0

    return curvarr.max(axis=0)
	def filter(self):
		# img_average = numpy.average(self.training_set[0].image_data)
		image = self.training_set[0].image_data
		derfilt = numpy.array([1.0,-2,1.0],numpy.float32)
		ck = signal.cspline2d(image,8.0)
		deriv = signal.sepfir2d(ck, derfilt, [1]) + signal.sepfir2d(ck, [1], derfilt)
		print_image(deriv, 'bsplines.png')
		for std in [1,2,4,8,16,32,64,128]:
			filtered_img = ndimage.median_filter(image, std)
			print_image(filtered_img, 'median_{}.png'.format(std))
def SoftSquareAnnulus( D=512, L1=64, L2=48, sm=25 ):
    """Frame, box radii, smooth
    Creates an image array with a smoothed square annulus
    D = frame size:  answ is D x D
    L1 = half width (height) of outer annulus box
    L2 = half width (height) of inner annulus box
    sm = smoothing factor
    returns: array"""
    answ = SquareAnnulus( D, L1, L2 )
    answ = cspline2d( answ, sm )
    return answ
Exemple #10
0
def pixel_basis_to_bspline(image, bspline_degree):
    m = bspline_degree
    if m == 0:
        bspline_image = image
    elif m == 2:
        bspline_image = signal.qspline2d(image)
    elif m == 3:
        bspline_image = signal.cspline2d(image)
    else:
        sys.exit('\nERROR: B-spline degree not supported !!')
    return bspline_image
Exemple #11
0
def pixel_basis_to_bspline( image , bspline_degree ):
    m = bspline_degree
    if m == 0:
        bspline_image = image
    elif m == 2:
        bspline_image = signal.qspline2d( image )
    elif m == 3:
        bspline_image = signal.cspline2d( image )
    else:
        sys.exit('\nERROR: B-spline degree not supported !!')
    return bspline_image
Exemple #12
0
def edge_laplacian(images):
    '''Do edge detection'''

    from scipy import signal

    output = []
    dim = np.sqrt(images.shape[1])
    for image in images.reshape(len(images), dim, dim):
        ck_spline = signal.cspline2d(image, 8.0, 1.0)
        laplacian = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], np.float32)
        deriv2 = signal.convolve2d(ck_spline, laplacian, mode = 'same', boundary = 'symm')
        output.append(deriv2)
        
    return np.array(output, dtype = float).reshape(len(images), -1)
def interpolate(img_stack, slices, method='bcspline'):
    """interpolate a single frame. method can be none, bilinear, lanczos3, or bcspline"""

    #TODO: make this more efficient!!
    if method == 'none':
        return img_stack

    #create the filter based on the type of interpolation:
    if method == 'bcspline':
        #reconstruction/interpolation filter
        #3rd order bspline function
        filt = signal.bspline([-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5], 3)
    elif method == 'bilinear':
        filt = [0.5, 1.0, 0.5]
    elif method == 'lanczos3':
        #x = linspace(-2.5,2.5,11) #evenly spaced from -2.5 to 2.5 by 0.5 increments
        #filt = sinc(x/3)*sinc(x)
        filt = [
            2.44565217e-02, 0, -1.35869565e-01, 0, 6.11413043e-01, 1,
            6.11413043e-01, 0, -1.35869565e-01, 0, 2.44565217e-02
        ]

    #allocate the output array:
    #img_stack.shape is (w/2, h/2, 4)
    #we're going to expand to (w,h,4):
    s = list(img_stack.shape)
    s[:2] = np.multiply(s[:2], 2)  #element-wise multiply (w,h,4)
    #interpolated result:
    interp_stack = zeros(s)

    #interpolation coefficients for intermediate steps
    c_jk = zeros(s[:2])  #(w,h)

    #loop over last dimension (i0,i90,...)
    for j in xrange(s[-1]):
        #zero the coefficients
        c_jk[...] = 0.0
        #get coefficients
        if method in ['bilinear', 'lanczos3']:
            #coefficients are just the image slices
            c_jk[slices[j]] = img_stack[..., j]
        elif method == 'bcspline':
            #coefficients are bicubic spline coefficients for slice
            c_jk[slices[j]] = signal.cspline2d(img_stack[..., j])
        #convolve (filters are seperable, so we can use sepfir2d)
        interp_stack[..., j] = signal.sepfir2d(c_jk, filt, filt)
    #return interpolated image:
    return interp_stack
def FuzzBlocks():
    data = np.zeros((512,512))
    k = 0.0
    for v in range( 7 ):
        for h in range( 7 ):
            # create the image
            temp = np.zeros((64,64))
            temp[16:48,16:48] = 1
            if k > 0:
                temp = cspline2d( temp, k )
            # place in large array
            vv = (v+1)*64-32
            hh = (h+1)*64-32
            data[vv:vv+64,hh:hh+64] = temp + 0
            k += 1
    return data
Exemple #15
0
def edge_laplacian(images):
    '''Do edge detection'''

    from scipy import signal

    output = []
    dim = np.sqrt(images.shape[1])
    for image in images.reshape(len(images), dim, dim):
        ck_spline = signal.cspline2d(image, 8.0, 1.0)
        laplacian = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], np.float32)
        deriv2 = signal.convolve2d(ck_spline,
                                   laplacian,
                                   mode='same',
                                   boundary='symm')
        output.append(deriv2)

    return np.array(output, dtype=float).reshape(len(images), -1)
Exemple #16
0
    def Process(self, steps):
        N = len(steps)
        for command in steps:
            cName = command[0]
            if (cName == "D"):
                print("in Shift")
                yIn = command[1]
                xIn = command[2]
                vec = np.array([yIn, xIn])
                self.finalImg = nd.shift(self.finalImg, vec)
            elif (cName == "R"):
                print("in Rotate")
                deg = command[1]
                self.finalImg = nd.rotate(self.finalImg, deg)

            elif (cName == "C"):
                print("in Crop")
                top = command[1]
                bottom = command[2]
                left = command[3]
                right = command[4]
                self.finalImg = self.finalImg[top:bottom, left:right]

            elif (cName == "S"):
                print("in Smooth")
                smooth = command[1]
                self.finalImg = sg.cspline2d(self.finalImg, smooth)
            elif (cName == "L"):
                print("in Dilation")
                dil = command[1]
                self.finalImg = nd.grey_dilation(self.finalImg, dil)
            elif (cName == "T"):
                print("in Square Root")
                self.finalImg = np.sqrt(self.finalImg)
            elif (cName == "P"):
                print("in Passive Threshold")
                thresh = command[1]
                lowValIndic = self.finalImg < thresh
                self.finalImg[lowValIndic] = 0
        sm.imsave("finalImag.jpg", self.finalImg)
Exemple #17
0
def test_cspline2d():
    np.random.seed(181819142)
    image = np.random.rand(71, 73)
    signal.cspline2d(image, 8.0)
Exemple #18
0
def max_curvature(image, splinesmooth=2.0):

    splineimage = signal.cspline2d(image,splinesmooth)
    curvarr = np.array([laplace_interp(image,splineimage,direction=D) for D in ['vertical','horizontal','diagonal1','diagonal2']]) * -1.0

    return curvarr.max(axis=0)
Exemple #19
0
    # the transpose makes the coordinates of images match those of matrices
    img_array = np.array(img).transpose()

    img.close()

    # x_points = []
    # y_points = []
    # for i in range(len(img_array)):
    #     for j in range(len(img_array[i])):
    #         if img_array[i][j] == 1:
    #             x_points.append(i)
    #             y_points.append(j)
    #
    # tck = interpolate.splrep(x_points, y_points)

    derfilt = np.array([1.0, -2, 1.0], dtype=np.float32)
    ck = signal.cspline2d(img_array, 8.0)
    deriv = (signal.sepfir2d(ck, derfilt, [1]) +
             signal.sepfir2d(ck, [1], derfilt))

    plt.figure()
    plt.imshow(deriv)
    plt.gray()
    plt.title('Output of spline edge filter')

    image_file_name = image_file_name.replace(input_extension, '')
    plt.savefig(OUTPUT_DIR + image_file_name + '.pdf')
    plt.show()
    plt.close()
    # np.savetxt(OUTPUT_DIR + image_file_name + '.txt', [[contour[:, 1], contour[:, 0]] for contour in contours], fmt='%s')
Exemple #20
0
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt

image = misc.face(gray=True).astype(np.float32)
derfilt = np.array([1.0, -2, 1.0], dtype=np.float32)
ck = signal.cspline2d(image, 8.0)
deriv = (signal.sepfir2d(ck, derfilt, [1]) + signal.sepfir2d(ck, [1], derfilt))

# Alternatively we could have done::

# laplacian = np.array([[0,1,0], [1,-4,1], [0,1,0]], dtype=np.float32)
# deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm')

plt.figure()
plt.imshow(image)
plt.gray()
plt.title('Original image')
plt.show()

plt.figure()
plt.imshow(deriv)
plt.gray()
plt.title('Output of spline edge filter')
plt.show()
Exemple #21
0
def edgeDetect2(imageArray):
    derfilt = numpy.array([1.0,-2,1.0],numpy.float32)
    ck = signal.cspline2d(imageArray,8.0)
    deriv = signal.sepfir2d(ck, derfilt, [1]) + signal.sepfir2d(ck, [1], derfilt)
    return deriv
============================
To smoothen the input raw satellite image or image with general formats using various 
smoothing filters such as average filter, Weighted average filter, Gaussian smoothing, etc.
============================
created: 17/08/2015
*auhor: [email protected]*
'''
from scipy import misc, signal
import numpy as np

x = misc.lena()
x1 = misc.lena().astype(np.float32)
w = signal.gaussian(50, 5.0)
laplacian = np.array([[0,1,0], [1,-4,1], [0,1,0]], dtype=np.float32)
derfilt = np.array([1.0, -2, 1.0], dtype=np.float32)
ck = signal.cspline2d(x1, 8.0)
deriv = (signal.sepfir2d(ck, derfilt, [1]) + signal.sepfir2d(ck, [1], derfilt))
im1 = signal.convolve2d(x1,laplacian,mode='same',boundary='symm')
im2 = signal.sepfir2d(x, w, w) 
plt.figure()
plt.subplot(221)
plt.imshow(x)
plt.title('original image')
plt.subplot(222)
plt.imshow(im1)
plt.title('laplacian filter image')
plt.subplot(223)
plt.imshow(im2)
plt.title('gaussian blurred iamge')
plt.subplot(224)
plt.imshow(deriv)
Exemple #23
0
def edgeDetect2(imageArray):
    derfilt = numpy.array([1.0, -2, 1.0], numpy.float32)
    ck = signal.cspline2d(imageArray, 8.0)
    deriv = signal.sepfir2d(ck, derfilt, [1]) + signal.sepfir2d(
        ck, [1], derfilt)
    return deriv
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt
img = misc.lena()

splineresult = signal.cspline2d(img, 2.0)
laplacian = np.array([[-1,0,1], [-2,0,2], [-1,0,1]], dtype=np.float32)
derivative = signal.convolve2d(splineresult,laplacian,mode=’same’,boundary=’symm’)
plt.figure()
plt.imshow(derivative)
plt.title(’Image filtered by spline edge filter’)
plt.show()
Exemple #25
0
# Purpose:  Image test from examples (header added)
# Date:     N/A
# Notes:
# 1) from examples
# Ref: http://docs.scipy.org/doc/scipy/reference/tutorial/signal.html 

import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt

# import the image -- pre-defined
image = misc.lena().astype(np.float32)

# filter the image
derfilt = np.array([1.0, -2, 1.0], dtype=np.float32)
ck = signal.cspline2d(image, 8.0)
deriv = (signal.sepfir2d(ck, derfilt, [1]) +
         signal.sepfir2d(ck, [1], derfilt))

laplacian = np.array([[0,1,0], [1,-4,1], [0,1,0]], dtype=np.float32)
deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm')

# plot the original
plt.figure()
plt.imshow(image)
plt.gray()
plt.title('Original image')
plt.show()

# plot the edge filter
plt.figure()