def transform(img, scale, sigma, cval=0, ret_trans=False): ''' Transforms a single 2D image ''' trans = np.indices(img.shape) + \ scale * np.random.uniform(-1, 1, (2,) + img.shape) for t in trans: gauss(t, sigma, output=t, mode='nearest', truncate=2) ret_img = mapcoords(img, trans, order=1, cval=cval, mode='constant') if ret_trans: return ret_img, trans else: return ret_img
def calcFlow(self, relative=True, blur=(0,0,0), parameters=None): flowParams = {'pyr_scale':0.5, 'levels':3, 'winsize':7, 'iterations':3, 'poly_n':5, 'poly_sigma':1.1, 'flags':cv2.OPTFLOW_FARNEBACK_GAUSSIAN} flowParams = parameters if parameters else flowParams frames, h, w = self.data.shape self.xflow = ndarray((frames-1,h,w)) self.yflow = ndarray((frames-1,h,w)) data = self.data if relative: f0 = percentile(self.data,10,0); plt.imshow(f0, cmap='gray', interpolation='nearest', vmin=f0.min(), vmax=f0.max()) plt.title("F0"); plt.colorbar() data = (self.data-f0)/f0 blurData = gauss(data, blur) prev = self.data[0] for i,curr in enumerate(blurData[1:]): flow = cv2.calcOpticalFlowFarneback(prev, curr, **flowParams) self.xflow[i] = flow[:,:,0] self.yflow[i] = flow[:,:,1] prev = curr
def __init__ (self, energy=None, gradient=None, field=None, g_grad=True, notes=None, names=None, interpolate=False): self.energy = energy self.energy_g = gauss(self.energy,1.0,mode='constant') self.shape = self.energy.shape self.ndim = len(self.shape) self.idx = np.meshgrid(*[range(self.shape[d]) for d in range(self.ndim)],indexing='ij' ) if field == None: self.field = self.idx else: self.field = field if np.all(energy != None): if np.all(gradient == None): if g_grad: self.gradient= np.array(np.gradient(self.energy_g)) else: self.gradient= np.array(np.gradient(self.energy)) else: self.gradient = gradient self.idxs = np.vstack([i.ravel() for i in self.idx]).transpose() if interpolate: self._do_interpolate(kind="Energy") self._do_interpolate(kind="Gradient") else: self.interp_E = None self.interp_grad = None self.slc =[ [slice(0,1,1)] * len(self.shape) for i in range(self.ndim) ] self.field_interp = [] # FUNC[axis](index) -> value self.field_invert = [] # FUNC[axis](value) -> index self.axis=[] for i in range(self.ndim): self.slc[i][i] = slice(None) self.axis.append(self.field[i][self.slc[i]].ravel()) self.field_interp.append(interp1d(range(self.shape[i]),self.axis[i],bounds_error=False,fill_value='extrapolate')) self.field_invert.append(interp1d(self.axis[i],range(self.shape[i]),bounds_error=False,fill_value='extrapolate')) self.dR = np.array([ np.average(np.diff(self.axis[i])) for i in range(self.ndim) ]) self.notes=notes self.names=names
or blur images, and are often used to reduce the affect of scatter or noise in an image. ''' #Add Some Random Noise #To see how this works, let's first add some random noise to our image - such as you might see in a photograph taken in low light or at a low resolution. import skimage img_n = skimage.util.random_noise(img_eq) plt.imshow(img_n) #Using a Gaussian Filter #A Gaussian filter is a slightly more complex version of a mean filter, with a similar blurring effect. from scipy.ndimage.filters import gaussian_filter as gauss img_gauss = gauss(img_n, sigma=1) plt.imshow(img_gauss) #Using a Median Filter ''' The Gaussian filter results in a blurred image, which may actually be better for feature extraction as it makes it easier to find contrasting areas. If it's too blurred, we could try a median filter, which as the name suggests applies the median value to the pixel in the center of the filter kernel. ''' from scipy.ndimage.filters import median_filter as med img_med = med(img_n, size=2) plt.imshow(img_med) ''' Extract Features
I = data.camera() I = img_as_float(I) Gx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) Gy = np.transpose(Gx) Ix = conv(I, Gx, mode='constant') Iy = conv(I, Gy, mode='constant') plt.figure(1) plt.subplot(1,2,1) plt.imshow(Ix) plt.subplot(1,2,2) plt.imshow(Iy) # Tenseur Axx = gauss(Ix*Ix, 1, mode='constant') Ayy = gauss(Iy*Iy, 1, mode='constant') Axy = gauss(Ix*Iy, 1, mode='constant') # determinant detA = Axx * Ayy - Axy ** 2 # trace traceA = Axx + Ayy # Response k = 0.05 R = detA - k * traceA ** 2 # R = corner_harris(I)
ori_img = Image.fromarray(img3) o_h,o_w = ori_img.size print() target_size = (200,200) new_img = ori_img.resize(target_size) # 直方图均衡 from PIL import Image import matplotlib.pyplot as plt img3 = Image.open("cat.jpg") img3 = np.array(img3) plt.hist(img3.ravel()) # 计算直方图 plt.show() plt.hist(img3.ravel(), bins=255, cumulative=True) # 累计直方图 from PIL import ImageOps img3_eq = ImageOps.equalize(Image.fromarray(img3)) # 直方图均衡化 # 去噪 import skimage img3_n = skimage.util.random_noise(img3_eq) # 加噪声 # 高斯滤波器 from scipy.ndimage.filters import gaussian_filter as gauss img3_gauss = gauss(img3_n,sigma=1) # 中值滤波 from scipy.ndimage.filters import median_filter as med img3_med = med(img3_n,size=3) # 特征提取 # Sobel边缘检测
def readSHARP(sharpnum, t_cm, ns, nph, sm=4, nocomp=False, magtype='los', coords='full'): """ Read magnetogram for SHARP region at specified time, and map to computational grid. Return br array and imbalance fraction (0 = flux balanced, 1 = unipolar). Currently used B-LOS. Argument sm is the standard deviation of the Gaussian filter used to smooth the magnetogram before interpolation. If nocomp=True, just returns original HMI magnetogram and mask arrays. Set magtype='los' for line-of-sight magnetograms, or magtype='br' to use radial-component (from vector-B) magnetograms. L-O-S shouldn't be used if the SHARPs are selected at their time of maximum flux, as it will give spurius data near the limb. Set coords='full' to account fully for CEA coordinate mapping used by HMI. Default is to assume that x, y in the HMI coordinates are just longitude and latitude. Outputs: br -- magnetogram with only this region (shifted to 180 degrees longitude) pcen -- amount of longitudinal shift imbalance -- imbalance in polarity k -- metadata """ # Get time series of longitudes of this SHARP region (0 is central meridian): c = drms.Client() if (magtype == 'los'): k, seg = c.query( ('hmi.sharp_cea_720s[%i]' % sharpnum) + '[' + t_cm + ']', key= 'USFLUX, CRPIX1, CRVAL1, CRPIX2, CRVAL2, CDELT1, CDELT2, NOAA_AR, AREA', seg='BITMAP, MAGNETOGRAM') if (magtype == 'br'): k, seg = c.query( ('hmi.sharp_cea_720s[%i]' % sharpnum) + '[' + t_cm + ']', key= 'USFLUX, CRPIX1, CRVAL1, CRPIX2, CRVAL2, CDELT1, CDELT2, NOAA_AR, AREA', seg='BITMAP, BR') # Download bounding data for region: im = fits.open('http://jsoc.stanford.edu' + seg.BITMAP[0]) mask = im[0].data if (magtype == 'los'): # Download l-o-s magnetogram data: im = fits.open('http://jsoc.stanford.edu' + seg.MAGNETOGRAM[0]) blos = im[1].data if (magtype == 'br'): # Download Br data: im = fits.open('http://jsoc.stanford.edu' + seg.BR[0]) blos = im[1].data blos = np.nan_to_num(blos) # set nan values to zero # Remove data outside SHARP masked region: blos[mask < 30] = 0.0 # Smooth with Gaussian filter: blos = gauss(blos, sm) # Get heliographic (Carrington) coordinates of image: ny, nx = blos.shape if (coords == 'full'): xmin = (1 - k.CRPIX1) * k.CDELT1 xmax = (nx - k.CRPIX1) * k.CDELT1 ymin = (1 - k.CRPIX2) * k.CDELT2 ymax = (ny - k.CRPIX2) * k.CDELT2 x = np.linspace(xmin + 0.5 * k.CDELT1, xmax - 0.5 * k.CDELT1, nx) y = np.linspace(ymin + 0.5 * k.CDELT2, ymax - 0.5 * k.CDELT2, ny) coslatc = np.cos(np.deg2rad(k.CRVAL2[0])) sinlatc = np.sin(np.deg2rad(k.CRVAL2[0])) yr, xr = np.meshgrid(np.deg2rad(y), np.deg2rad(x), indexing='ij') lat = np.arcsin(coslatc * yr + sinlatc * np.sqrt(1 - yr**2) * np.cos(xr)) lon = np.rad2deg( np.arcsin( np.sqrt(1 - yr**2) * np.sin(xr) / np.cos(lat))) + k.CRVAL1[0] lat = np.rad2deg(lat) if (nocomp): return mask, blos, lon, lat # Get s, phi coordinates of original map [and shift to Carrington # longitude 180 to avoid problems at edge of map later]: pcm = np.deg2rad(lon) scm = np.sin(np.deg2rad(lat)) pcen = np.sum(np.abs(blos) * pcm) / np.sum(np.abs(blos)) scen = np.sum(np.abs(blos) * scm) / np.sum(np.abs(blos)) pcm += np.pi - pcen points = np.stack((scm.flatten(), pcm.flatten()), axis=1) # Define the computational grid: ds = 2.0 / ns dph = 2 * np.pi / nph sc = np.linspace(-1 + 0.5 * ds, 1 - 0.5 * ds, ns) pc = np.linspace(0.5 * dph, 2 * np.pi - 0.5 * dph, nph) sc2, pc2 = np.meshgrid(sc, pc, indexing='ij') # Interpolate to the computational grid: br = griddata(points, blos.flatten(), (sc2, pc2), method='cubic', fill_value=0) br += griddata(points, blos.flatten(), (sc2, pc2 + 2 * np.pi), method='cubic', fill_value=0) br += griddata(points, blos.flatten(), (sc2, pc2 - 2 * np.pi), method='cubic', fill_value=0) else: xmin = (1 - k.CRPIX1) * k.CDELT1 + k.CRVAL1 xmax = (nx - k.CRPIX1) * k.CDELT1 + k.CRVAL1 ymin = (1 - k.CRPIX2) * k.CDELT2 + k.CRVAL2 ymax = (ny - k.CRPIX2) * k.CDELT2 + k.CRVAL2 lon = np.linspace(xmin + 0.5 * k.CDELT1, xmax - 0.5 * k.CDELT1, nx) lat = np.linspace(ymin + 0.5 * k.CDELT2, ymax - 0.5 * k.CDELT2, ny) if (nocomp): return mask, blos, lon, lat # Get s, phi coordinates of original map [and shift to Carrington # longitude 180 to avoid problems at edge of map later]: pcm = np.deg2rad(lon) scm = np.sin(np.deg2rad(lat)) scm2, pcm2 = np.meshgrid(scm, pcm, indexing='ij') pcen = np.sum(np.abs(blos) * pcm2) / np.sum(np.abs(blos)) scen = np.sum(np.abs(blos) * scm2) / np.sum(np.abs(blos)) pcm += np.pi - pcen # Define the computational grid: ds = 2.0 / ns dph = 2 * np.pi / nph sc = np.linspace(-1 + 0.5 * ds, 1 - 0.5 * ds, ns) pc = np.linspace(0.5 * dph, 2 * np.pi - 0.5 * dph, nph) # Interpolate to the computational grid: bri = interp2d(pcm, scm, blos, kind='cubic', copy=True, bounds_error=False, fill_value=0) br = np.zeros((ns, nph)) for i in range(ns): br[i, :] = bri(pc, sc[i]).flatten() + bri( pc + 2 * np.pi, sc[i]).flatten() + bri(pc - 2 * np.pi, sc[i]).flatten() del (bri) absflux = np.sum(np.abs(br)) * ds * dph * (6.96e10)**2 netflux = np.sum(br) * ds * dph * (6.96e10)**2 imbalance = netflux / absflux # Correct flux balance: br = correct_flux_multiplicative(br) return br, pcen, imbalance, k
plt.show() img3_noise = skimage.util.random_noise(img3_arr) plt.imshow(img3_noise) plt.show() fig = plt.figure(figsize=(12,4)) fig.add_subplot(1,2,1) plt.imshow(img3) fig.add_subplot(1,2,2) plt.imshow(img3_noise) plt.show() # GAUSS Filter, picuture will become blur from scipy.ndimage.filters import gaussian_filter as gauss img3_gauss = gauss(img3_noise, sigma=1) # ? TODO sigma mean, control the blur strength fig = plt.figure(figsize=(12,4)) fig.add_subplot(2,2,1) plt.imshow(img3) fig.add_subplot(2,2,3) plt.imshow(img3_noise) fig.add_subplot(2,2,4) plt.imshow(img3_gauss) plt.show() # the media filter, picuture will more sharp from scipy.ndimage import filters img3_med = filters.median_filter(img3_noise, size=3)
def plotModel(self,dist_pc=140,inc=3,extinction=0,show=False,sourcename='Oph.1'): self.dist=dist_pc*pc self.inc=inc self.extinction=extinction modelname = self.folder+self.name self.mo = ModelOutput(modelname+'.rtout') #tracy_dust = np.loadtxt('Tracy_models/OH5.par') chi = np.loadtxt('kmh94_3.1_full.chi') wav = np.loadtxt('kmh94_3.1_full.wav') Chi = interp1d(wav,chi,kind='linear') fig = plt.figure(figsize=(20,14)) ax=fig.add_subplot(2,3,1) sed = self.mo.get_sed(aperture=-1, inclination='all', distance=self.dist) #print tracy_dust[11,1],Cext(sed.wav[-1]),Cext(sed.wav[-1])/tracy_dust[11,1] tau = self.extinction*Chi(sed.wav)/Chi(0.550)/1.086 #print Cext(sed.wav)/tracy_dust[11,1] ext = np.array([np.exp(-tau) for i in range(sed.val.shape[0])]) #print tau,np.exp(-tau) ax.loglog(sed.wav, sed.val.transpose()*ext.T, color='black') ax.set_title(modelname+'_seds, Av='+str(self.extinction)) ax.set_xlim(sed.wav.min(), 1300) ax.set_ylim(1e-13, 1e-7) ax.set_xlabel(r'$\lambda$ [$\mu$m]') ax.set_ylabel(r'$\lambda F_\lambda$ [ergs/cm$^2/s$]') self.plotData(ax,sourcename) ax.set_xscale('log') ax.set_yscale('log') #ax.set_ylabel(r'$F_{Jy}$ [Jy]') #plt.legend(loc=4) ax=fig.add_subplot(2,3,2) sed = self.mo.get_sed(aperture=-1, inclination=self.inc, distance=self.dist) ext=np.exp(-tau) ax.loglog(sed.wav, sed.val.transpose()*ext.T, lw=3,color='black',label='source_total') ax.set_xlim(sed.wav.min(), 1300) ax.set_ylim(1e-13, 1e-7) ### for lamFlam sed = self.mo.get_sed(aperture=-1, inclination=self.inc, distance=self.dist,component='source_emit') ax.loglog(sed.wav, sed.val.transpose()*ext.T, color='blue',label='source_emit') sed = self.mo.get_sed(aperture=-1, inclination=self.inc, distance=self.dist,component='source_scat') ax.loglog(sed.wav, sed.val.transpose()*ext.T, color='teal',label='source_scat') sed = self.mo.get_sed(aperture=-1, inclination=self.inc, distance=self.dist,component='dust_emit') ax.loglog(sed.wav, sed.val.transpose()*ext.T, color='red',label='dust_emit') sed = self.mo.get_sed(aperture=-1, inclination=self.inc, distance=self.dist,component='dust_scat') ax.loglog(sed.wav, sed.val.transpose()*ext.T, color='orange',label='dust_scat') self.plotData(ax,sourcename) ax.set_xscale('log') ax.set_yscale('log') ax.set_title('seds_inc=inc') ax.set_xlabel(r'$\lambda$ [$\mu$m]') ax.set_ylabel(r'$\lambda F_\lambda$ [ergs/cm$^2/s$]') #ax.set_ylabel(r'$F_{Jy}$ [Jy]') leg = ax.legend(loc=4,fontsize='small') #leg = plt.gca().get_legend() #plt.setp(leg.get_text(),fontsize='small') # Extract the quantities g = self.mo.get_quantities() # Get the wall positions for r and theta rw, tw = g.r_wall / au, g.t_wall # Make a 2-d grid of the wall positions (used by pcolormesh) R, T = np.meshgrid(rw, tw) # Calculate the position of the cell walls in cartesian coordinates X, Z = R * np.sin(T), R * np.cos(T) # Make a plot in (x, z) space for different zooms from matplotlib.colors import LogNorm,PowerNorm # Make a plot in (r, theta) space ax = fig.add_subplot(2, 3, 3) if g.shape[-1]==2: c = ax.pcolormesh(X, Z, g['temperature'][0].array[0, :, :]+g['temperature'][1].array[0, :, :],norm=PowerNorm(gamma=0.5,vmin=1,vmax=500)) else : c = ax.pcolormesh(X, Z, g['temperature'][0].array[0, :, :],norm=PowerNorm(gamma=0.5,vmin=1,vmax=500)) #ax.set_xscale('log') #ax.set_yscale('log') ax.set_xlim(X.min(), X.max()/5.) ax.set_ylim(Z.min()/10., Z.max()/10.) ax.set_xlabel('x (au)') ax.set_ylabel('z (au)') #ax.set_yticks([np.pi, np.pi * 0.75, np.pi * 0.5, np.pi * 0.25, 0.]) #ax.set_yticklabels([r'$\pi$', r'$3\pi/4$', r'$\pi/2$', r'$\pi/4$', r'$0$']) cb = fig.colorbar(c) ax.set_title('Temperature structure') cb.set_label('Temperature (K)') #fig.savefig(modelname+'_temperature_spherical_rt.png', bbox_inches='tight') ax = fig.add_subplot(2, 3, 4) if g.shape[-1]==2: c = ax.pcolormesh(X, Z, g['density'][0].array[0, :, :]+g['density'][1].array[0, :, :],norm=LogNorm(vmin=1e-22,vmax=g['density'][0].array[0, :, :].max())) else : c = ax.pcolormesh(X, Z, g['density'][0].array[0, :, :],norm=LogNorm(vmin=1e-22,vmax=g['density'][0].array[0, :, :].max())) #ax.set_xscale('log') #ax.set_yscale('log') ax.set_xlim(X.min(), X.max()/5.) ax.set_ylim(Z.min()/10., Z.max()/10.) ax.set_xlabel('x (au)') ax.set_ylabel('z (au)') ax.set_title('Density structure') cb = fig.colorbar(c) cb.set_label('Density (g/cm2)') ### plot the convolved image with the 37 micron filter (manually set to slice 18 of the cube - this would change with wavelength coverage) ax = fig.add_subplot(2, 3, 5) self.image = self.mo.get_image(inclination=inc,distance=self.dist,units='Jy') fits.writeto(modelname+'_inc_'+str(inc)+'.fits',self.image.val.swapaxes(0,2).swapaxes(1,2),clobber=True) ### need to convolve the image with a Gaussian PSF pix = 2.*self.limval/au/self.Npix # in AU/pix pix_asec = pix/(self.dist/pc) # in asec/pix airy_asec = 3.5 #asec airy_pix = airy_asec/pix_asec # in pix gauss_pix = airy_pix/2.35 # in Gaussian std print "Gaussian std: ",gauss_pix from scipy.ndimage.filters import gaussian_filter as gauss #print [(i,sed.wav[i]) for i in range(len(sed.wav))] img37 = self.image.val[:,:,18] convol = gauss(img37,gauss_pix,mode='constant',cval=0.0) Nc = self.Npix/2 hw = min(int(20./pix_asec),Nc) #(max is Nc) #ax.imshow(img37,norm=LogNorm(vmin=1e-20,vmax=img37.max())) #ax.imshow(img37,interpolation='nearest') #ax.imshow(convol,norm=LogNorm(vmin=1e-20,vmax=img37.max())) #ax.imshow(convol,interpolation='nearest',norm=LogNorm(vmin=1e-20,vmax=img37.max())) ax.imshow(convol[Nc-hw:Nc+hw,Nc-hw:Nc+hw],interpolation='nearest',origin='lower',cmap=plt.get_cmap('gray')) airy_disk = plt.Circle((airy_pix*1.3,airy_pix*1.3),airy_pix,color=colors[3]) ax.add_artist(airy_disk) ax.text(airy_pix*3,airy_pix*1.3/2.0,'SOFIA 37um Airy disk',color=colors[3]) ax.set_title('Convolved image') fits.writeto(modelname+'_inc_'+str(inc)+'_convol37.fits',convol,clobber=True) ### draw a cross-section of the image to show the spatial extension in linear scale, to compare with what we observe in the model. ax = fig.add_subplot(2, 3, 6) ax.plot(range(Nc-hw,Nc+hw),convol[Nc-hw:Nc+hw,Nc-1],label='cross-section 1') ax.plot(range(Nc-hw,Nc+hw),convol[Nc-1,Nc-hw:Nc+hw],label='cross-section 2') maxconvol = convol[Nc-hw:Nc+hw,Nc-1].max() gauss = np.exp( -(np.array(range(-hw,hw))**2 / (2. * gauss_pix**2))) gauss/= gauss.max() gauss*=maxconvol ax.plot(range(Nc-hw,Nc+hw),gauss,label='SOFIA beam') leg = ax.legend(loc=2,fontsize='small') #leg = plt.gca().get_legend() #plt.setp(leg.get_text(),fontsize='small') ax.set_title('Cross section at the center') string=self.modelPrint() fig.text(0.0,0.14,string+'Av='+str(self.extinction)+'\n'+'dist='+str(self.dist/pc)+'\n',color='r') fig.savefig(modelname+'.png', bbox_inches='tight',dpi=300) if show: plt.show()
def get_gauss_filtered(hist, order): g = gauss(hist, 1, axis=-1, order=order, output=None, mode='nearest', truncate=2.0) return (g - g.min()) / (g.max() - g.min())