Пример #1
0
def sim_matrix_find_segments(arr, length1=10, length2=10):
    length1 = max(length1, 1)
    length2 = max(length2, 2)

    length1 = min(length1, (len(arr) / 2) - 1)
    length2 = min(length2, (len(arr) / 2) - 1)

    k1 = range(1, length1) + range(length1, 0, -1)
    k2 = range(1, length2) + range(length2 - 1, 0, -1)

    k1 = array(k1, Float32) / sqrt(sum(k1))

    #print k1

    for i in range(0, len(k2) / 2):
        #for i in range(0, len(k2), 2):
        k2[i] = -k2[i]

    #print k1, type(k1)
    #print k2, type(k2)
    k2 = array(k2)
    #print "f**k signal.sepfir2d"
    #print arr
    res1 = signal.sepfir2d(arr, k1, k1)
    #print res1
    res2 = signal.sepfir2d(res1, k2, k2)
    #print shape(res2)
    return abs(res2)
Пример #2
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))
Пример #3
0
def test_sepfir2d_invalid_image():
    filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])
    image = np.random.rand(8, 8)

    # Image must be 2 dimensional
    with pytest.raises(ValueError, match="object too deep"):
        signal.sepfir2d(image.reshape(4, 4, 4), filt, filt)

    with pytest.raises(ValueError, match="object of too small depth"):
        signal.sepfir2d(image[0], filt, filt)
Пример #4
0
 def sobel3x3_separable(image):
     
     sobel_c = array([-1.,0.,1.])
     sobel_r = array([1.,2.,1.])
     
     imgx = signal.sepfir2d(image, sobel_c, sobel_r)
     imgy = signal.sepfir2d(image, sobel_r, sobel_c)
         
     mag = sqrt(imgx**2 + imgy**2) + 1e-16
     
     return (mag, imgx, imgy)
Пример #5
0
def show_angle(angle,power):
    ARROW_STEP = 40
    kernel = np.ones((ARROW_STEP,ARROW_STEP))
    rowFilter = gaussian(ARROW_STEP,ARROW_STEP/5)
    colFilter = rowFilter
    
    gb180 = cmt.get_cmap('gb180')
    
    #X = np.arange(0,angle.shape(-1),ARROW_STEP)
    #Y = np.arange(0,angle.shape(-2),ARROW_STEP)

    x = np.matrix(np.arange(ARROW_STEP/2,angle.shape[-1],ARROW_STEP))
    y = np.transpose(np.matrix(np.arange(ARROW_STEP/2,angle.shape[-2],ARROW_STEP)))

    X = np.array((0*y+1)*x)
    Y = np.array(y*(0*x+1))
    
    #u = convolve2d(sin(angle),kernel,mode='same')
    #v = convolve2d(cos(angle),kernel,mode='same')
    #p = convolve2d(power,kernel,mode='same')
    
    u = sepfir2d(np.sin(angle),rowFilter,colFilter)
    v = sepfir2d(np.cos(angle),rowFilter,colFilter)
    p = sepfir2d(power,rowFilter,colFilter)
    
    U = u[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]*p[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]
    V = v[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]*p[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP]
    
    #U = sin(angle[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])*(power[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])
    #V = cos(angle[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])*(power[ARROW_STEP/2::ARROW_STEP,ARROW_STEP/2::ARROW_STEP])

    #X = X[(power[::ARROW_STEP,::ARROW_STEP]>.016)]
    #Y = Y[(power[::ARROW_STEP,::ARROW_STEP]>.016)]
    #U = U[(power[::ARROW_STEP,::ARROW_STEP]>.016)]
    #V = V[(power[::ARROW_STEP,::ARROW_STEP]>.016)]
    
    ua = ARROW_STEP/1.5*np.nansum(np.sin(angle)*power)/np.nansum(power)
    va = -ARROW_STEP/1.5*np.nansum(np.cos(angle)*power)/np.nansum(power)
    xc, yc = angle.shape[-1]/2, angle.shape[-2]/2
    
    pylab.imshow(angle,cmap=gb180)
    #pylab.imshow(angle,cmap='hsv')
    pylab.quiver(X,Y,U,V,pivot='middle',color='w',headwidth=1,headlength=0)
    pylab.arrow(xc,yc,ua,va,color='w',linewidth=2)
    pylab.arrow(xc,yc,-ua,-va,color='w',linewidth=2)
    ax=pylab.gca()
    ax.set_axis_off()
    pylab.show()

    A = np.arctan2(-ua,va)
    return A
Пример #6
0
    def dog_sep_convolution(self,
                            img,
                            k,
                            cell_type,
                            originating_function="filter",
                            force_homebrew=False,
                            mode="full"):
        ''' Wrapper for separated convolution for DoG kernels in FoCal, 
        enables use of NumPy based sepfir2d.
        
        img                  => the image to convolve
        k                    => 1D kernels to use
        cell_type            => ganglion cell type, useful for sampling 
                                resolution numbers
        originating_function => if "filter": use special sampling resolution,
                                else: use every pixel
        force_hombrew        => if True: use my code, else: NumPy's
        mode                 => "full" all image convolution, else only valid
    '''

        if originating_function == "filter":
            row_keep, col_keep = self.get_subsample_keepers(cell_type)
        else:
            row_keep, col_keep = 1, 1

        if not force_homebrew:
            # has a problem with images smaller than kernel
            right_img = sepfir2d(img.copy(), k[0], k[1])
            left_img = sepfir2d(img.copy(), k[2], k[3])
        else:
            right_img = self.sep_convolution(img,
                                             k[0],
                                             k[1],
                                             col_keep=col_keep,
                                             row_keep=row_keep,
                                             mode=mode)
            left_img = self.sep_convolution(img,
                                            k[2],
                                            k[3],
                                            col_keep=col_keep,
                                            row_keep=row_keep,
                                            mode=mode)

        conv_img = left_img + right_img

        if not force_homebrew and originating_function == "filter":
            conv_img = self.subsample(conv_img, cell_type)

        return conv_img
Пример #7
0
def impyramid_next_level(_img, filter='burt_adelson'):
    """
    IMPYRAMID_NEXT_LEVEL: computes the next level in a Gaussian pyramidal
     decomposition.

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :param filter: string
    Which filter to use in removing high frequencies:
    - burt_adelson: [-0.125, 0.250, 0.375, 0.250, -0.125]
    - custom1: [0.125, 0.275, 0.375, 0.125]  (Gaussian, sigma=0.866)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    assert (_img.ndim == 2)

    # classical low-pass filter, with the kernel from Burt & Adelson (1983):
    if filter == 'burt_adelson':
        a = 0.375
        krn = [1 / 4 - a / 2, 1 / 4, a, 1 / 4, 1 / 4 - a / 2]
        res = (_img - sepfir2d(_img, krn, krn))[::2, ::2]
    elif filter == 'custom1':
        res = gaussian_filter(_img, sigma=0.866)[::2, ::2]

    return res
Пример #8
0
def impyramid_next_level(_img, filter='burt_adelson'):
    """
    IMPYRAMID_NEXT_LEVEL: computes the next level in a Gaussian pyramidal
     decomposition.

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :param filter: string
    Which filter to use in removing high frequencies:
    - burt_adelson: [-0.125, 0.250, 0.375, 0.250, -0.125]
    - custom1: [0.125, 0.275, 0.375, 0.125]  (Gaussian, sigma=0.866)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    assert (_img.ndim == 2)

    # classical low-pass filter, with the kernel from Burt & Adelson (1983):
    if filter == 'burt_adelson':
        a = 0.375
        krn = [1/4 - a/2, 1/4, a, 1/4, 1/4 - a/2]
        res = (_img - sepfir2d(_img, krn, krn))[::2, ::2]
    elif filter == 'custom1':
        res = gaussian_filter(_img, sigma=0.866)[::2, ::2]

    return res
Пример #9
0
def test_sepfir2d_invalid_filter():
    filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])
    image = np.random.rand(7, 9)
    # No error for odd lengths
    signal.sepfir2d(image, filt, filt[2:])

    # Row or column filter must be odd
    with pytest.raises(ValueError, match="odd length"):
        signal.sepfir2d(image, filt, filt[1:])
    with pytest.raises(ValueError, match="odd length"):
        signal.sepfir2d(image, filt[1:], filt)

    # Filters must be 1-dimensional
    with pytest.raises(ValueError, match="object too deep"):
        signal.sepfir2d(image, filt.reshape(1, -1), filt)
    with pytest.raises(ValueError, match="object too deep"):
        signal.sepfir2d(image, filt, filt.reshape(1, -1))
Пример #10
0
def themis_plot_phasespace_contour(vlsvReader,
                                   cellID,
                                   plane_x=np.array([1., 0, 0]),
                                   plane_y=np.array([0, 0, 1.]),
                                   smooth=False,
                                   xlabel="Vx",
                                   ylabel="Vy"):
    ''' Plots a contour view of phasespace, as seen by a themis detector, at the given cellID
    :param vlsvReader:        Some VlsvReader class with a file open
    :type vlsvReader:         :class:`vlsvfile.VlsvReader`
    :param cellid:            The cell id where the distribution is supposet to be sampled NOTE: The cell id must have a velocity distribution!
    :param plane_x and plane_y: x and y direction of the resulting plot plane
    '''

    matrix = simulation_to_observation_frame(plane_x, plane_y)

    angles, energies, vmin, vmax, values = themis_observation_from_file(
        vlsvReader=vlsvReader, cellid=cellID, matrix=matrix)

    if vmin == 0:
        vmin = 1e-15
    if vmax <= vmin:
        vmax = vmin * 10.

    # Regrid into cartesian space, 256x256:
    grid_r, grid_theta = np.meshgrid(energies, angles)

    grid_x = -grid_r * np.sin(
        grid_theta)  # turn radial grid points into (x, y)
    grid_y = -grid_r * np.cos(
        grid_theta
    )  # (the - comes from detector-look-direction vs particle-movement-direction)

    hires_x = np.linspace(-2200, 2200, 256)
    hires_y = np.linspace(-2200, 2200, 256)
    xi, yi = np.meshgrid(hires_x, hires_y)
    vi = griddata((grid_x.flatten(), grid_y.flatten()), values.flatten(),
                  (xi, yi))

    if smooth:
        # Convolve the grid data with a gaussian kernel
        blurkernel = np.exp(
            -.17 * np.power([6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6], 2))
        vi = sepfir2d(vi, blurkernel, blurkernel) / 4.2983098411528502

    fig, ax = pl.subplots(figsize=(12, 10))
    ax.set_aspect('equal')
    ax.set_title("Phasespace at cell " + str(cellID))
    ax.set_xlabel(xlabel + " (km/s)")
    ax.set_ylabel(ylabel + " (km/s)")
    cax = ax.contour(xi,
                     yi,
                     vi.T,
                     levels=np.logspace(np.log10(vmin), np.log10(vmax), 20),
                     norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax))
    ax.grid(True)
    fig.colorbar(cax)
    pl.show()
Пример #11
0
def themis_plot_phasespace_helistyle(vlsvReader, cellID, plane_x=np.array([1.,0,0]), plane_y=np.array([0,0,1.]), smooth=True, xlabel="Vx", ylabel="Vy", vmin_min=1e-16):
    ''' Plots a view of phasespace, as seen by a themis detector, at the given cellID, in the style that heli likes.
    :param vlsvReader:        Some VlsvReader class with a file open
    :type vlsvReader:         :class:`vlsvfile.VlsvReader`
    :param cellid:            The cell id where the distribution is supposet to be sampled NOTE: The cell id must have a velocity distribution!
    :param smooth:            Smooth re-gridded phasespace before plotting
    :param plane_x and plane_y: x and y direction of the resulting plot plane
    '''

    matrix = simulation_to_observation_frame(plane_x,plane_y)

    angles, energies, vmin, vmax, values = themis_observation_from_file( vlsvReader=vlsvReader, cellid=cellID, matrix=matrix, countrates=False, noise=False)
    if vmin == 0:
        vmin = vmin_min
    if vmax < vmin:
        vmax = vmin*10

    # Regrid into cartesian space, 256x256:
    grid_r, grid_theta = np.meshgrid(energies,angles)

    grid_x = -grid_r * np.sin(grid_theta)  # turn radial grid points into (x, y)
    grid_y = -grid_r * np.cos(grid_theta)

    hires_x = np.linspace(-2200,2200,256);
    hires_y = np.linspace(-2200,2200,256);
    xi,yi = np.meshgrid(hires_x,hires_y);
    vi = griddata( (grid_x.flatten(),grid_y.flatten()), values.flatten(), (xi,yi), method='linear')

    if smooth:
        # Convolve the grid data with a gaussian kernel
        blurkernel = np.exp(-.17*np.power([6,5,4,3,2,1,0,1,2,3,4,5,6],2))
        vi = sepfir2d(vi, blurkernel, blurkernel) / 4.2983098411528502

    fig,ax=pl.subplots(figsize=(12,10))
    ax.set_aspect('equal')
    ax.set_title("Phasespace at cell " + str(cellID))
    ax.set_xlabel(xlabel+" (km/s)")
    ax.set_ylabel(ylabel+" (km/s)")
    vi *= 10.**-3 # Go from s^3 m^-6 to s^3 km^-3 cm^-3
    vmin *= 10.**-3
    vmax *= 5*10.**-3
    cax = ax.pcolormesh(xi,yi,vi.T, norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), vmin=vmin, vmax=vmax, cmap=pl.get_cmap("Blues"), shading='flat')
    cax2 = ax.contourf(xi,yi,vi.T, levels=np.logspace(np.log10(vmin),np.log10(vmax),20), norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), vmin=vmin, vmax=vmax, cmap=pl.get_cmap("Blues"))
    #cax3 = ax.contour(xi,yi,vi.T, levels=np.logspace(np.log10(vmin),np.log10(vmax),20), norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax), cmap=pl.get_cmap("binary"))
    ax.grid(True)

    # Draw a circle at themis max extents
    angles = np.linspace(0,2*np.pi,180)
    x = 2188*np.cos(angles)
    y = 2188*np.sin(angles)
    ax.plot(x,y)

    cb = fig.colorbar(cax)
    cb.set_label("Phasespace density (s^3 km^-3 cm^3)")
    #pl.show()

    return ax
Пример #12
0
def lowpass(image):
	points = 100
	std_dev = 10.0
	w = signal.gaussian(points, std_dev)
	lowpass_image = signal.sepfir2d(image, w, w)
	avg_image = numpy.mean(image)
	lowpass_avg_image = numpy.mean(lowpass_image)
	lowpass_im = lowpass_image * avg_image / lowpass_avg_image
	return lowpass_im
Пример #13
0
def filterImage(image, filter_size):
    """
    Filter the image with a rectangular filter

    filter_size, (int,int) : size of the filter to apply
    """
    hrow = [1. / filter_size[1]] * filter_size[1]
    hcol = [1. / filter_size[0]] * filter_size[0]
    image = image - signal.sepfir2d(image, hrow, hcol)
    return image
Пример #14
0
def filterImage(image, filter_size):
    """
    Filter the image with a rectangular filter

    filter_size, (int,int) : size of the filter to apply
    """
    hrow = [1./filter_size[1]]*filter_size[1]
    hcol = [1./filter_size[0]]*filter_size[0]
    image = image - signal.sepfir2d(image, hrow, hcol)
    return image
Пример #15
0
def blur(phi, window=.2):
    """
    Gaussian blur of basis functions
    """
    C, N, P = phi.shape
    w = np.int(window * min(C,P))
    g = signal.gaussian(w, 1)
    philp = np.empty_like(phi)
    for i in range(N):
        philp[:,i] = signal.sepfir2d(phi[:,i], g, g)
    return philp
Пример #16
0
def blur(phi, window=.2):
    """
    Gaussian blur of basis functions
    """
    C, N, P = phi.shape
    w = np.int(window * min(C,P))
    g = signal.gaussian(w, 1)
    philp = np.empty_like(phi)
    for i in range(N):
        philp[:,i] = signal.sepfir2d(phi[:,i], g, g)
    return philp
Пример #17
0
def heatMap (xy):
    # First calculate the 2D histogram
    hist2d, xedges, yedges = np.histogram2d(xy[:,1], xy[:,0], bins=(100, 100))
    # Then blur the histogram
    filtx = signal.gaussian(15, 15/6.0)
    filtx = filtx/sum(filtx)
    filty = filtx
    hist2d = signal.sepfir2d(hist2d, filtx, filty)

    # Calculate the range / extent    
    extent = array([amin(xy[:,0]), amax(xy[:,0]), amin(xy[:,1]), amax(xy[:,1])])
    return (hist2d, extent)
Пример #18
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))
Пример #19
0
def dog_sep_convolution(img, k, cell_type, originating_function="filter",
                        only_positives=False,
                        sampling_resolution="basab",
                        force_homebrew = False):

    if force_homebrew:
        use_numpy = False
    else:
        use_numpy = True #if k[0].size < numpy.sqrt(img.shape[0]*img.shape[1])/2 else False

    #print("filtering for cell type idx %s (numpy? %s)"%(cell_type, use_numpy))

    if originating_function == "filter":
        row_keep, col_keep = get_subsample_keepers(img, cell_type, k, 
                                                   sampling_resolution=sampling_resolution)
    else:
        row_keep, col_keep = 1, 1

    if use_numpy == True:
        right_img = sepfir2d(img.copy(), k[0], k[1])
        left_img  = sepfir2d(img.copy(), k[2], k[3])

    else:

        right_img = sep_convolution(img, k[0], k[1], 
                                    col_keep=col_keep, row_keep=row_keep)
        left_img  = sep_convolution(img, k[2], k[3], 
                                    col_keep=col_keep, row_keep=row_keep)

    c = left_img + right_img
    #print("after addition")
    if only_positives:
        c = c*(c>0)
        #print("after only_positives")

    if use_numpy == True and originating_function == "filter":
        c = subsample(c, cell_type, k, sampling_resolution=sampling_resolution)


    return c
Пример #20
0
  def dog_sep_convolution(self, img, k, cell_type, originating_function="filter",
                          force_homebrew = False, mode="full"):
    ''' Wrapper for separated convolution for DoG kernels in FoCal, 
        enables use of NumPy based sepfir2d.
        
        img                  => the image to convolve
        k                    => 1D kernels to use
        cell_type            => ganglion cell type, useful for sampling 
                                resolution numbers
        originating_function => if "filter": use special sampling resolution,
                                else: use every pixel
        force_hombrew        => if True: use my code, else: NumPy's
        mode                 => "full" all image convolution, else only valid
    '''

    if originating_function == "filter":
        row_keep, col_keep = self.get_subsample_keepers(cell_type)
    else:
        row_keep, col_keep = 1, 1

    if not force_homebrew:
      # has a problem with images smaller than kernel
      right_img = sepfir2d(img.copy(), k[0], k[1])
      left_img  = sepfir2d(img.copy(), k[2], k[3])
    else:
      right_img = self.sep_convolution(img, k[0], k[1], col_keep=col_keep, 
                                       row_keep=row_keep, mode=mode)
      left_img  = self.sep_convolution(img, k[2], k[3], col_keep=col_keep, 
                                       row_keep=row_keep, mode=mode )

    conv_img = left_img + right_img

    if not force_homebrew and originating_function == "filter":
        conv_img = self.subsample(conv_img, cell_type)

    return conv_img
Пример #21
0
    def detect_edges(self, img):
        logging.debug('Detecting horizontal and vertical edges in screen')
        mat = np_from_img(img)
        gradient_kernel = (0, 1, 0, -1, 0)
        smoothing_kernel = np.ones((7), dtype='float32')

        vertical_edges = sepfir2d(mat, gradient_kernel, smoothing_kernel) / 7
        vertical_edges_positive = vertical_edges * (vertical_edges > 0)
        vertical_edges_negative = vertical_edges * (vertical_edges < 0)
        vertical_edges = (np.roll(vertical_edges_positive, -1, axis=1) -
                          np.roll(vertical_edges_negative, 1, axis=1)) / 2

        horizontal_edges = sepfir2d(mat, smoothing_kernel, gradient_kernel) / 7
        horizontal_edges_positive = horizontal_edges * (horizontal_edges > 0)
        horizontal_edges_negative = horizontal_edges * (horizontal_edges < 0)
        horizontal_edges = (np.roll(horizontal_edges_positive, -1, axis=0) -
                            np.roll(horizontal_edges_negative, 1, axis=0)) / 2

        if self.config.dump_x_gradients:
            img_from_np(vertical_edges).save(self.config.dump_x_gradients)
        if self.config.dump_y_gradients:
            img_from_np(horizontal_edges).save(self.config.dump_y_gradients)

        return horizontal_edges, vertical_edges
Пример #22
0
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 themis_plot_phasespace_contour(vlsvReader, cellID, plane_x=np.array([1.,0,0]), plane_y=np.array([0,0,1.]), smooth=False, xlabel="Vx", ylabel="Vy"):
    ''' Plots a contour view of phasespace, as seen by a themis detector, at the given cellID
    :param vlsvReader:        Some VlsvReader class with a file open
    :type vlsvReader:         :class:`vlsvfile.VlsvReader`
    :param cellid:            The cell id where the distribution is supposet to be sampled NOTE: The cell id must have a velocity distribution!
    :param plane_x and plane_y: x and y direction of the resulting plot plane
    '''

    matrix = simulation_to_observation_frame(plane_x,plane_y)

    angles, energies, vmin, vmax, values = themis_observation_from_file( vlsvReader=vlsvReader, cellid=cellID, matrix=matrix)

    if vmin == 0:
        vmin = 1e-15
    if vmax <= vmin:
        vmax = vmin * 10.

    # Regrid into cartesian space, 256x256:
    grid_r, grid_theta = np.meshgrid(energies,angles)

    grid_x = -grid_r * np.sin(grid_theta)  # turn radial grid points into (x, y)
    grid_y = -grid_r * np.cos(grid_theta)  # (the - comes from detector-look-direction vs particle-movement-direction)

    hires_x = np.linspace(-2200,2200,256);
    hires_y = np.linspace(-2200,2200,256);
    xi,yi = np.meshgrid(hires_x,hires_y);
    vi = griddata( (grid_x.flatten(),grid_y.flatten()), values.flatten(), (xi,yi))

    if smooth:
        # Convolve the grid data with a gaussian kernel
        blurkernel = np.exp(-.17*np.power([6,5,4,3,2,1,0,1,2,3,4,5,6],2))
        vi = sepfir2d(vi, blurkernel, blurkernel) / 4.2983098411528502

    fig,ax=pl.subplots(figsize=(12,10))
    ax.set_aspect('equal')
    ax.set_title("Phasespace at cell " + str(cellID))
    ax.set_xlabel(xlabel+" (km/s)")
    ax.set_ylabel(ylabel+" (km/s)")
    cax = ax.contour(xi,yi,vi.T, levels=np.logspace(np.log10(vmin),np.log10(vmax),20), norm=matplotlib.colors.LogNorm(vmin=vmin,vmax=vmax))
    ax.grid(True)
    fig.colorbar(cax)
    pl.show()
 def separable_convolution2d(self, im, row, col, **kwargs):
     print im.shape
     print row.shape
     print col.shape
     return sepfir2d(array(im), row, col)
Пример #25
0
 def transform(self):
     Iν = self.I.copy()
     Iν[self.i, self.j] = self.Iν
     return DImage(signal.sepfir2d(Iν, self.G, self.G))
Пример #26
0
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt
#need to pip install matplotlib first

image = misc.ascent()
w = signal.gaussian(50, 10.0)
image_new = signal.sepfir2d(image, w, w)

plt.figure()
plt.imshow(image_new)  #顯示濾波後的圖形
plt.gray()
plt.title('Filtered image')
plt.show()
Пример #27
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()
Пример #28
0
# 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()
plt.imshow(deriv)
Пример #29
0
    data=np.asarray(img)
    return data
def g(v, std):
    x = v[0]
    y = v[1]
    return  np.exp(-((x ** 2) + (y ** 2)) / (2 * std ** 2))# * (1.0 / (2 * np.pi * std ** 2))
#x is the axis of 121 data, from -3~3, k is the calculated value of the gaussian function at integer coordinates
x = np.linspace(-3, 3, 121)
xy = np.meshgrid(x, x)
k = g(xy, 5.0)
k = k[::20, ::20]

#load the image
img = loadtiffs('C:/Users/90759/Desktop/Teaching_python-master/Teaching_python-master/week_2/data/640.tif)
 #use convolve and fftconcolve to do the convolution to filter the image
img_con = signal.convolve(img, k, mode = "valid")
img_fft = signal.fftconvolve(img, k, mode = "valid")
#use sepfir2d to filter the image
w = signal.gaussian(7, std = 5.0)
img_sep = signal.sepfir2d(img, w, w)
#show the result
plt.gray()
plt.subplot(221, title = "orginal")
plt.imshow(img)
plt.subplot(222, title = "fftconvolve")
plt.imshow(img_fft)
plt.subplot(223, title = "sepfir2d")
plt.imshow(img_sep)
plt.subplot(224, title = "convolve")
plt.imshow(img_con)
Пример #30
0
def horizontal_fir2d_filter(arr, width=10, factor=10 / 12.0):
    fir2d = signal.sepfir2d(arr, [1] * width, [1])
    return greater(arr, fir2d / width * factor) * arr
Пример #31
0
#!/usr/bin/python
NOTES = '''
Author: Joe Warga
Date: 2014-11-07
'''

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

image = misc.lena()
w = signal.gaussian(50, 5.0)
image_new = signal.sepfir2d(image, w, w)

plt.figure()
plt.imshow(image_new)
plt.gray()
plt.title('Filtered image')
plt.show()
Пример #32
0
Spyder Editor

Este é um arquivo de script temporário.
"""
from pylab import imread, imshow, figure, subplot
from scipy.signal import sepfir2d, gaussian
from numpy import uint8, float32, array


def norm8(img):
    mn = img.min()
    mx = img.max()
    I = (img - mn) / (mx - mn) * 255
    return I.astype(uint8)


filtro = gaussian(30, 20.0).astype(float32)
# possível solução
lena = array(imread('dat/lena.dat'))
face = lena[180:390, 250:350]  # rosto
figure(figsize=(10, 8), dpi=80)
subplot(2, 2, 1)
imshow(face)
emba = sepfir2d(lena[200:390, 250:350], filtro, filtro)  # embaçamento
embb = norm8(emba)
subplot(2, 2, 2)
imshow(embb)
#copia.setflags(write=1)
lena[200:390, 250:350] = embb
subplot(2, 1, 2)
imshow(lena)
Пример #33
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
Пример #34
0
 def separable_convolution2d(self, im, row, col, **kwargs):
     print im.shape
     print row.shape
     print col.shape
     return sepfir2d(array(im), row, col)
 def separable_convolution2d(self, im, row, col, **kwargs):
     return sepfir2d(im, row, col)
Пример #36
0
    the precision used when computing the infinite sum needed to apply mirror-
    symmetric boundary conditions.


'''

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

img = mpimg.imread('Screenshot.png')
print img
imgplot = plt.imshow(img)
#plt.show()
image = misc.lena().astype("float32")
imgplot = plt.imshow(image)
plt.show()
derfilt = np.array([1.0, -2, 1.0], "float32")
ck = signal.cspline2d(image, 8.0)
deriv = signal.sepfir2d(ck, derfilt, [1]) + \
    signal.sepfir2d(ck, [1], derfilt)
'''
Alternative:
laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],float32)
deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm')
'''
plt.gray()
imgplot = plt.imshow(deriv)
plt.show()
Пример #37
0
plt.show()



# -----------------------------------------------------------------------------
# SIGNAL PROCESSING

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

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))
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()

image = misc.face(gray = True)
w = np.zeros((50, 50))
w[0][0] = 1.0
Пример #38
0
def gradient(image):
    p = np.array([0.0377, 0.2492, 0.4264, 0.2492, 0.0377]).astype(np.float32)
    d = np.array([0.1096, 0.2767, 0, -0.2767, -0.1096]).astype(np.float32)
    grad_x = -signal.sepfir2d(image, d, p)
    grad_y = signal.sepfir2d(image, p, d)
    return grad_x, grad_y
Пример #39
0
def border_fir2d_filter(arr, filter_x=[1] * 3, filter_y=[1] * 10):
    return greater(
        fast_horizontal_filter(signal.sepfir2d(arr, filter_x, filter_y)),
        0) * arr
Пример #40
0
def plot_log_agn_postcard(MBH, eddrate, 
	# from Baskin & Laor (2017)
	rad_efficiency = 0.1,
	Z = 5, # metallicity
	# Radiative Fountain system assumptions
	dust_to_gas_ratio = 1/20.,
	kappa = 1e3 * u.cm**2/u.g,
	rho_g = 300 * u.Msun / u.pc**3,
	show_BH = True,
	show_corona = True,
	show_disk = True,
	show_BLR = True,
	show_NLR = True,
	show_jet = True,
	show_TOR = True,
	show_SOI = True,
	show_viewing = True,
	colored_disk = True,
	show_flows = True,
):
	L_AGN_edd = compute_eddington_luminosity(MBH)

	L_AGN = eddrate * L_AGN_edd
	L_AGN_46 = (L_AGN / (1e46 * u.erg/u.s)).to(1)
	L_AGN_edd = compute_eddington_luminosity(MBH)
	r_grav = compute_grav_radius(MBH).to(u.pc)

	M_dot = (L_AGN / c.c**2 / rad_efficiency).to(u.Msun / u.yr)
	
	R_in = compute_sublimation_radius(MBH, M_dot)
	# from Kormendy & Ho+13, compute sigma from BH mass
	sigma = 200 * u.km / u.s * 10**((log10((MBH / (1e9 * u.Msun)).to(1)) + 0.510) / 4.377)
	r_infl = compute_sphere_of_influence(MBH, sigma).to(u.pc)

	R = numpy.logspace(log10(r_grav/R_in), 3, 1000) * R_in
	R = numpy.logspace(log10(r_grav/R_in), max(3, log10(r_infl/R_in)), 1000) * R_in

	title = "$M_\mathrm{BH}=%s$ $\lambda=%.3f$ $L_\mathrm{AGN}=%.1f$ $\dot{M}=%.1f M_\odot/yr$" % (log_bhm(MBH), eddrate, log_lum(L_AGN), M_dot.to(u.Msun / u.yr).value)
	#plt.title(title)
	
	colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
	textsize = 10
	
	xlo, xhi = 8e-8 * u.pc, 50*100 * u.pc
	ylo, yhi = xlo / 100,  200*100 * u.pc

	# Sphere of influence:
	theta = numpy.linspace(0, pi/2, 400)
	y, x = pol2cart(r_infl, theta)
	if show_SOI:
		plt.plot(x, y, ls='--', lw=0.5, color=colors[8], label='Sphere of influence')
		#plt.text(x.max().value*1.1, r_infl.value / 1000, 'Sphere of influence', 
		#	va='bottom', ha='left', rotation=90)
		plt.text(x.max().value * 1.2, ylo.value * 2, 'Sphere of influence', 
			va='bottom', ha='left', rotation=90)
		#plt.fill_between(x.value, y.value, y.value*0 + yhi.value, 
		#	color=colors[8], alpha=0.1)
		#plt.fill_between([x.max().value, xhi.value], [ylo.value]*2, [yhi.value]*2, 
		#	color=colors[8], alpha=0.1)
		#plt.fill_between(x.value, y.value, y.value*0 + ylo.value, 
		#	color=colors[8], alpha=0.06)

	# Accretion disk:
	R_disk = R
	z_disk = compute_alphadisk_height(MBH, M_dot, R_disk, alpha=1).to(u.pc)
	T_disk = compute_alphadisk_temperature(MBH, M_dot, R_disk, alpha=1).to(u.K)
	if show_disk:
		mask = R < r_infl
		if colored_disk:
			for color, R_part, z_disk_part in find_color_chunks(color_data_T, T_disk[mask], color_data_rgb, R_disk[mask], z_disk[mask]):
				plt.fill_between(R_part, z_disk_part, z_disk_part * 0 + ylo, color=color)
		else:
			plt.fill_between(R_disk[mask], z_disk[mask], z_disk[mask] * 0 + ylo, color='k', label="Accretion disk (SS)")
		
		#	'Accretion disk\n$\log \dot{M}=%.1f$' % rround(log10(M_dot.value)),
		plt.text(7 * r_grav.value, ylo.value * 2, 
			'Accretion disk\n$\log L_\mathrm{bol}=%.1f$' % log_lum(L_AGN),
			va='bottom', ha='left', color='k', size=textsize, bbox=dict(color='white'))
		#idx = numpy.where(R>20*r_grav)[0][0]
		#plt.text(R_disk[idx].value, z_disk[idx].value, 'Accretion disk', 
		#	va='top', ha='left', color='k', size=textsize)
		
		if show_flows:
			outflow = compute_outflow_rate(L_AGN, Mstar = 1e11 * u.Msun, SFR = 0*u.Msun/u.yr)
			inflow = M_dot # at accretion disk at least, or when considering steady-state
			# y = z_disk[mask][-1].value/10
			plt.text(r_infl.value*2, 1e-3, '$\\uparrow$ Outflow\n$%s M_\odot/\mathrm{yr} \cdot M_{\star,11}^{-0.4}$\n$\leftarrow$ BH Inflow\n$%s M_\odot/\mathrm{yr}$' % (rround(outflow.to(u.Msun/u.yr).value), rround(inflow.to(u.Msun/u.yr).value)), 
				va='top', ha='left', color='k', size=textsize)
		
	# Jet:
	R_fullrange = numpy.logspace(log10(r_grav.value), log10(R.value.max()*5), 400) * u.pc
	R_fullrange = numpy.logspace(log10(r_grav.value), log10(max(yhi, 1e8*r_grav).value), 400) * u.pc
	R_j = compute_jet_edge(MBH, R_fullrange)
	if show_jet:
		jetcolor = colors[4]
		plt.plot(R_j, R_fullrange, '--', color=jetcolor, label='Jet')
		plt.fill_betweenx(R_fullrange, R_j, color=jetcolor, label='Jet', alpha=0.05)
		plt.text(R_j.value[-1] / 5, R_fullrange.value[-1] / 2, 'Jet', color=jetcolor, 
			va='top', ha='right', size=textsize)

	# BH:
	theta = numpy.linspace(0, pi/2, 4000)
	y, x = pol2cart(r_grav, theta[::-1])
	if show_BH:
		plt.fill_between(x, 1e-10 + 0*y.value, y, color='k', label='Black hole')
		#plt.plot(x, y / 10, '-', color='k', label='Black hole 1')
		plt.text(r_grav.value * 0.8, r_grav.value / 3, 
			'Black Hole\n\n$\log M=%.1f$' % (log_bhm(MBH)) if MBH > 10**7.5 * u.Msun else 'BH\n\n$\log M=%.1f$' % (log_bhm(MBH)), 
			va='top', ha='right', color='white', fontweight='bold', size=textsize)

	# Corona:
	y, x = pol2cart(6*r_grav, theta)
	if show_corona:
		plt.plot(x, y, ls=':', color=colors[1], label='X-ray Corona')
		plt.text(xlo.value*1.2, 6*r_grav.value, 'Corona',
			va='bottom', ha='left', color=colors[1])

	# BLR:
	z1, z2, zmax            = compute_blr_shape(MBH, M_dot, L_AGN, R, Z, variant='static')
	z1, z2, zmax_dyn        = compute_blr_shape(MBH, M_dot, L_AGN, R, Z, variant='dynamic', dyn_factor=2)
	CF = get_blr_covering_factor(z1, z2, R)
	Rpeak, Hpeak = get_peak(z2, z1, R)
	z1, z2, zmax_dyn_nodust = compute_blr_shape(MBH, M_dot, L_AGN, R, Z, variant='dustfree', dyn_factor=2)

	idx, = numpy.where(numpy.logical_or(zmax_dyn_nodust > z_disk, zmax_dyn > z_disk))
	if idx.any():
		lo, hi = idx.min() - 1, idx.max() + 1
		zmax_dyn_disk = numpy.where(zmax_dyn > z_disk, zmax_dyn, z_disk)
		zmax_dyn_nodust_disk = numpy.where(zmax_dyn_nodust > z_disk, zmax_dyn_nodust, z_disk)
	else:
		lo, hi = 0, -1
		zmax_dyn_disk = zmax_dyn
		zmax_dyn_nodust_disk = zmax_dyn_nodust
	
	if show_BLR:
		color = colors[0]
		l, = plt.plot(R[lo:hi], zmax_dyn_nodust_disk[lo:hi], '--',
			label="Broad Line Region (BLCH, CF=%.0f%%)" % (CF*100),
			color=color,
		)
		
		plt.plot(R[lo:hi], zmax_dyn_disk[lo:hi], '-', color=color, label='Dusty BLR')
		plt.fill_between(R[lo:hi], z_disk[lo:hi], zmax_dyn_disk[lo:hi], color=color)
		#plt.plot(Rpeak, Hpeak, 'o', color=color)
		plt.text(Rpeak.value, Hpeak.value, 'BLCH BLR\nCF=%.2f' % (CF),
			va='bottom', ha='center', color=color)
		#plt.fill_between(R.flatten(), 0, zmax_dyn, color=color, hatch='//')
		#plt.vlines(R_in.to(u.pc).value, 0, Hpeak.to(u.pc).value, linestyles=[':'], colors=[color])

	# Radiative fountain
	r_d = compute_dust_sublimation_radius(L_AGN)
	r_0 = compute_heating_radius(L_AGN, rho_g = 300 * u.Msun / u.pc**3)
	r_max = compute_rmax(MBH, L_AGN, theta, r_0, r_d, 
		dust_to_gas_ratio = dust_to_gas_ratio,
		kappa = kappa).to(u.pc)
	theta_crit = compute_critical_angle(MBH, L_AGN, r_0, r_d, 
		dust_to_gas_ratio, kappa = kappa)
	CF = cos(theta_crit)
	
	color = colors[3]
	r_max[r_max > 1000 * u.pc] = numpy.nan
	z_min = numpy.interp(r_d.value, R.value, z_disk.value)
	theta_min = arctan2(z_min, r_d.value)
	y, x = pol2cart(r_max, theta)
	
	if show_TOR:
		#plt.plot(x, y, ls='-.', color=color, label="Radiative Fountain TOR")
		
		## structure:
		rng = numpy.random.RandomState(1)
		Nrad = 100
		# 100 pixels in radial direction
		rho = 10**rng.normal(size=(Nrad, Nrad))
		rho[rho > 1000] = 1000
		from scipy.signal import sepfir2d, convolve2d
		# we need 5 degree smoothing in theta according to Wada+ sims
		# but this could be partly due to resolution issues, 
		# so I take twice that here
		correlation_degrees = 5 / 2
		# same scale in radial direction as in vertical direction
		sigma_rad_pixels = len(rho) * sin(correlation_degrees * pi / 180)
		H_r = numpy.exp(-0.5 * numpy.linspace(-5, 5, int(sigma_rad_pixels)*10)**2)
		H_r /= H_r.sum()
		H_c = H_r
		kernel = H_r.reshape((-1, 1)) * H_c.reshape((1, -1))
		kernel /= kernel.sum()
		
		rad = numpy.linspace(0, r_infl.to(u.pc).value, Nrad)
		X, Y = numpy.meshgrid(rad, rad)
		R, THETA = cart2pol(X, Y)
		low_density = 0
		# use high values close to disk
		rho[THETA <= theta_min] = 10
		# now erase disallowed regions:
		# empty jet
		X_jet = compute_jet_edge(MBH, Y * u.pc).to(u.pc).value
		rho[X < X_jet] = low_density
		RMAX = numpy.interp(pi/2 - THETA, xp=theta, fp=r_max.value)
		RMAX[~numpy.isfinite(RMAX)] = numpy.inf
		# only fill below r_max
		rho[R <= RMAX] = low_density
		# only fill within SOI
		rho[R > r_infl.to(u.pc).value] = low_density
		
		# do convolution
		convolved = sepfir2d(rho, H_r, H_c)
		#convolved = convolve2d(rho, kernel, mode='same', fillvalue=low_density)
		convolved[R <= RMAX] = low_density
		convolved[R > r_infl.to(u.pc).value] = low_density
		convolved[X < X_jet] = low_density
		#convolved[THETA <= theta_min] = 3
		#plt.contourf(rad, rad, convolved/convolved[convolved>low_density].std(), 
		#	levels=numpy.linspace(-3, 3, 10), cmap='Reds', zorder=-10)
		#convolved[convolved > 3] = 3
		#convolved[convolved < -3] = numpy.nan
		C = plt.contourf(rad, rad, convolved, 
			levels=10, cmap='Reds', zorder=-10)
		C.collections[0].set_facecolor('white')
		## end structure


	mask = theta > 89.7/180*pi
	if show_TOR and mask.any() and numpy.isfinite(x[mask][0].value):
		plt.text(x[mask][0].value, y[mask][0].value, 'RF TOR \nCF=%.2f ' % CF, 
			va='bottom', ha='right', color=color)
	
	# NLR
	R_NLR_hi = get_nlr_size().to(u.pc)
	# these are chosen arbitrarily: the inner edge of the NLR and the maximum angle
	# in practice they are observationally and host galaxy limited, respectively
	R_NLR_lo = r_infl
	R_NLR = numpy.array([R_NLR_lo.value, R_NLR_hi.value]) * u.pc
	thetai = numpy.linspace(pi/400, pi/4, 10)
	for i, (thetalo, thetahi) in enumerate(zip(thetai[:-1], thetai[1:])):
		if not show_NLR: break
		ylo1, ylo2 = R_NLR.value
		xlo1, xlo2 = compute_jet_edge(MBH, R_NLR).value
		(yhi1, yhi2), (xhi1, xhi2) = pol2cart(R_NLR.value, thetahi)
		
		#(ylo1, ylo2), (xlo1, xlo2) = pol2cart(R_NLR_lo.value, numpy.array([thetalo, thetahi]))
		#(yhi1, yhi2), (xhi1, xhi2) = pol2cart(R_NLR_hi.value, numpy.array([thetalo, thetahi]))
		label = 'NLR' if i == 0 else None
		alpha = (1. - (i*1./len(thetai))**0.8)*0.5
		
		plt.fill([xlo1, xhi1, xhi2, xlo2], [ylo1, yhi1, yhi2, ylo2], 
			color=colors[2], 
			alpha=alpha, lw=0,
			label=label)
		plt.text(xlo2, ylo2*0.9, 'NLR',
			color='white', va='top', ha='left', size=textsize)
	
	
	# sight-lines
	theta = numpy.array([1, 5, 15, 30, 60, 85])
	theta[theta == 0] = 5
	theta[theta == 90] = 85
	for thetai in theta:
		if not show_viewing: break
		Rline = numpy.array([5 * r_grav.to(u.pc).value, 4])
		#Rline = numpy.linspace(5 * r_grav.to(u.pc).value, 10, 1000)
		y, x = pol2cart(Rline, thetai / 180 * pi)
		#x = R_fullrange.value
		#y = x * sin(thetai / 180 * pi)
		#mask = y > 1
		#y, x = y[mask], x[mask]
		plt.plot(x, y, ':', color='k', alpha=0.1)
		plt.text(x[-1], y[-1], '$%d^\circ$' % (thetai))
	
	plt.xlabel("R [pc]")
	plt.ylabel("z [pc]")
	plt.xticks()
	#plt.legend(loc="lower right", prop=dict(size=12))
	#plt.ylim(r_grav.value / 100, 200*100)
	#plt.xlim(r_grav.value / 2, 50*100)
	plt.ylim(8e-8 / 100, 200*100)
	plt.xlim(8e-8, 50*100)
	plt.xscale('log')
	plt.yscale('log')
Пример #41
0
 def separable_convolution2d(self, im, row, col, **kwargs):
     return sepfir2d(im, row, col)
Пример #42
0
def compute_similarity_from_jhist(jh, fwhm=None, cost_fun='nmi'):
    """
    Computes an information-theoretic similarity from a joint histogram.

    Parameters
    ----------
    jh: 2D array
        joint histogram of the two random variables being compared

    fwhm: float or pair of float
        kernel width for smoothing the joint histogram

    cost_fun: string, optional (default 'nmi')
        smilarity model to use; possible values are:
        'mi': Mutual Information
        'nmi': Normalized Mutual Information
        'ecc': Entropic Cross-Correlation

    Returns
    -------
    o: float
        the computed similariy measure
    """
    # sanitize input
    if fwhm is None:
        fwhm = [7., 7.]
    if len(np.shape(jh)) != 2:
        raise ValueError("jh must be 2D array, got %s" % jh)

    if len(np.shape(fwhm)) == 0:
        fwhm = [fwhm] * 2
    fwhm = fwhm[:2]

    # create separable filter for smoothing the joint-histogram
    lim = np.ceil(fwhm * 2)
    krn1 = centered_smoothing_kernel(fwhm[0],
                                     np.linspace(-1 * lim[0], lim[0],
                                                 num=2 * lim[0]))
    krn1 = krn1 / np.sum(krn1)
    krn2 = centered_smoothing_kernel(fwhm[1],
                                     np.linspace(-1 * lim[1], lim[1],
                                                 num=2 * lim[1]))
    krn2 = krn2 / np.sum(krn2)

    # smooth the histogram with kern1 x kern2
    jh = sepfir2d(jh, krn1, krn2)

    # compute marginal histograms
    jh = jh + EPS
    sh = np.sum(jh)
    jh = jh / sh
    s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0]))
    s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1))

    # compute cost function proper
    if cost_fun == 'mi':
        # Mutual Information:
        jh = jh * np.log2(jh / np.dot(s2, s1))
        mi = np.sum(jh)
        o = -mi
    elif cost_fun == 'ecc':
        # Entropy Correlation Coefficient of:
        # Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).
        # "Multimodality image registration by maximisation of mutual
        # information". IEEE Transactions on Medical Imaging 16(2):187-198
        jh = jh * np.log2(jh / np.dot(s2, s1))
        mi = np.sum(jh.ravel(order='F'))
        ecc = -2 * mi / (np.sum(s1 * np.log2(s1)) + np.sum(s2 * np.log2(s2)))
        o = -ecc
    elif cost_fun == 'nmi':
        # Normalised Mutual Information of:
        # Studholme,  jhill & jhawkes (1998).
        # "A normalized entropy measure of 3-D medical image alignment".
        # in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
        nmi = (np.sum(s1 * np.log2(s1)) + np.sum(s2 * np.log2(s2))) / np.sum(
            np.sum(jh * np.log2(jh)))
        o = -nmi
    else:
        raise NotImplementedError(
            "Unsupported cost_fun (cost function): %s" % cost_fun)

    return o
Пример #43
0
def compute_similarity_from_jhist(jh, fwhm=None, cost_fun='nmi'):
    """
    Computes an information-theoretic similarity from a joint histogram.

    Parameters
    ----------
    jh: 2D array
        joint histogram of the two random variables being compared

    fwhm: float or pair of float
        kernel width for smoothing the joint histogram

    cost_fun: string, optional (default 'nmi')
        smilarity model to use; possible values are:
        'mi': Mutual Information
        'nmi': Normalized Mutual Information
        'ecc': Entropic Cross-Correlation

    Returns
    -------
    o: float
        the computed similariy measure
    """
    # sanitize input
    if fwhm is None:
        fwhm = [7., 7.]
    if len(np.shape(jh)) != 2:
        raise ValueError("jh must be 2D array, got %s" % jh)

    if len(np.shape(fwhm)) == 0:
        fwhm = [fwhm] * 2
    fwhm = fwhm[:2]

    # create separable filter for smoothing the joint-histogram
    lim = np.ceil(fwhm * 2).astype(np.int)
    krn1 = centered_smoothing_kernel(
        fwhm[0], np.linspace(-1 * lim[0], lim[0], num=2 * lim[0]))
    krn1 = krn1 / np.sum(krn1)
    krn2 = centered_smoothing_kernel(
        fwhm[1], np.linspace(-1 * lim[1], lim[1], num=2 * lim[1]))
    krn2 = krn2 / np.sum(krn2)

    # smooth the histogram with kern1 x kern2
    jh = sepfir2d(jh, krn1, krn2)

    # compute marginal histograms
    jh = jh + EPS
    sh = np.sum(jh)
    jh = jh / sh
    s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0]))
    s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1))

    # compute cost function proper
    if cost_fun == 'mi':
        # Mutual Information:
        jh = jh * np.log2(jh / np.dot(s2, s1))
        mi = np.sum(jh)
        o = -mi
    elif cost_fun == 'ecc':
        # Entropy Correlation Coefficient of:
        # Maes, Collignon, Vandermeulen, Marchal & Suetens (1997).
        # "Multimodality image registration by maximisation of mutual
        # information". IEEE Transactions on Medical Imaging 16(2):187-198
        jh = jh * np.log2(jh / np.dot(s2, s1))
        mi = np.sum(jh.ravel(order='F'))
        ecc = -2 * mi / (np.sum(s1 * np.log2(s1)) + np.sum(s2 * np.log2(s2)))
        o = -ecc
    elif cost_fun == 'nmi':
        # Normalised Mutual Information of:
        # Studholme,  jhill & jhawkes (1998).
        # "A normalized entropy measure of 3-D medical image alignment".
        # in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.
        nmi = (np.sum(s1 * np.log2(s1)) + np.sum(s2 * np.log2(s2))) / np.sum(
            np.sum(jh * np.log2(jh)))
        o = -nmi
    else:
        raise NotImplementedError("Unsupported cost_fun (cost function): %s" %
                                  cost_fun)

    return o
Пример #44
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
def 高斯模糊():
    image = misc.ascent()  # 二维图像数组,ascent 图像
    w = signal.gaussian(50, 10.0)
    global image_new
    image_new = signal.sepfir2d(image, w, w)
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)
plt.gray()
Пример #47
0
from numpy import *
from scipy import signal, misc
import matplotlib.pyplot as plt

image = misc.lena().astype(float32)
derfilt = array([1.0,-2,1.0],float32)
ck = signal.cspline2d(image,8.0)
deriv = signal.sepfir2d(ck, derfilt, [1]) + \
        signal.sepfir2d(ck, [1], derfilt)

# Alternatively we could have done::

# laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],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()
Пример #48
0
pos_error_xx = np.sum(pos_error_x * pos_error_x, axis=1) / cfg.N
pos_error_yy = np.sum(pos_error_y * pos_error_y, axis=1) / cfg.N
pos_error_xy = np.sum(pos_error_x * pos_error_y, axis=1) / cfg.N

"""
Ploting the heatmap, blur heatmaps - boxcar window filter
"""
w = signal.get_window("boxcar", 7)
w /= np.sum(w)

# xx
heatmap_data = pos_error_xx
Z = heatmap_data.reshape(
    [(boundaries[1][1] - boundaries[1][0] - 1) / cfg.res + 1, (boundaries[0][1] - boundaries[0][0] - 1) / cfg.res + 1]
)
Z = signal.sepfir2d(Z, w, w)

pos_error_xx = Z.reshape((grid.shape[0]))

# yy
heatmap_data = pos_error_yy
Z = heatmap_data.reshape(
    [(boundaries[1][1] - boundaries[1][0] - 1) / cfg.res + 1, (boundaries[0][1] - boundaries[0][0] - 1) / cfg.res + 1]
)
Z = signal.sepfir2d(Z, w, w)

pos_error_yy = Z.reshape((grid.shape[0]))

# plot xy
heatmap_data = pos_error_xy
Z = heatmap_data.reshape(