def _hough_transform(img, angles): rows, cols = img.shape # determine the number of bins d = sp.ceil(sp.hypot(*img.shape)) nr_bins = 2 * d bins = sp.linspace(-d, d, nr_bins) # create the accumulator out = sp.zeros((nr_bins, len(angles)), dtype=sp.float64) # compute the sines/cosines cos_theta = sp.cos(angles) sin_theta = sp.sin(angles) # constructe the x and y values y = [] x = [] for i in xrange(rows): y += [i] * cols x += range(cols) y = sp.array(y) x = sp.array(x) # flatten image flattened_img = img.flatten() for i, (c, s) in enumerate(zip(cos_theta, sin_theta)): distances = x * c + y * s bin_indices = (sp.round_(distances) - bins[0]).astype(sp.uint8) bin_sums = sp.bincount(bin_indices, flattened_img) out[:len(bin_sums), i] = bin_sums return out
def polarZ(z): if(z == 0): return (0,0) else : a = z.real b = z.imag return( sp.hypot(a,b), sp.arctan(b/a))
def gauss_smooth(arr, w): """ Smooths an input array by w pixels """ alpha = w/2.3548 pix = arr.shape[0] ker = sp.exp(-(alpha**-2.)*sp.hypot(*sp.ogrid[-pix/2:pix/2,-pix/2:pix/2])**2.) return sp.real(spf.fftshift(spf.ifft2( spf.fft2(arr)*spf.fft2(ker) )))
def plot_cc(tri, edgecolor=None): import matplotlib as mpl from matplotlib import pylab as pl if edgecolor is None: edgecolor = (0,0,1,0.2) dxy = (sp.array([(tri.x[i], tri.y[i]) for i,j,k in tri.triangle_nodes]) - tri.circumcenters) r = sp.hypot(dxy[:,0], dxy[:,1]) ax = pl.gca() for i in xrange(len(r)): p = mpl.patches.Circle(tri.circumcenters[i], r[i], resolution=100, edgecolor=edgecolor, facecolor=(1,1,1,0), linewidth=0.2) ax.add_patch(p) pl.draw_if_interactive()
def init_probe(self, *args, **kwargs): if CXP.io.initial_probe_guess is not '': probe = CXData() probe.load(CXP.io.initial_probe_guess) self.probe.modes = [CXData(data=[probe.data[0]/(i+1)]) for i in range(CXP.reconstruction.probe_modes)] self.probe.normalise() else: dx_s = CXP.dx_s p, p2 = CXP.preprocessing.desired_array_shape, CXP.preprocessing.desired_array_shape/2 probe = sp.zeros((p, p), complex) if CXP.experiment.optic.lower() == 'kb': if len(CXP.experiment.beam_size)==1: bsx=bsy=np.round(CXP.experiment.beam_size[0]/dx_s) elif len(CXP.experiment.beam_size)==2: bsx, bsy = np.round(CXP.experiment.beam_size[0]/dx_s), np.round(CXP.experiment.beam_size[1]/dx_s) probe = np.sinc((np.arange(p)-p2)/bsx)[:,np.newaxis]*np.sinc((np.arange(p)-p2)/bsy)[np.newaxis,:] elif CXP.experiment.optic.lower() == 'zp': probe = np.sinc(sp.hypot(*sp.ogrid[-p2:p2, -p2:p2])/np.round(3.*CXP.experiment.beam_size[0]/(2*CXP.dx_s))) ph_func = gauss_smooth(np.random.random(probe.shape), 10) fwhm = p/2.0 radker = sp.hypot(*sp.ogrid[-p/2:p/2,-p/2:p/2]) gaussian = exp(-1.0*(fwhm/2.35)**-2. * radker**2.0 ) gaussian /= gaussian.max() probe = abs(gaussian*probe)* exp(complex(0.,np.pi)*ph_func/ph_func.max()) self.probe.modes = [CXData(data=[probe/(i+1)]) for i in range(CXP.reconstruction.probe_modes)] self.probe.normalise()
def edge_detection(f): import Image #sigma = 1.0 img = Image.open(f) #grayscale imgdata = np.array(img, dtype = float) G = imgdata #G = ndi.filters.gaussian_filter(imgdata, sigma) gradx = np.array(G, dtype = float) grady = np.array(G, dtype = float) mask_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) mask_y = np.array([[1,2,1],[0,0,0],[-1,-2,-1]]) width = img.size[1] height = img.size[0] for i in range(1, width-1): for j in range(1, height-1): px = np.sum(mask_x*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) py = np.sum(mask_y*G[(i-1):(i+1)+1,(j-1):(j+1)+1]) gradx[i][j] = px grady[i][j] = py mag = scipy.hypot(gradx,grady) treshold = np.max(mag)*0.9 for i in range(width): for j in range(height): if mag[i][j]>treshold: mag[i][j]=1 else: mag[i][j] = 0 return mag
def makeSobel(self,patchImg,sigma = 2.2): img = patchImg; imgdata = numpy.array(img, dtype = float) G = ndi.filters.gaussian_filter(imgdata, sigma) #gaussian low pass filter sobelout = Image.new('L', img.size) #empty image gradx = numpy.array(sobelout, dtype = float) grady = numpy.array(sobelout, dtype = float) sobel_x = [[-1,0,1], [-2,0,2], [-1,0,1]] sobel_y = [[-1,-2,-1], [0,0,0], [1,2,1]] self.width = img.size[1] self.height = img.size[0] #calculate |G| and dir(G) for x in range(1, self.width-1): for y in range(1, self.height-1): px = (sobel_x[0][0] * G[x-1][y-1]) + (sobel_x[0][1] * G[x][y-1]) + \ (sobel_x[0][2] * G[x+1][y-1]) + (sobel_x[1][0] * G[x-1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x+1][y]) + \ (sobel_x[2][0] * G[x-1][y+1]) + (sobel_x[2][1] * G[x][y+1]) + \ (sobel_x[2][2] * G[x+1][y+1]) py = (sobel_y[0][0] * G[x-1][y-1]) + (sobel_y[0][1] * G[x][y-1]) + \ (sobel_y[0][2] * G[x+1][y-1]) + (sobel_y[1][0] * G[x-1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x+1][y]) + \ (sobel_y[2][0] * G[x-1][y+1]) + (sobel_y[2][1] * G[x][y+1]) + \ (sobel_y[2][2] * G[x+1][y+1]) gradx[x][y] = px grady[x][y] = py self.sobeloutmag = scipy.hypot(gradx, grady) self.sobeloutdir = scipy.arctan2(grady, gradx) return [self.sobeloutmag,self.sobeloutdir]
for y in range(1, height - 1): px = (sobel_x[0][0] * G[x-1][y-1]) + (sobel_x[0][1] * G[x][y-1]) + \ (sobel_x[0][2] * G[x+1][y-1]) + (sobel_x[1][0] * G[x-1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x+1][y]) + \ (sobel_x[2][0] * G[x-1][y+1]) + (sobel_x[2][1] * G[x][y+1]) + \ (sobel_x[2][2] * G[x+1][y+1]) py = (sobel_y[0][0] * G[x-1][y-1]) + (sobel_y[0][1] * G[x][y-1]) + \ (sobel_y[0][2] * G[x+1][y-1]) + (sobel_y[1][0] * G[x-1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x+1][y]) + \ (sobel_y[2][0] * G[x-1][y+1]) + (sobel_y[2][1] * G[x][y+1]) + \ (sobel_y[2][2] * G[x+1][y+1]) gradx[x][y] = px grady[x][y] = py sobeloutmag = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) scipy.misc.imsave('cannynewmag.jpg', sobeloutmag) scipy.misc.imsave('cannynewdir.jpg', sobeloutdir) for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y] = 0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y] = 45 elif (sobeloutdir[x][y]>=67.5 and sobeloutdir[x][y]<112.5)or \
def canny(input_image): # convenience functions def nonmaxs(grad, i, j, x1, y1, x2, y2): try: if (grad[i, j] > grad[i + x1, j + y1]) and (grad[i, j] > grad[i + x2, j + y2]): return 1 else: return 0 except IndexError: return -1 def edge_end(imag, threshold): X, Y = np.where(imag > threshold) try: y = Y.min() except: return -1 X = X.tolist() Y = Y.tolist() index = Y.index(y) x = X[index] return [x, y] def edge_follower(imag, p0, p1, p2, threshold): kit = [-1, 0, 1] X, Y = imag.shape for i in kit: for j in kit: if (i + j) == 0: continue x = p0[0] + i y = p0[1] + j if (x < 0) or (y < 0) or (x >= X) or (y >= Y): continue if ([x, y] == p1) or ([x, y] == p2): continue if imag[x, y] > threshold: # and (imag[i,j] < 256): return [x, y] return -1 thresholdhold_high = 40 thresholdhold_low = 8 # precalculated gauss kernel (sigma=0.5, window size 5) gausskernel = np.array( [ [6.96247819e-08, 2.80886418e-05, 2.07548550e-04, 2.80886418e-05, 6.96247819e-08], [2.80886418e-05, 1.13317669e-02, 8.37310610e-02, 1.13317669e-02, 2.80886418e-05], [2.07548550e-04, 8.37310610e-02, 6.18693507e-01, 8.37310610e-02, 2.07548550e-04], [2.80886418e-05, 1.13317669e-02, 8.37310610e-02, 1.13317669e-02, 2.80886418e-05], [6.96247819e-08, 2.80886418e-05, 2.07548550e-04, 2.80886418e-05, 6.96247819e-08], ] ) fx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) fy = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) imout = convolve2d(input_image, gausskernel)[1:-1, 1:-1] gradx = convolve2d(imout, fx)[1:-1, 1:-1] grady = convolve2d(imout, fy)[1:-1, 1:-1] grad = scipy.hypot(gradx, grady) theta = scipy.arctan2(grady, gradx) theta = 180 + (180 / math.pi) * theta x, y = np.where(grad < 10) theta[x, y] = 0 grad[x, y] = 0 x0, y0 = np.where(((theta < 22.5) + (theta > 157.5) * (theta < 202.5) + (theta > 337.5)) == True) x45, y45 = np.where(((theta > 22.5) * (theta < 67.5) + (theta > 202.5) * (theta < 247.5)) == True) x90, y90 = np.where(((theta > 67.5) * (theta < 112.5) + (theta > 247.5) * (theta < 292.5)) == True) x135, y135 = np.where(((theta > 112.5) * (theta < 157.5) + (theta > 292.5) * (theta < 337.5)) == True) theta[x0, y0] = 0 theta[x45, y45] = 45 theta[x90, y90] = 90 theta[x135, y135] = 135 x, y = theta.shape temp = Image.new("RGB", (y, x), (255, 255, 255)) for i in range(x): for j in range(y): if theta[i, j] == 0: temp.putpixel((j, i), (0, 0, 255)) elif theta[i, j] == 45: temp.putpixel((j, i), (255, 0, 0)) elif theta[i, j] == 90: temp.putpixel((j, i), (255, 255, 0)) elif theta[i, j] == 45: temp.putpixel((j, i), (0, 255, 0)) grad = grad.copy() x, y = grad.shape for i in range(x): for j in range(y): if theta[i, j] == 0: if not nonmaxs(grad, i, j, 1, 0, -1, 0): grad[i, j] = 0 elif theta[i, j] == 45: if not nonmaxs(grad, i, j, 1, -1, -1, 1): grad[i, j] = 0 elif theta[i, j] == 90: if not nonmaxs(grad, i, j, 0, 1, 0, -1): grad[i, j] = 0 elif theta[i, j] == 135: if not nonmaxs(grad, i, j, 1, 1, -1, -1): grad[i, j] = 0 init_point = edge_end(grad, thresholdhold_high) while init_point != -1: grad[init_point[0], init_point[1]] = -1 p2 = init_point p1 = init_point p0 = init_point p0 = edge_follower(grad, p0, p1, p2, thresholdhold_low) while p0 != -1: p2 = p1 p1 = p0 grad[p0[0], p0[1]] = -1 p0 = edge_follower(grad, p0, p1, p2, thresholdhold_low) init_point = edge_end(grad, thresholdhold_high) x, y = np.where(grad == -1) grad[:, :] = 0 grad[x, y] = 255 return grad
def edgeDetection(im): sigma = 1.4 # imdata = numpy.array(im) imdata = numpy.array(im, dtype=float) # image: 494 * 343 ---> but Image(x, y) will be represent in array like Arr[y][x], so Arr will become 343 * 494, so Arr[x][y] will refer to the image(x,y) # G = imdata G = ndi.filters.gaussian_filter(imdata, sigma) # G = numpy.transpose(imdata) # numpy.transpose(G) gradOut = Image.new('L', im.size) gradx = numpy.array(gradOut, dtype=float) grady = numpy.array(gradOut, dtype=float) # graddxdy = numpy.array(gradOut, dtype = float) kernel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] kernel_y = [[-1, -2, -1], [0, 0, 0], [-1, -2, -1]] # numpy.array will change image from 424 * 343 to 343*424 array width = im.size[1] height = im.size[0] # print width, height for x in range(1, width - 1): for y in range(1, height - 1): px = kernel_x[0][0] * G[x-1][y-1] + kernel_x[0][1] * G[x][y-1] + \ kernel_x[0][2] * G[x+1][y-1] + kernel_x[1][0] * G[x-1][y] + \ kernel_x[1][1] * G[x][y] + kernel_x[1][2] * G[x+1][y] + \ kernel_x[2][0] * G[x-1][y+1] + kernel_x[2][1] * G[x][y+1] + \ kernel_x[2][2] * G[x+1][y+1] py = kernel_y[0][0] * G[x-1][y-1] + kernel_y[0][1] * G[x][y-1] + \ kernel_y[0][2] * G[x+1][y-1] + kernel_y[1][0] * G[x-1][y] + \ kernel_y[1][1] * G[x][y] + kernel_y[1][2] * G[x+1][y] + \ kernel_y[2][0] * G[x-1][y+1] + kernel_y[2][1] * G[x][y+1] + \ kernel_y[2][2] * G[x+1][y+1] gradx[x][y] = px grady[x][y] = py # graddxdy [x][y] = py * 1.0 / px sobeloutmag = scipy.hypot(gradx, grady) sobeloutmag_n = sobeloutmag / numpy.max(sobeloutmag) mag_sup = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y] = 0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y] = 45 elif (sobeloutdir[x][y]>=67.5 and sobeloutdir[x][y]<112.5)or \ (sobeloutdir[x][y]>=247.5 and sobeloutdir[x][y]<292.5): sobeloutdir[x][y] = 90 else: sobeloutdir[x][y] = 135 for x in range(1, width - 1): for y in range(1, height - 1): if sobeloutdir[x][y] == 0: if (sobeloutmag[x][y]<=sobeloutmag[x][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x][y-1]): mag_sup[x][y] = 0 elif sobeloutdir[x][y] == 45: if (sobeloutmag[x][y]<=sobeloutmag[x-1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x+1][y-1]): mag_sup[x][y] = 0 elif sobeloutdir[x][y] == 90: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y]): mag_sup[x][y] = 0 else: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y-1]): mag_sup[x][y] = 0 return mag_sup / numpy.max(mag_sup), gradx, grady
def extract_edges(img): img = img.convert('L') # grayscale imgdata = numpy.array(img, dtype=float) G = ndi.filters.gaussian_filter(imgdata, sigma) # gaussian low pass filter sobelout = Image.new('L', img.size) # empty image gradx = numpy.array(sobelout, dtype=float) grady = numpy.array(sobelout, dtype=float) sobel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] sobel_y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] width = img.size[1] height = img.size[0] # calculate |G| and dir(G) for x in range(1, width - 1): for y in range(1, height - 1): px = (sobel_x[0][0] * G[x - 1][y - 1]) + (sobel_x[0][1] * G[x][y - 1]) + \ (sobel_x[0][2] * G[x + 1][y - 1]) + (sobel_x[1][0] * G[x - 1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x + 1][y]) + \ (sobel_x[2][0] * G[x - 1][y + 1]) + (sobel_x[2][1] * G[x][y + 1]) + \ (sobel_x[2][2] * G[x + 1][y + 1]) py = (sobel_y[0][0] * G[x - 1][y - 1]) + (sobel_y[0][1] * G[x][y - 1]) + \ (sobel_y[0][2] * G[x + 1][y - 1]) + (sobel_y[1][0] * G[x - 1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x + 1][y]) + \ (sobel_y[2][0] * G[x - 1][y + 1]) + (sobel_y[2][1] * G[x][y + 1]) + \ (sobel_y[2][2] * G[x + 1][y + 1]) gradx[x][y] = px grady[x][y] = py sobeloutmag = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) for x in range(width): for y in range(height): if (sobeloutdir[x][y] < 22.5 and sobeloutdir[x][y] >= 0) or \ (sobeloutdir[x][y] >= 157.5 and sobeloutdir[x][y] < 202.5) or \ (sobeloutdir[x][y] >= 337.5 and sobeloutdir[x][y] <= 360): sobeloutdir[x][y] = 0 elif (sobeloutdir[x][y] >= 22.5 and sobeloutdir[x][y] < 67.5) or \ (sobeloutdir[x][y] >= 202.5 and sobeloutdir[x][y] < 247.5): sobeloutdir[x][y] = 45 elif (sobeloutdir[x][y] >= 67.5 and sobeloutdir[x][y] < 112.5) or \ (sobeloutdir[x][y] >= 247.5 and sobeloutdir[x][y] < 292.5): sobeloutdir[x][y] = 90 else: sobeloutdir[x][y] = 135 mag_sup = sobeloutmag.copy() for x in range(1, width - 1): for y in range(1, height - 1): if sobeloutdir[x][y] == 0: if (sobeloutmag[x][y] <= sobeloutmag[x][y + 1]) or \ (sobeloutmag[x][y] <= sobeloutmag[x][y - 1]): mag_sup[x][y] = 0 elif sobeloutdir[x][y] == 45: if (sobeloutmag[x][y] <= sobeloutmag[x - 1][y + 1]) or \ (sobeloutmag[x][y] <= sobeloutmag[x + 1][y - 1]): mag_sup[x][y] = 0 elif sobeloutdir[x][y] == 90: if (sobeloutmag[x][y] <= sobeloutmag[x + 1][y]) or \ (sobeloutmag[x][y] <= sobeloutmag[x - 1][y]): mag_sup[x][y] = 0 else: if (sobeloutmag[x][y] <= sobeloutmag[x + 1][y + 1]) or \ (sobeloutmag[x][y] <= sobeloutmag[x - 1][y - 1]): mag_sup[x][y] = 0 m = numpy.max(mag_sup) th = th_float * m tl = tl_float * m gnh = numpy.zeros((width, height)) gnl = numpy.zeros((width, height)) for x in range(width): for y in range(height): if mag_sup[x][y] >= th: gnh[x][y] = mag_sup[x][y] if mag_sup[x][y] >= tl: gnl[x][y] = mag_sup[x][y] gnl = gnl - gnh def traverse(i, j): x = [-1, 0, 1, -1, 1, -1, 0, 1] y = [-1, -1, -1, 0, 0, 1, 1, 1] for k in range(8): if gnh[i + x[k]][j + y[k]] == 0 and gnl[i + x[k]][j + y[k]] != 0: gnh[i + x[k]][j + y[k]] = 1 traverse(i + x[k], j + y[k]) for i in range(1, width - 1): for j in range(1, height - 1): if gnh[i][j]: gnh[i][j] = 1 traverse(i, j) ones = numpy.ones((width, height)) gnh = ones - gnh return gnh
for y in range(1, height-1): px = (sobel_x[0][0] * G[x-1][y-1]) + (sobel_x[0][1] * G[x][y-1]) + \ (sobel_x[0][2] * G[x+1][y-1]) + (sobel_x[1][0] * G[x-1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x+1][y]) + \ (sobel_x[2][0] * G[x-1][y+1]) + (sobel_x[2][1] * G[x][y+1]) + \ (sobel_x[2][2] * G[x+1][y+1]) py = (sobel_y[0][0] * G[x-1][y-1]) + (sobel_y[0][1] * G[x][y-1]) + \ (sobel_y[0][2] * G[x+1][y-1]) + (sobel_y[1][0] * G[x-1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x+1][y]) + \ (sobel_y[2][0] * G[x-1][y+1]) + (sobel_y[2][1] * G[x][y+1]) + \ (sobel_y[2][2] * G[x+1][y+1]) gradx[x][y] = px grady[x][y] = py sobeloutmag = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) scipy.misc.imsave('cannynewmag.jpg', sobeloutmag)#thick scipy.misc.imsave('cannynewdir.jpg', sobeloutdir)#looks object print 'cannynewmag.jpg' for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y]=0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y]=45
def canny(colorModelTag, currentImageChannelIndex, pixels, imgSize, G, amplifier=1.0, threshold=(10, 250)): sigma = 2.2 gradxR = [] gradyR = [] gradxG = [] gradyG = [] gradxB = [] gradyB = [] sobel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] sobel_y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] width = imgSize[1] height = imgSize[0] #calculate |G| and dir(G) for x in range(1, width - 1): gradxLineR = [] gradyLineR = [] gradxLineG = [] gradyLineG = [] gradxLineB = [] gradyLineB = [] for y in range(1, height - 1): pxR = (sobel_x[0][0] * G[x-1,y-1][0]) + (sobel_x[0][1] * G[x,y-1][0]) + \ (sobel_x[0][2] * G[x+1,y-1][0]) + (sobel_x[1][0] * G[x-1,y][0]) + \ (sobel_x[1][1] * G[x,y][0]) + (sobel_x[1][2] * G[x+1,y][0]) + \ (sobel_x[2][0] * G[x-1,y+1][0]) + (sobel_x[2][1] * G[x,y+1][0]) + \ (sobel_x[2][2] * G[x+1,y+1][0]) pyR = (sobel_y[0][0] * G[x-1,y-1][0]) + (sobel_y[0][1] * G[x,y-1][0]) + \ (sobel_y[0][2] * G[x+1,y-1][0]) + (sobel_y[1][0] * G[x-1,y][0]) + \ (sobel_y[1][1] * G[x,y][0]) + (sobel_y[1][2] * G[x+1,y][0]) + \ (sobel_y[2][0] * G[x-1,y+1][0]) + (sobel_y[2][1] * G[x,y+1][0]) + \ (sobel_y[2][2] * G[x+1,y+1][0]) pxG = (sobel_x[0][0] * G[x-1,y-1][1]) + (sobel_x[0][1] * G[x,y-1][1]) + \ (sobel_x[0][2] * G[x+1,y-1][1]) + (sobel_x[1][0] * G[x-1,y][1]) + \ (sobel_x[1][1] * G[x,y][1]) + (sobel_x[1][2] * G[x+1,y][1]) + \ (sobel_x[2][0] * G[x-1,y+1][1]) + (sobel_x[2][1] * G[x,y+1][1]) + \ (sobel_x[2][2] * G[x+1,y+1][1]) pyG = (sobel_y[0][0] * G[x-1,y-1][1]) + (sobel_y[0][1] * G[x,y-1][1]) + \ (sobel_y[0][2] * G[x+1,y-1][1]) + (sobel_y[1][0] * G[x-1,y][1]) + \ (sobel_y[1][1] * G[x,y][1]) + (sobel_y[1][2] * G[x+1,y][1]) + \ (sobel_y[2][0] * G[x-1,y+1][1]) + (sobel_y[2][1] * G[x,y+1][1]) + \ (sobel_y[2][2] * G[x+1,y+1][1]) pxB = (sobel_x[0][0] * G[x-1,y-1][0]) + (sobel_x[0][1] * G[x,y-1][0]) + \ (sobel_x[0][2] * G[x+1,y-1][0]) + (sobel_x[1][0] * G[x-1,y][0]) + \ (sobel_x[1][1] * G[x,y][0]) + (sobel_x[1][2] * G[x+1,y][0]) + \ (sobel_x[2][0] * G[x-1,y+1][0]) + (sobel_x[2][1] * G[x,y+1][0]) + \ (sobel_x[2][2] * G[x+1,y+1][0]) pyB = (sobel_y[0][0] * G[x-1,y-1][2]) + (sobel_y[0][1] * G[x,y-1][2]) + \ (sobel_y[0][2] * G[x+1,y-1][2]) + (sobel_y[1][0] * G[x-1,y][2]) + \ (sobel_y[1][1] * G[x,y][2]) + (sobel_y[1][2] * G[x+1,y][2]) + \ (sobel_y[2][0] * G[x-1,y+1][2]) + (sobel_y[2][1] * G[x,y+1][2]) + \ (sobel_y[2][2] * G[x+1,y+1][2]) gradxLineR.append(pxR) gradyLineR.append(pyR) gradxLineG.append(pxG) gradyLineG.append(pyG) gradxLineB.append(pxB) gradyLineB.append(pyB) gradxR.append(gradxLineR) gradyR.append(gradyLineR) gradxG.append(gradxLineG) gradyG.append(gradyLineG) gradxB.append(gradxLineB) gradyB.append(gradyLineB) sobeloutmagR = scipy.hypot(gradxR, gradyR) sobeloutdirR = scipy.arctan2(gradyR, gradxR) sobeloutmagG = scipy.hypot(gradxG, gradyG) sobeloutdirG = scipy.arctan2(gradyG, gradxG) sobeloutmagB = scipy.hypot(gradxB, gradyB) sobeloutdirB = scipy.arctan2(gradyB, gradxB) for x in range(width - 2): for y in range(height - 2): if (sobeloutdirR[x][y]<22.5 and sobeloutdirR[x][y]>=0) or \ (sobeloutdirR[x][y]>=157.5 and sobeloutdirR[x][y]<202.5) or \ (sobeloutdirR[x][y]>=337.5 and sobeloutdirR[x][y]<=360): sobeloutdirR[x][y] = 0 elif (sobeloutdirR[x][y]>=22.5 and sobeloutdirR[x][y]<67.5) or \ (sobeloutdirR[x][y]>=202.5 and sobeloutdirR[x][y]<247.5): sobeloutdirR[x][y] = 45 elif (sobeloutdirR[x][y]>=67.5 and sobeloutdirR[x][y]<112.5)or \ (sobeloutdirR[x][y]>=247.5 and sobeloutdirR[x][y]<292.5): sobeloutdirR[x][y] = 90 else: sobeloutdirR[x][y] = 135 if (sobeloutdirG[x][y]<22.5 and sobeloutdirG[x][y]>=0) or \ (sobeloutdirG[x][y]>=157.5 and sobeloutdirG[x][y]<202.5) or \ (sobeloutdirG[x][y]>=337.5 and sobeloutdirG[x][y]<=360): sobeloutdirG[x][y] = 0 elif (sobeloutdirG[x][y]>=22.5 and sobeloutdirG[x][y]<67.5) or \ (sobeloutdirG[x][y]>=202.5 and sobeloutdirG[x][y]<247.5): sobeloutdirG[x][y] = 45 elif (sobeloutdirG[x][y]>=67.5 and sobeloutdirG[x][y]<112.5)or \ (sobeloutdirG[x][y]>=247.5 and sobeloutdirG[x][y]<292.5): sobeloutdirG[x][y] = 90 else: sobeloutdirG[x][y] = 135 if (sobeloutdirB[x][y]<22.5 and sobeloutdirB[x][y]>=0) or \ (sobeloutdirB[x][y]>=157.5 and sobeloutdirB[x][y]<202.5) or \ (sobeloutdirB[x][y]>=337.5 and sobeloutdirB[x][y]<=360): sobeloutdirB[x][y] = 0 elif (sobeloutdirB[x][y]>=22.5 and sobeloutdirB[x][y]<67.5) or \ (sobeloutdirB[x][y]>=202.5 and sobeloutdirB[x][y]<247.5): sobeloutdirB[x][y] = 45 elif (sobeloutdirB[x][y]>=67.5 and sobeloutdirB[x][y]<112.5)or \ (sobeloutdirB[x][y]>=247.5 and sobeloutdirB[x][y]<292.5): sobeloutdirB[x][y] = 90 else: sobeloutdirB[x][y] = 135 mag_supR = sobeloutmagR.copy() mag_supG = sobeloutmagG.copy() mag_supB = sobeloutmagB.copy() for x in range(1, width - 3): for y in range(1, height - 3): if sobeloutdirR[x][y] == 0: if (sobeloutmagR[x][y]<=sobeloutmagR[x][y+1]) or \ (sobeloutmagR[x][y]<=sobeloutmagR[x][y-1]): mag_supR[x][y] = 0 elif sobeloutdirR[x][y] == 45: if (sobeloutmagR[x][y]<=sobeloutmagR[x-1][y+1]) or \ (sobeloutmagR[x][y]<=sobeloutmagR[x+1][y-1]): mag_supR[x][y] = 0 elif sobeloutdirR[x][y] == 90: if (sobeloutmagR[x][y]<=sobeloutmagR[x+1][y]) or \ (sobeloutmagR[x][y]<=sobeloutmagR[x-1][y]): mag_supR[x][y] = 0 else: if (sobeloutmagR[x][y]<=sobeloutmagR[x+1][y+1]) or \ (sobeloutmagR[x][y]<=sobeloutmagR[x-1][y-1]): mag_supR[x][y] = 0 if sobeloutdirG[x][y] == 0: if (sobeloutmagG[x][y]<=sobeloutmagG[x][y+1]) or \ (sobeloutmagG[x][y]<=sobeloutmagG[x][y-1]): mag_supG[x][y] = 0 elif sobeloutdirG[x][y] == 45: if (sobeloutmagG[x][y]<=sobeloutmagG[x-1][y+1]) or \ (sobeloutmagG[x][y]<=sobeloutmagG[x+1][y-1]): mag_supG[x][y] = 0 elif sobeloutdirG[x][y] == 90: if (sobeloutmagG[x][y]<=sobeloutmagG[x+1][y]) or \ (sobeloutmagG[x][y]<=sobeloutmagG[x-1][y]): mag_supG[x][y] = 0 else: if (sobeloutmagG[x][y]<=sobeloutmagG[x+1][y+1]) or \ (sobeloutmagG[x][y]<=sobeloutmagG[x-1][y-1]): mag_supG[x][y] = 0 if sobeloutdirB[x][y] == 0: if (sobeloutmagB[x][y]<=sobeloutmagB[x][y+1]) or \ (sobeloutmagB[x][y]<=sobeloutmagB[x][y-1]): mag_supB[x][y] = 0 elif sobeloutdirB[x][y] == 45: if (sobeloutmagB[x][y]<=sobeloutmagB[x-1][y+1]) or \ (sobeloutmagB[x][y]<=sobeloutmagB[x+1][y-1]): mag_supB[x][y] = 0 elif sobeloutdirB[x][y] == 90: if (sobeloutmagB[x][y]<=sobeloutmagB[x+1][y]) or \ (sobeloutmagB[x][y]<=sobeloutmagB[x-1][y]): mag_supB[x][y] = 0 else: if (sobeloutmagB[x][y]<=sobeloutmagB[x+1][y+1]) or \ (sobeloutmagB[x][y]<=sobeloutmagB[x-1][y-1]): mag_supB[x][y] = 0 mR = numpy.max(mag_supR) mG = numpy.max(mag_supG) mB = numpy.max(mag_supB) thR = 0.2 * mR tlR = 0.1 * mR thG = 0.2 * mG tlG = 0.1 * mG thB = 0.2 * mB tlB = 0.1 * mB gnhR = numpy.zeros((width, height)) gnlR = numpy.zeros((width, height)) gnhG = numpy.zeros((width, height)) gnlG = numpy.zeros((width, height)) gnhB = numpy.zeros((width, height)) gnlB = numpy.zeros((width, height)) for x in range(width - 2): for y in range(height - 2): if mag_supR[x][y] >= thR: gnhR[x][y] = mag_supR[x][y] if mag_supR[x][y] >= tlR: gnlR[x][y] = mag_supR[x][y] if mag_supG[x][y] >= thG: gnhR[x][y] = mag_supG[x][y] if mag_supG[x][y] >= tlG: gnlG[x][y] = mag_supG[x][y] if mag_supB[x][y] >= thB: gnhB[x][y] = mag_supB[x][y] if mag_supB[x][y] >= tlB: gnlB[x][y] = mag_supB[x][y] gnlR = gnlR - gnhR gnlG = gnlG - gnhG gnlB = gnlB - gnhB def traverse(i, j): x = [-1, 0, 1, -1, 1, -1, 0, 1] y = [-1, -1, -1, 0, 0, 1, 1, 1] for k in range(8): if gnhR[i + x[k]][j + y[k]] == 0 and gnlR[i + x[k]][j + y[k]] != 0: gnhR[i + x[k]][j + y[k]] = 255 traverse(i + x[k], j + y[k]) if gnhG[i + x[k]][j + y[k]] == 0 and gnlG[i + x[k]][j + y[k]] != 0: gnhG[i + x[k]][j + y[k]] = 255 traverse(i + x[k], j + y[k]) if gnhB[i + x[k]][j + y[k]] == 0 and gnlB[i + x[k]][j + y[k]] != 0: gnhB[i + x[k]][j + y[k]] = 255 traverse(i + x[k], j + y[k]) for i in range(1, width - 1): for j in range(1, height - 1): if gnhR[i][j]: gnhR[i][j] = 255 traverse(i, j) if gnhG[i][j]: gnhG[i][j] = 255 traverse(i, j) if gnhB[i][j]: gnhB[i][j] = 255 traverse(i, j) for y in range(imgSize[0]): QCoreApplication.processEvents() for x in range(imgSize[1]): oldR, oldG, oldB = pixels[y, x] if currentImageChannelIndex == 0: pixels[y, x] = (int(gnhR[y][x]), int(gnhG[y][x]), int(gnhB[y][x])) if currentImageChannelIndex == 1: pixels[y, x] = (int(gnhR[y][x]), oldG, oldB) if currentImageChannelIndex == 2: pixels[y, x] = (oldR, int(gnhG[y][x]), oldB) if currentImageChannelIndex == 3: pixels[y, x] = (oldR, oldG, int(gnhB[y][x]))
return intercept, sd_intercept, slope, sd_slope, abs(res)<1*res.std() V_calibrated_M_0 = 0.4319 V_calibrated_M_0_err = 0.0184 I_calibrated_M_0 = 0.1065 I_calibrated_M_0_err = 0.0380 z_calibrated_M_0 = 0.5406 z_calibrated_M_0_err = 0.0539 V_M_0, V_M_0_err, V_alpha, V_alpha_err, V_fit_mask = fit_line(rrl_log_normalized_fundamental_periods[vmag_mask], rrl_data["V_mag"][vmag_mask]) I_M_0, I_M_0_err, I_alpha, I_alpha_err, I_fit_mask = fit_line(rrl_log_normalized_fundamental_periods[imag_mask], rrl_data["I_mag"][imag_mask]) z_M_0, z_M_0_err, z_alpha, z_alpha_err, z_fit_mask = fit_line(rrl_log_normalized_fundamental_periods, rrl_data["sdss_z_mag"]) V_mu = V_M_0 - V_calibrated_M_0 V_mu_err = hypot(V_calibrated_M_0_err, V_M_0_err) I_mu = I_M_0 - I_calibrated_M_0 I_mu_err = hypot(I_calibrated_M_0_err, I_M_0_err) z_mu = z_M_0 - z_calibrated_M_0 z_mu_err = hypot(z_calibrated_M_0_err, z_M_0_err) def scatter2fract_dist(scatter_mag): upper = ((10**((scatter_mag+5)/5))/10)-1 lower = 1-((10**((-scatter_mag+5)/5))/10) return (upper + lower)/2 def compute_distance(mu, mu_err, A=0, A_err=0): effective_mu = mu-A effective_mu_err = (mu_err**2 + A_err**2)**0.5
def __init__(self, zp_radius, dx_zp): zp_radius_in_pixels = sp.ceil(zp_radius*1e-6/dx_zp) self.T = spf.fftshift(spf.fft2(sp.where(sp.hypot(*sp.ogrid[-1024:1024, -1024:1024])<zp_radius_in_pixels, 1., 0.)))
def canny(imgfile): sigma = 4 f = imgfile img = Image.open(f).convert('L') #grayscale imgdata = numpy.array(img, dtype = float) G = ndi.filters.gaussian_filter(imgdata, sigma) #gaussian low pass filter sobelout = Image.new('L', img.size) #empty image gradx = numpy.array(sobelout, dtype = float) grady = numpy.array(sobelout, dtype = float) sobel_x = [[-1,0,1], [-2,0,2], [-1,0,1]] sobel_y = [[-1,-2,-1], [0,0,0], [1,2,1]] width = img.size[1] height = img.size[0] #calculate |G| and dir(G) for x in range(1, width-1): for y in range(1, height-1): px = (sobel_x[0][0] * G[x-1][y-1]) + (sobel_x[0][1] * G[x][y-1]) + \ (sobel_x[0][2] * G[x+1][y-1]) + (sobel_x[1][0] * G[x-1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x+1][y]) + \ (sobel_x[2][0] * G[x-1][y+1]) + (sobel_x[2][1] * G[x][y+1]) + \ (sobel_x[2][2] * G[x+1][y+1]) py = (sobel_y[0][0] * G[x-1][y-1]) + (sobel_y[0][1] * G[x][y-1]) + \ (sobel_y[0][2] * G[x+1][y-1]) + (sobel_y[1][0] * G[x-1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x+1][y]) + \ (sobel_y[2][0] * G[x-1][y+1]) + (sobel_y[2][1] * G[x][y+1]) + \ (sobel_y[2][2] * G[x+1][y+1]) gradx[x][y] = px grady[x][y] = py sobeloutmag = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) scipy.misc.imsave('cannynewmag.jpg', sobeloutmag) scipy.misc.imsave('cannynewdir.jpg', sobeloutdir) for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y]=0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y]=45 elif (sobeloutdir[x][y]>=67.5 and sobeloutdir[x][y]<112.5)or \ (sobeloutdir[x][y]>=247.5 and sobeloutdir[x][y]<292.5): sobeloutdir[x][y]=90 else: sobeloutdir[x][y]=135 scipy.misc.imsave('cannynewdirquantize.jpg', sobeloutdir) mag_sup = sobeloutmag.copy() for x in range(1, width-1): for y in range(1, height-1): if sobeloutdir[x][y]==0: if (sobeloutmag[x][y]<=sobeloutmag[x][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==45: if (sobeloutmag[x][y]<=sobeloutmag[x-1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x+1][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==90: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y]): mag_sup[x][y]=0 else: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y-1]): mag_sup[x][y]=0 scipy.misc.imsave('cannynewmagsup.jpg', mag_sup) m = numpy.max(mag_sup) th = 0.2*m tl = 0.1*m gnh = numpy.zeros((width, height)) gnl = numpy.zeros((width, height)) for x in range(width): for y in range(height): if mag_sup[x][y]>=th: gnh[x][y]=mag_sup[x][y] if mag_sup[x][y]>=tl: gnl[x][y]=mag_sup[x][y] scipy.misc.imsave('cannynewgnlbeforeminus.jpg', gnl) gnl = gnl-gnh scipy.misc.imsave('cannynewgnlafterminus.jpg', gnl) scipy.misc.imsave('cannynewgnh.jpg', gnh) def traverse(i, j): x = [-1, 0, 1, -1, 1, -1, 0, 1] y = [-1, -1, -1, 0, 0, 1, 1, 1] for k in range(8): if gnh[i+x[k]][j+y[k]]==0 and gnl[i+x[k]][j+y[k]]!=0: gnh[i+x[k]][j+y[k]]=1 traverse(i+x[k], j+y[k]) for i in range(1, width-1): for j in range(1, height-1): if gnh[i][j]: gnh[i][j]=1 traverse(i, j) gnh = gnh[:100,:64] scipy.misc.imsave('cannynewout.jpg', gnh) return gnh
def test_case(): import pylab as pyl pyl.ion() from pylab import matshow, show, plot # Generate test data lena = sp.misc.lena() shape = lena.shape mask = np.where(sp.hypot(*sp.ogrid[-shape[0]/2:shape[0]/2, -shape[1]/2:shape[1]/2])<50, 1.0, 0.0) lena *= mask shift = [10,15] # Test least squares try: sample = np.zeros((128,128)) sample[34,64]=1e3 theta = np.linspace(0,180,num=200,endpoint=True) sino = np.rollaxis(radon(sample, theta=theta, circle=True), 1, 0) sino3D = np.zeros((200,128,128)) for i in range(54,74): sino3D[:,i,:] = sino # Test 2D sinogram #================= # Insert random misalignment for i in range(200): sx = 12*(np.random.random()-0.5) sino[i,:] = spni.shift(sino[i,:],(sx,)) sino_out=least_sq(sino, theta) assert(np.allclose(sino, sino_out)) # Test 3D sinogram #================= # Insert random misalignment for i in range(200): sx = 12*(np.random.random()-0.5) sino3D[i,:,:] = spni.shift(sino3D[i,:,:],(0,sx)) sino_out=least_sq(sino3D, theta) assert(np.allclose(sino3D, sino_out)) print('Least squares sinogram alignment: PASSED') except AssertionError: print('Least squares sinogram alignment: FAILED') # Test cross correlation try: rec_shift = cross_correlate(lena, translate(lena, -shift[0], -shift[1])) assert rec_shift == shift print('Cross correlation test: PASSED') except AssertionError: print('Cross correlation test: FAILED') # Test phase correlation try: rec_shift = phase_correlate(lena, translate(lena, -shift[0], -shift[1])) assert rec_shift == shift print('Phase correlation test: PASSED') except AssertionError: print('Phase correlation test: FAILED') # Test invariant correlation try: img, scale, angle, rec_shift= imreg.similarity(lena, translate(lena, -shift[0], -shift[1])) rec_shift[0] *= -1 rec_shift[1] *= -1 assert rec_shift == shift print('Invariant correlation test: PASSED') except AssertionError: print('Invariant correlation test: FAILED') ipdb.set_trace()
if zo == 0: zo = scipy.median(z) if zunit = 'velocity': v = z zo /= c else: v = c * (z-zo)/(1+zo) # then x corresponds to cluster-centric distance: if len(y) == 0: if xyunit == 'kpc': r = x / 1e3 elif xyunit in ('deg', 'arcmin', 'arcsec'): r = cosmology.dProj(zo, x, input_unit=xyunit, unit='Mpc') # otherwise use the given center to calculate distances elif xyunit in ('kpc', 'Mpc'): r = scipy.hypot(x, y) if xyunit == 'kpc': r /= 1e3 else: if xyunit == 'arcsec': x /= 3600. y /= 3600. if xyunit == 'arcmin': x /= 60. y /= 60. dist = astCoords.calcAngSepDeg(x, y, xycenter[0], xycenter[1]) r = cosmology.dProj(zo, dist, input_unit='deg', unit='Mpc')
ptych_num = spec_data.shape[0] xscansize = np.max(spec_data[:, 0]) - np.min(spec_data[:, 0]) yscansize = np.max(spec_data[:, 1]) - np.min(spec_data[:, 1]) midposx = np.min(spec_data[:, 0]) + xscansize / 2.0 midposy = np.min(spec_data[:, 1]) + yscansize / 2.0 # centre the scan and convert the positions to pixel units pos_x = (spec_data[:, 0] - midposx) // dx4 pos_y = (spec_data[:, 1] - midposy) // dx4 radpix = sp.hypot(*sp.ogrid[-padpix / 2.0 : padpix / 2.0, -padpix / 2.0 : padpix / 2]) dataFilename = f"pos_000000_to_{ptych_num-1:06}_int_sum.npy" data = np.load(fulldatapath + dataFilename) if data.shape[0] == data.shape[1]: data = data.transpose(2, 0, 1) data_energy = np.sum(data, axis=(1, 2)) inverse_data_energy = 1.0 / data_energy data = np.sqrt(data)
def incircle(cx, cy, r, x, y): """Return True if (x,y) is strictly inside the circle centered at (cx,cy) with radius r. """ r2 = sp.hypot(x-cx, y-cy) assert r2 < r
def cosine_peak(x, y): circle = sp.hypot(80 * x - 40.0, 90 * y - 45.) f = sp.exp(-0.04 * circle) * sp.cos(0.15 * circle) return f
def smooth_map(x, y, lum=None, center=None, z=None, r200=1, dx=0.02, width=4, profile='gauss', rweight='wen13'): """ Calculate a smoothed map of the light distribution or galaxy number density, using the radial weighting of Wen & Han (2013) Parameters ---------- x : array of floats galaxy positions in the x direction, in Mpc (relative to cluster center unless center is given). y : array of floats galaxy positions in the y direction, in Mpc (relative to cluster center unless center is given). lum : array of floats, same length as x and y (optional) galaxy luminosity or other weighting value. If not specified the map returned corresponds to the galaxy density map. center : array-like of 2 floats (optional) if defined, must be an array-like with the coordinates of the cluster center (RA and Dec). x and y must then be RA and Dec, respectively, and distances will be calculated here. z : float (must be given if center is given) redshift of the cluster. r200 : float (default 1) radius of the cluster in Mpc, used mainly for the radial weighting of Wen & Han. Alternatively, x and y can already be in units of r200 or the desired radius. dx : float (default 0.02) width of the bin, in Mpc. The same size is used for x and y. width : float (default 4) total width of the map, in Mpc. profile : str (default 'gaussian') 2d profile to use in the smoothing. Currently only a gaussian with the radial weighting of Wen & Han (2013). rweight : {'wen13', float} radial weighting for the smoothed profile. Currently, can only be that of Wen & Han or a constant weight for all galaxies, in which case the width of the gaussian (in Mpc) should be given. Returns ------- smap : 2-dimensional array of floats the smoothed map. Notes ----- - Any selection of galaxies must be done outside of this function """ # first, check data formats N = len(x) if len(y) != N: raise ValueError('lengths of x and y must be the same') if lum is not None: if len(lum) != N: raise ValueError('length of lum must be the same as len(x) if defined') lum = 1 if center is not None: if len(center) != 2: msg = 'argument *center* must be an array-like with 2 values' raise ValueError(msg) if z is None: msg = 'argument center is given, therefore a redshift must be given' raise ValueError(msg) if profile != 'gauss': msg = 'WARNING: only a gaussian profile is implemented;' msg += ' falling back to it' print msg profile = 'gaussian' x200 = r200 / dx # check whether center is given if center is not None: dz = cosmology.dA(z) * scipy.pi/180 # want to do it like this because the sign matters! x = -1 * (x - center[0]) * scipy.cos(scipy.pi/180 * center[1]) * dz y = (y - center[1]) * dz # create grid edge = width/2. bins = scipy.arange(-edge-dx/2., edge+dx, dx) Nbins = len(bins) xo = yo = scipy.array([(bins[i]+bins[i-1])/2 for i in xrange(1, Nbins)]) # each galaxy's distance to each cell (dimension 3xN) dcells = scipy.array([[scipy.hypot(x-xi, y-yj) for xi in xo] for yj in yo]) dist = scipy.hypot(x, y) / x200 # choice of profile and calculation of map if profile == 'gauss': def p(t, s): # why is there a s**2 in the denominator, instead of s? return dx**2 * scipy.exp(-t**2/(2*s**2)) / (s*scipy.sqrt(2*scipy.pi)) if rweight == 'wen13': w = (0.03 + 0.15*dist) * x200 else: w = rweight grid = [scipy.array([sum(lum * p(dij, w)) for dij in dcells[jj]]) \ for jj in xrange(len(yo))] # done! return scipy.array(grid), bins
def simulate_data(self): CXP.log.info('Simulating diffraction patterns.') self.sample = CXData() self.sample.load(CXP.io.simulation_sample_filename[0]) self.sample.data[0] = self.sample.data[0].astype(float) self.sample.normalise(val=0.8) self.sample.data[0]+=0.2 self.input_probe = CXModal() if len(CXP.io.simulation_sample_filename)>1: ph = CXData() ph.load(CXP.io.simulation_sample_filename[1]) ph.data[0] = ph.data[0].astype(float) ph.normalise(val=np.pi/3) self.sample.data[0] = self.sample.data[0]*exp(complex(0., 1.)*ph.data[0]) p = self.sample.data[0].shape[0] ham_window = sp.hamming(p)[:,np.newaxis]*sp.hamming(p)[np.newaxis,:] sample_large = CXData(data=sp.zeros((CXP.ob_p, CXP.ob_p), complex)) sample_large.data[0][CXP.ob_p/2-p/2:CXP.ob_p/2+p/2, CXP.ob_p/2-p/2:CXP.ob_p/2+p/2] = self.sample.data[0]*ham_window ker = sp.arange(0, p) fwhm = p/3.0 radker = sp.hypot(*sp.ogrid[-p/2:p/2,-p/2:p/2]) gaussian = exp(-1.0*(fwhm/2.35)**-2. * radker**2.0 ) ortho_modes = lambda n1, n2 : gaussian*np.sin(n1*math.pi*ker/p)[:,np.newaxis]*np.sin(n2*math.pi*ker/p)[np.newaxis, :] mode_generator = lambda : sp.floor(4*sp.random.random(2))+1 used_modes = [] self.input_psi = CXModal() for mode in range(CXP.reconstruction.probe_modes): if mode==0: new_mode = [1,1] else: new_mode = list(mode_generator()) while new_mode in used_modes: new_mode = list(mode_generator()) used_modes.append(new_mode) CXP.log.info('Simulating mode {:d}: [{:d}, {:d}]'.format(mode, int(new_mode[0]), int(new_mode[1]))) ph_func = gauss_smooth(np.random.random((p,p)), 10) self.input_probe.modes.append(CXData(name='probe{:d}'.format(mode), data=ortho_modes(new_mode[0], new_mode[1])*exp(complex(0.,np.pi)*ph_func/ph_func.max()))) self.input_probe.normalise() self.input_probe.orthogonalise() for mode in range(CXP.reconstruction.probe_modes): p2 = p/2 x, y = self.positions.correct self.input_psi.modes.append(CXData(name='input_psi_mode{:d}'.format(mode), data=[])) for i in xrange(len(x)): if i%(len(x)/10)==0.: CXP.log.info('Simulating diff patt {:d}'.format(i)) tmp = (CXData.shift(sample_large, -1.0*(x[i]-CXP.ob_p/2), -1.0*(y[i]-CXP.ob_p/2)) [CXP.ob_p/2-p2:CXP.ob_p/2+p2, CXP.ob_p/2-p2:CXP.ob_p/2+p2]* self.input_probe[mode][0]) self.input_psi[mode].data.append(tmp.data[0]) # Add modes incoherently self.det_mod = CXModal.modal_sum(abs(fft2(self.input_psi))) self.det_mod.save(path=CXP.io.base_dir+'/'+CXP.io.scan_id+'/raw_data/{:s}.npy'.format('det_mod'))
def cosine_peak(x, y): circle = sp.hypot(80*x-40.0, 90*y-45.) f = sp.exp(-0.04*circle) * sp.cos(0.15*circle) return f
def canny(imgfile): sigma = 4 f = imgfile img = Image.open(f).convert('L') #grayscale img = img.resize((constants.CANNY_RESIZE_WIDTH, constants.CANNY_RESIZE_HEIGHT), Image.NEAREST) #resize para evitar errores imgdata = numpy.array(img, dtype = float) G = ndi.filters.gaussian_filter(imgdata, sigma) #gaussian low pass filter sobelout = Image.new('L', img.size) #empty image gradx = numpy.array(sobelout, dtype = float) grady = numpy.array(sobelout, dtype = float) sobel_x = [[-1,0,1], [-2,0,2], [-1,0,1]] sobel_y = [[-1,-2,-1], [0,0,0], [1,2,1]] width = img.size[1] height = img.size[0] #calculate |G| and dir(G) for x in range(1, width-1): for y in range(1, height-1): px = (sobel_x[0][0] * G[x-1][y-1]) + (sobel_x[0][1] * G[x][y-1]) + \ (sobel_x[0][2] * G[x+1][y-1]) + (sobel_x[1][0] * G[x-1][y]) + \ (sobel_x[1][1] * G[x][y]) + (sobel_x[1][2] * G[x+1][y]) + \ (sobel_x[2][0] * G[x-1][y+1]) + (sobel_x[2][1] * G[x][y+1]) + \ (sobel_x[2][2] * G[x+1][y+1]) py = (sobel_y[0][0] * G[x-1][y-1]) + (sobel_y[0][1] * G[x][y-1]) + \ (sobel_y[0][2] * G[x+1][y-1]) + (sobel_y[1][0] * G[x-1][y]) + \ (sobel_y[1][1] * G[x][y]) + (sobel_y[1][2] * G[x+1][y]) + \ (sobel_y[2][0] * G[x-1][y+1]) + (sobel_y[2][1] * G[x][y+1]) + \ (sobel_y[2][2] * G[x+1][y+1]) gradx[x][y] = px grady[x][y] = py sobeloutmag = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y]=0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y]=45 elif (sobeloutdir[x][y]>=67.5 and sobeloutdir[x][y]<112.5)or \ (sobeloutdir[x][y]>=247.5 and sobeloutdir[x][y]<292.5): sobeloutdir[x][y]=90 else: sobeloutdir[x][y]=135 mag_sup = sobeloutmag.copy() for x in range(1, width-1): for y in range(1, height-1): if sobeloutdir[x][y]==0: if (sobeloutmag[x][y]<=sobeloutmag[x][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==45: if (sobeloutmag[x][y]<=sobeloutmag[x-1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x+1][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==90: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y]): mag_sup[x][y]=0 else: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y-1]): mag_sup[x][y]=0 m = numpy.max(mag_sup) th = 0.2*m tl = 0.1*m gnh = numpy.zeros((width, height)) gnl = numpy.zeros((width, height)) for x in range(width): for y in range(height): if mag_sup[x][y]>=th: gnh[x][y]=mag_sup[x][y] if mag_sup[x][y]>=tl: gnl[x][y]=mag_sup[x][y] gnl = gnl-gnh def traverse(i, j): x = [-1, 0, 1, -1, 1, -1, 0, 1] y = [-1, -1, -1, 0, 0, 1, 1, 1] for k in range(8): if gnh[i+x[k]][j+y[k]]==0 and gnl[i+x[k]][j+y[k]]!=0: gnh[i+x[k]][j+y[k]]=1 traverse(i+x[k], j+y[k]) for i in range(1, width-1): for j in range(1, height-1): if gnh[i][j]: gnh[i][j]=1 traverse(i, j) gnh = gnh[:100,:64] return gnh
fwhm_list.append([new_fwhm_median, phot_cat_path]) if len(data) < 23: continue for row in data: row_ra = row[3] row_dec = row[4] curve_coords_ra = zeros(len(light_curve_data)) curve_coords_dec = zeros(len(light_curve_data)) for n in range(len(light_curve_data)): curve_coords_ra[n] = light_curve_data[n][0] curve_coords_dec[n] = light_curve_data[n][1] dist_array = hypot(cos(row_dec*0.01745329252)*(row_ra-curve_coords_ra), row_dec-curve_coords_dec) if len(dist_array) > 0: min_dist_index = where(dist_array==dist_array.min())[0][0] row_curve_separation = 206264.806247*(float(ephem.separation( (light_curve_data[min_dist_index][0] * 0.01745329252, light_curve_data[min_dist_index][1] * 0.01745329252), (row_ra * 0.01745329252, row_dec * 0.01745329252)))) if row_curve_separation < 2.0: curve_length = len(light_curve_data[min_dist_index][2]) light_curve_data[min_dist_index][0] = \ light_curve_data[min_dist_index][0] * \ ((curve_length-1.0)/float(curve_length)) + \ row_ra*((1.0)/float(curve_length)) light_curve_data[min_dist_index][1] = \ light_curve_data[min_dist_index][1] * \ ((curve_length-1.0)/float(curve_length)) + \
def edgeDetection(im): sigma = 1.4 # imdata = numpy.array(im) imdata = numpy.array(im, dtype = float) # image: 494 * 343 ---> but Image(x, y) will be represent in array like Arr[y][x], so Arr will become 343 * 494, so Arr[x][y] will refer to the image(x,y) # G = imdata G = ndi.filters.gaussian_filter(imdata, sigma) # G = numpy.transpose(imdata) # numpy.transpose(G) gradOut = Image.new('L', im.size) gradx = numpy.array(gradOut, dtype = float) grady = numpy.array(gradOut, dtype = float) # graddxdy = numpy.array(gradOut, dtype = float) kernel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] kernel_y = [[-1, -2, -1], [ 0, 0, 0], [-1, -2, -1]] # numpy.array will change image from 424 * 343 to 343*424 array width = im.size[1] height = im.size[0] # print width, height for x in range(1, width - 1): for y in range(1, height -1): px = kernel_x[0][0] * G[x-1][y-1] + kernel_x[0][1] * G[x][y-1] + \ kernel_x[0][2] * G[x+1][y-1] + kernel_x[1][0] * G[x-1][y] + \ kernel_x[1][1] * G[x][y] + kernel_x[1][2] * G[x+1][y] + \ kernel_x[2][0] * G[x-1][y+1] + kernel_x[2][1] * G[x][y+1] + \ kernel_x[2][2] * G[x+1][y+1] py = kernel_y[0][0] * G[x-1][y-1] + kernel_y[0][1] * G[x][y-1] + \ kernel_y[0][2] * G[x+1][y-1] + kernel_y[1][0] * G[x-1][y] + \ kernel_y[1][1] * G[x][y] + kernel_y[1][2] * G[x+1][y] + \ kernel_y[2][0] * G[x-1][y+1] + kernel_y[2][1] * G[x][y+1] + \ kernel_y[2][2] * G[x+1][y+1] gradx [x][y] = px grady [x][y] = py # graddxdy [x][y] = py * 1.0 / px sobeloutmag = scipy.hypot(gradx, grady) sobeloutmag_n = sobeloutmag / numpy.max(sobeloutmag) mag_sup = scipy.hypot(gradx, grady) sobeloutdir = scipy.arctan2(grady, gradx) for x in range(width): for y in range(height): if (sobeloutdir[x][y]<22.5 and sobeloutdir[x][y]>=0) or \ (sobeloutdir[x][y]>=157.5 and sobeloutdir[x][y]<202.5) or \ (sobeloutdir[x][y]>=337.5 and sobeloutdir[x][y]<=360): sobeloutdir[x][y]=0 elif (sobeloutdir[x][y]>=22.5 and sobeloutdir[x][y]<67.5) or \ (sobeloutdir[x][y]>=202.5 and sobeloutdir[x][y]<247.5): sobeloutdir[x][y]=45 elif (sobeloutdir[x][y]>=67.5 and sobeloutdir[x][y]<112.5)or \ (sobeloutdir[x][y]>=247.5 and sobeloutdir[x][y]<292.5): sobeloutdir[x][y]=90 else: sobeloutdir[x][y]=135 for x in range(1, width-1): for y in range(1, height-1): if sobeloutdir[x][y]==0: if (sobeloutmag[x][y]<=sobeloutmag[x][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==45: if (sobeloutmag[x][y]<=sobeloutmag[x-1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x+1][y-1]): mag_sup[x][y]=0 elif sobeloutdir[x][y]==90: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y]): mag_sup[x][y]=0 else: if (sobeloutmag[x][y]<=sobeloutmag[x+1][y+1]) or \ (sobeloutmag[x][y]<=sobeloutmag[x-1][y-1]): mag_sup[x][y]=0 return mag_sup/numpy.max(mag_sup), gradx, grady
if (j == 0): Ex = p[i][j + 1] - p[i][j] else: if (j == N): Ex = p[i][j - 1] - p[i][j] else: Ex = (p[i][j - 1] - p[i][j + 1]) / 2 return Ex, Ey for i in range(N + 1): for j in range(N + 1): Exx[i][j], Eyy[i][j] = E(i, j) # Plot the streamlines with an appropriate colormap and arrow style color = sp.hypot(Exx, Eyy) plt.streamplot(x, x, Exx, Eyy, color=color, linewidth=1, cmap=plt.cm.inferno, density=2, arrowstyle='->', arrowsize=1.5) plt.xlim(-N // 2, N // 2) plt.ylim(-N // 2, N // 2) plt.gca().set_aspect('equal') plt.colorbar().set_label('Elecric Field (V/cm)')