def phrag_map(bgrn, wid=10): """ Impose a model for phragmites on a scaled (R,G,B,N -> r,g,b,N/Nmax) map """ # -- smooth the images print("median filtering... ") t0 = time.time() imgsm = mf(bgrn, (1, wid, wid)) print(" {0}s".format(np.round(time.time() - t0, 2))) imgusm = uf(bgrn, (0, wid, wid)) img2usm = uf(bgrn**2, (0, wid, wid)) # -- get the variance image var = img2usm - imgusm**2 # -- get the pseudo NDVI pndvi = bgrn[3] - bgrn[2] # -- apply cuts return (imgsm[0] - imgsm[1] > 0.09) & (var[3] < 0.005) & (pndvi > 0.0)
def show_spectrum(event): if hold_spec[0]: return if event.inaxes==ax[0]: cind = int(round(event.xdata)) rind = int(round(event.ydata)) mn = cube.data[:,rind,cind].mean() sd = cube.data[:,rind,cind].std() if not median_filter: lin[0].set_data(waves,cube.data[:,rind,cind]) else: lin[0].set_data(waves,mf(cube.data[:,rind,cind], median_filter)) ax[1].set_ylim([min(-10,cube.data[:,rind,cind].min()), max(20,1.2*cube.data[:,rind,cind].max())]) pos_text.set_y(ax[1].get_ylim()[1]) pos_text.set_text('(row,col) = ({0:4},{1:4})'.format(rind,cind)) fig.canvas.draw() return
def show_spectrum(event): if hold_spec[0]: return if event.inaxes == ax[0]: cind = int(round(event.xdata)) rind = int(round(event.ydata)) mn = cube.data[:, rind, cind].mean() sd = cube.data[:, rind, cind].std() if not median_filter: lin[0].set_data(waves, cube.data[:, rind, cind]) else: lin[0].set_data(waves, mf(cube.data[:, rind, cind], median_filter)) ax[1].set_ylim([ min(-10, cube.data[:, rind, cind].min()), max(20, 1.2 * cube.data[:, rind, cind].max()) ]) pos_text.set_y(ax[1].get_ylim()[1]) pos_text.set_text('(row,col) = ({0:4},{1:4})'.format(rind, cind)) fig.canvas.draw() return
# Applied Data Science/ fall 2014 # # Video Project (Final) # # Dimas Rinarso Putro | [email protected] # # image_manipulation.py # ############################################## import os import sys import time import pylab import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf #1-7 img_ml = mf( 1.0 * (255 - nd.imread(os.path.join('images', 'ml.jpg'))[::2, ::2, ::-1]), [8, 2, 1]).clip(0, 255).astype(np.uint8) #plot it ysize = 10. xsize = ysize * float(img_ml.shape[1]) / float(img_ml.shape[0]) fig0, ax0 = plt.subplots(num=0, figsize=[xsize, ysize]) fig0.canvas.set_window_title('modified Mona Lisa') fig0.subplots_adjust(0, 0, 1, 1, 0, 0) ax0.axis('off') im0 = ax0.imshow(img_ml) fig0.canvas.draw() plt.show()
def plot_cube(cube,cmap='bone',clim=None,median_filter=False,figsize=10): """ An interactive visualization of the data cube. Parameters ---------- cube : HyperCube An instance of the HyperCube class to be shown. cmap : matplotlib color map, optional The matplotlib color map to use. clim : 2-element list, optional The limits of the color stretch. median_filter : float, optional Set the width of the median filter on the spectra. figsize : float, optional The horizontal width of the figure in inches. """ # -- set the flag to freeze the spectrum def toggle_hold(event): if event.button==1 and event.inaxes==ax[0]: hold_spec[0] = not hold_spec[0] return # -- mouseover event updates the spectrum def show_spectrum(event): if hold_spec[0]: return if event.inaxes==ax[0]: cind = int(round(event.xdata)) rind = int(round(event.ydata)) mn = cube.data[:,rind,cind].mean() sd = cube.data[:,rind,cind].std() if not median_filter: lin[0].set_data(waves,cube.data[:,rind,cind]) else: lin[0].set_data(waves,mf(cube.data[:,rind,cind], median_filter)) ax[1].set_ylim([min(-10,cube.data[:,rind,cind].min()), max(20,1.2*cube.data[:,rind,cind].max())]) pos_text.set_y(ax[1].get_ylim()[1]) pos_text.set_text('(row,col) = ({0:4},{1:4})'.format(rind,cind)) fig.canvas.draw() return # -- utilities waves = cube.wavelength*1e-3 if not cube.indexing else np.arange(cube.nwav) xlab = 'wavelength [micron]' if not cube.indexing else 'index' arat = float(cube.nrow)/float(cube.ncol) rat = arat*3./5. med = np.median(cube.img_L) sig = cube.img_L.std() scl = 0.2 if clim==None: clim = [scl*max(med - 2*sig,cube.img_L.min()), scl*min(med + 10*sig,cube.img_L.max())] # -- initialize the figure fig = plt.figure(figsize=[figsize,figsize*rat]) fig.subplots_adjust(0,0,1,1,0,0) ax = [] ax.append(fig.add_axes([0.1,0.35,0.85,0.6])) ax.append(fig.add_axes([0.1,0.1,0.85,0.2])) fig.set_facecolor('ivory') ax[0].axis('off') ax[1].set_ylim([-10,20]) ax[1].grid(1,color='white',ls='-',lw=1.5) ax[1].set_axis_bgcolor('lightgray') ax[1].set_xlabel(xlab) ax[1].set_xlim([waves.min(),waves.max()]) ax[1].set_ylabel('intensity\n[arb units]') ax[1].set_axisbelow(True) # -- show the grayscale iamge ax[0].imshow(cube.img_L,clim=clim,cmap=cmap,aspect=0.6/0.85*rat/arat) # -- plot the spectrum if not median_filter: lin = ax[1].plot(waves,cube.data[:,0,0],color='#E24A33',lw=1.5) else: lin = ax[1].plot(waves,mf(cube.data[:,0,0],median_filter), color='#E24A33',lw=1.5) # -- show the position of the spectrum pos_text = ax[1].text(ax[1].get_xlim()[1],ax[1].get_ylim()[1], '(row,col) = ({0:4},{1:4})'.format(0,0), ha='right',va='bottom') # -- initialize hold flag and connect events hold_spec = [False] fig.canvas.mpl_connect('button_press_event',toggle_hold) fig.canvas.mpl_connect('motion_notify_event',show_spectrum) return
def Fg_Extract(frame,type = 1,trun = 100): #extract foreground global BG_old global F_case global M_case global B_case if type ==1: # training BG mu[:] = alpha*frame + (1.0-alpha)*mu_old mu_old[:] = mu sig2[:] = alpha*(1.0*frame-mu)**2 + (1.0-alpha)*sig2_old sig2_old[:] = sig2 sig = sig2**0.5 lmcs = lmc*sig bmcs = bmc*sig sig_factor = 1 fg= (np.abs(1.0*frame-mu)[:,:,0]-sig_factor*sig[:,:,0]>0.0) +\ (np.abs(1.0*frame-mu)[:,:,1]-sig_factor*sig[:,:,1]>0.0) +\ (np.abs(1.0*frame-mu)[:,:,2]-sig_factor*sig[:,:,2]>0.0) elif type == 2: # avg total seq (need saved file) print('bg') BG = pickle.load(open("./BG/20141031.pkl","rb")) BG = cv2.resize(BG,(0,0),fx = scale,fy=scale) fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>50.)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>50.)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>50.) elif type == 2.5 : #avg total seq (need saved file) normalized image BG = pickle.load(open("./BG/car accident.pkl","rb")) BG = cv2.resize(BG,(0,0),fx = scale,fy=scale) fcal = np.zeros(BG.shape) BG_r_avg = BG[:,:,0][Rmask].mean() BG_g_avg = BG[:,:,1][Rmask].mean() BG_b_avg = BG[:,:,2][Rmask].mean() BG_r_std = BG[:,:,0][Rmask].std() BG_g_std = BG[:,:,1][Rmask].std() BG_b_std = BG[:,:,2][Rmask].std() f_r_avg = frame[:,:,0][Rmask].mean() f_g_avg = frame[:,:,1][Rmask].mean() f_b_avg = frame[:,:,2][Rmask].mean() f_r_std = frame[:,:,0][Rmask].std() f_g_std = frame[:,:,1][Rmask].std() f_b_std = frame[:,:,2][Rmask].std() fcal[:,:,0] = (frame[:,:,0]-f_r_avg)/f_r_std*BG_r_std+BG_r_avg fcal[:,:,1] = (frame[:,:,1]-f_g_avg)/f_g_std*BG_g_std+BG_g_avg fcal[:,:,2] = (frame[:,:,2]-f_b_avg)/f_b_std*BG_b_std+BG_b_avg dif = abs(fcal-BG) fg = ((dif[:,:,1]>20.)|(dif[:,:,2]>30.)) elif type == 3 : #truncation mean 1. if len(vid)>trun: if (vid_idx-round(trun/2))<0: if F_case == 1: BG = BG_old else: LB = 0 UB = trun-1 BG = array(vid[LB:UB+1]).mean(0) F_case = 1 elif len(vid)-vid_idx<=(trun-1): if B_case == 1: BG = BG_old else: LB = len(vid)-(trun-1) UB = len(vid) BG = array(vid[LB:UB+1]).mean(0) B_case = 1 else: if M_case == 1: BG = BG_old + array(vid[vid_idx+int(trun/2)])/trun\ - array(vid[vid_idx-int(trun/2)+1])/trun else: LB = vid_idx-int(trun/2)+1 UB = vid_idx+int(trun/2) #pdb.set_trace() BG = array(vid[LB:UB+1]).mean(0) M_case = 1 fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>25.0)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>25.0)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>25.0) else: print('select truncation is larger then the sequence....') BG = array(vid).mean(0) fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>30.0)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>30.0)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>30.0) elif type==4: #truncation mean 2. if len(vid)>trun: if len(vid)-vid_idx<=(trun-1): if B_case == 1: BG = BG_old else: LB = len(vid)-(trun-1) UB = len(vid) BG = array(vid[LB:UB+1]).mean(0) B_case = 1 else: if F_case == 1: BG = BG_old + array(vid[vid_idx+trun-1])/trun\ - array(vid[vid_idx-1])/trun else: LB = 0 UB = trun-1 BG = array(vid[LB:UB+1]).mean(0) F_case = 1 fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>30.0)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>30.0)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>30.0) else: print('select truncation is larger then the sequence....') BG = array(vid).mean(0) fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>30.0)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>30.0)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>30.0) elif type == 5: if (vid_idx-round(trun/2))<0: if F_case == 1: BG = BG_old else: LB = 0 UB = trun-1 BG = array(vid[LB:UB+1]).mean(0) F_case = 1 elif len(vid)-vid_idx<=(trun-1): if B_case == 1: BG = BG_old else: LB = len(vid)-(trun-1) UB = len(vid) BG = array(vid[LB:UB+1]).mean(0) B_case = 1 else: if M_case == 1: BG = BG_old + array(vid[vid_idx+int(trun/2)])/trun\ - array(vid[vid_idx-int(trun/2)+1])/trun else: LB = vid_idx-int(trun/2)+1 UB = vid_idx+int(trun/2) BG = array(vid[LB:UB+1]).mean(0) M_case = 1 fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>25.0)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>25.0)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>25.0) #fg = fg * ShadowRm(fg,frame,BG,5,frame.shape[0],frame.shape[1],20) elif type == 6: global buf,Tf N = 25 trun = N*2+1 ind =range(trun) ind.pop(trun/2) buf[-1] = vid[vid_idx+N+1] if len(vid)>trun: BG = np.abs(buf[ind]-buf[trun/2]).mean(3).mean(0) fg = (BG>40.)*Tf buf=np.roll(buf,-1,0) else: print('select truncation is larger then the sequence....') if maskon: fg = fg*mask*mask2 fgd = ndm.binary_dilation(fg,np.ones([2,2])) fgf = ndm.binary_fill_holes(fgd) right.set_data(mf(fgf,5)) plt.draw() if (type!=1)&(type!=5): BG_old = BG return fgf
def Fg_Extract(frame,type = 1,trun = 100): #extract foreground global BG_old global F_case global M_case global B_case if type ==1: # training BG mu[:] = alpha*frame + (1.0-alpha)*mu_old mu_old[:] = mu sig2[:] = alpha*(1.0*frame-mu)**2 + (1.0-alpha)*sig2_old sig2_old[:] = sig2 sig = sig2**0.5 lmcs = lmc*sig bmcs = bmc*sig sig_factor = 1 #pdb.set_trace() fg= (np.abs(1.0*frame-mu)[:,:,0]-sig_factor*sig[:,:,0]>0.0) +\ (np.abs(1.0*frame-mu)[:,:,1]-sig_factor*sig[:,:,1]>0.0) +\ (np.abs(1.0*frame-mu)[:,:,2]-sig_factor*sig[:,:,2]>0.0) elif type == 2: # avg total seq (need saved file) print('bg') BG = pickle.load(open("./BG/TLC0005(15000-16000).pkl","rb")) BG = cv2.resize(BG,(0,0),fx = scale,fy=scale) fg = (np.abs(1.0*frame[:,:,0]-BG[:,:,0])>50.)+\ (np.abs(1.0*frame[:,:,1]-BG[:,:,1])>50.)+\ (np.abs(1.0*frame[:,:,2]-BG[:,:,2])>50.) elif type == 2.5 : #avg total seq (need saved file) normalized image BG = pickle.load(open("./BG/TLC0005(15000-16000).pkl","rb")) BG = cv2.resize(BG,(0,0),fx = scale,fy=scale) fcal = np.zeros(BG.shape) #pdb.set_trace() BG_r_avg = BG[:,:,0][Rmask].mean() BG_g_avg = BG[:,:,1][Rmask].mean() BG_b_avg = BG[:,:,2][Rmask].mean() BG_r_std = BG[:,:,0][Rmask].std() BG_g_std = BG[:,:,1][Rmask].std() BG_b_std = BG[:,:,2][Rmask].std() f_r_avg = frame[:,:,0][Rmask].mean() f_g_avg = frame[:,:,1][Rmask].mean() f_b_avg = frame[:,:,2][Rmask].mean() f_r_std = frame[:,:,0][Rmask].std() f_g_std = frame[:,:,1][Rmask].std() f_b_std = frame[:,:,2][Rmask].std() fcal[:,:,0] = (frame[:,:,0]-f_r_avg)/f_r_std*BG_r_std+BG_r_avg fcal[:,:,1] = (frame[:,:,1]-f_g_avg)/f_g_std*BG_g_std+BG_g_avg fcal[:,:,2] = (frame[:,:,2]-f_b_avg)/f_b_std*BG_b_std+BG_b_avg dif = abs(fcal-BG) fg = ((dif[:,:,1]>50.)|(dif[:,:,2]>50.)) Tf = (frame[:,:,1]>100) & (frame[:,:,0]<100) Tf = ndm.binary_closing(Tf,structure=np.ones((4,4))) Tf = ~ndm.binary_fill_holes(Tf) df = (abs(1.0*vid[vid_idx-1][:,:,0]-1.0*vid[vid_idx][:,:,0])>50.)+\ (abs(1.0*vid[vid_idx-1][:,:,1]-1.0*vid[vid_idx][:,:,1])>50.)+\ (abs(1.0*vid[vid_idx-1][:,:,2]-1.0*vid[vid_idx][:,:,2])>50.) if maskon: fg = fg*mask*Tf*df#*mask2 #fgo = ndm.binary_opening(fg,np.ones([5,5])) fgo = ndm.binary_dilation(fg,np.ones([2,2])) fgf = ndm.binary_fill_holes(fgo) right.set_data(mf(fgf,5)) plt.draw() if (type!=1)&(type!=5): BG_old = BG return fgf
start = 15225 end = 15240 buf = double(vid[start-trun/2:start+trun/2+1]) ind = range(trun+1) ind.pop(trun/2) th =40 #build tree filter Tf = (vid[0:100,:,:,1].mean(0)>100) & (vid[0:100,:,:,0].mean(0)<100) Tf = ndm.binary_closing(Tf,structure=np.ones((4,4))) Tf = ~ndm.binary_fill_holes(Tf) for ii in range(start,end): print(ii) left.set_data(vid[ii][:,:,::-1]) #pdb.set_trace() BG[:] = np.abs(buf[ind]-buf[trun/2]).mean(3).mean(0)>40. #fg = np.abs(buf[ind].mean(3)-buf[trun/2].mean(2)).mean(0)>40. fgo = ndm.binary_opening(BG*Tf) fgf = ndm.binary_fill_holes(fgo) right.set_data(mf(fgf,5)) plt.draw() buf = np.roll(buf,-1,0) buf[-1] = vid[ii+trun/2+1]
# In[1]: import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf ####### Problem 1 # In[2]: img = mf((255 - nd.imread('images/ml.jpg')[::1,::2,::-1]).astype(float), (8, 2, 1)).clip(0,255).astype(np.uint8) ### Explanation: ### 1. nd.imread reaturns a 3D array ### 2. Then subsetting [::2, ::1, ::-1] inverses colors and skips every other column ### 3. 255 - ... converts to negative ### 4. .astype(float) ### 5. mf() applies median filter ### 6. .clip() clips ### 7. .astype(np.uint8) converts to uint nrow, ncol = img.shape[:2] ysize = 10. xsize = ysize * float(ncol)/float(nrow) fig1, ax1 = plt.subplots(num = 1, figsize = [xsize, ysize])
import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf img = mf(1.0*(255 - np.array([[e[2], e[1], e[0]] for e in nd.imread('images/ml.jpg').reshape(610560,3)[::2]]).\ reshape(954,320,3)),[8,2,1]).clip(0,255).astype(np.uint8) ysize = 10. xsize = ysize*float(img.shape[1])/float(img.shape[0]) fig5, ax5 = plt.subplots(num=5,figsize=[xsize,ysize]) fig5.subplots_adjust(0,0,1,1) fig5.canvas.set_window_title("modified mona lisa") ax5.axis('off') im5 = ax5.imshow(img) fig5.canvas.draw() plt.show()
import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf img_ml=mf(1.0*(255-nd.imread('images/ml.jpg')[::2,::2,::-1]),[8,2,1]).clip(0,255) fig1, ax1 = plt.subplots(num=1,figsize=(6,1.0*img_ml.shape[0]/img_ml.shape[1]*6)) fig1.subplots_adjust(0,0,1,1);ax1.grid('off') ax1.axis('off') fig1.canvas.set_window_title('modified Mona Lisa') im1 = ax1.imshow(img_ml.astype(np.uint8))
def med_filter(im, size = 10): from scipy.ndimage.filters import median_filter as mf import numpy as np return mf(im, size = size)
import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf # 1: read in and manipulate image img = mf( (255 - (nd.imread(os.path.join('images', 'city_image.jpg'))[::2][:, :, ::-1])), [8, 2, 1]).clip(0, 255).astype(np.uint8) # 2: display it ysize = 3. xsize = ysize * float(img.shape[1]) / float(img.shape[0]) fig, ax = plt.subplots(1, figsize=[xsize, ysize]) fig.subplots_adjust(0, 0, 1, 1) ax.axis("off") im = ax.imshow(img) fig.canvas.set_window_title('modified city image') fig.canvas.draw() plt.show()
def med_filter(im, size=10): from scipy.ndimage.filters import median_filter as mf import numpy as np return mf(im, size=size)
def res_lc_plot(): # -- read in the residential data lcs = [] for night in range(22): fopen = open(os.path.join(os.environ['DST_WRITE'],'res_lc_night_' + str(night).zfill(2) + '_2.pkl'),'rb') lcs.append(pkl.load(fopen)) fopen.close() # -- utilities tcks, htimes = time_ticks() # -- define fri/sat and all other days # we = [0,6,7,13,14,20,21] # wd = [1,2,3,4,5,8,9,10,11,12,15,16,17,18,19] we = [0,6,7,13,14,20,21] wd = [1,2,3,4,5,8,9,10,11,12,15,16,17,18,19] # -- get mean averaged lc tmax = min([len(i.mean(0)) for i in lcs if len(i.mean(0))>3000]) mnwd = np.zeros(tmax) mnwe = np.zeros(tmax) cnt = 0.0 for idy in wd: if idy==8: continue if len(lcs[idy].mean(0))>3000: mnwd += lcs[idy].mean(0)[:tmax] cnt += 1.0 mnwd /= cnt cnt = 0.0 for idy in we: if idy==21: continue if len(lcs[idy].mean(0))>3000: mnwe += lcs[idy].mean(0)[:tmax] cnt += 1.0 mnwe /= cnt plt.figure(1,figsize=[5,5]) plt.xticks(tcks,htimes,rotation=30) plt.ylabel('intensity [arb units]',size=15) plt.xlim([0,3600]) plt.grid(b=1) plt.plot(mnwd,'k') plt.plot(mnwe,'r') plt.savefig('../output/res_lc_mean.png',clobber=True) plt.close() # -- open the figure plt.figure(0,figsize=[15,5]) plt.subplots_adjust(0.05,0.1,0.95,0.95) plt.subplot(131) for idy in wd: # plt.plot(mf(lcs[idy][0]/lcs[idy][0,0],6)) # plt.plot(mf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6)) # cdf = np.cumsum(lcs[idy].mean(0)) # plt.plot(cdf/cdf[360]/(np.arange(cdf.size)/360.)) lc_sm = gf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6) norm = (lc_sm-lc_sm[-1]) # plt.plot(lc_sm/lc_sm[0]) plt.plot(norm/norm[0]) # plt.plot(gf((lc_sm-np.roll(lc_sm,1))[1:-1],360)) # plt.ylim([0.8,1.2]) # plt.ylim([0.6,1.4]) plt.ylim([-0.1,1.4]) plt.grid(b=1) plt.xticks(tcks,htimes,rotation=30) plt.xlim([0,3600]) plt.ylabel('intensity [arb units]',size=15) plt.subplot(132) for idy in we: # plt.plot(mf(lcs[idy][0]/lcs[idy][0,0],6)) # plt.plot(mf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6)) # cdf = np.cumsum(lcs[idy].mean(0)) # plt.plot(cdf/cdf[360]/(np.arange(cdf.size)/360.)) lc_sm = gf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6) norm = (lc_sm-lc_sm[-1]) # plt.plot(lc_sm/lc_sm[0]) plt.plot(norm/norm[0]) # plt.plot(gf((lc_sm-np.roll(lc_sm,1))[1:-1],360)) # plt.ylim([0.6,1.4]) # plt.ylim([0.8,1.2]) plt.ylim([-0.1,1.4]) plt.grid(b=1) plt.xticks(tcks,htimes,rotation=30) plt.xlim([0,3600]) plt.ylabel('intensity [arb units]',size=15) plt.subplot(133) for idy in wd: # plt.plot(mf(lcs[idy][0]/lcs[idy][0,0],6),'k') plt.plot(mf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6),'k') for idy in we: # plt.plot(mf(lcs[idy][0]/lcs[idy][0,0],6),'r') plt.plot(mf(lcs[idy].mean(0)/lcs[idy].mean(0)[0],6),'r') plt.ylim([0.6,1.4]) plt.grid(b=1) plt.xticks(tcks,htimes,rotation=30) plt.xlim([0,3600]) plt.ylabel('intensity [arb units]',size=15) plt.savefig('../output/res_lc_all.png',clobber=True) plt.close() return
import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf if __name__ == '__main__': dpath = 'images' fname = 'ml.jpg' infile = os.path.join(dpath,fname) #fancy image read line img_ml = np.uint8( mf( np.float64(255-nd.imread(infile)[::2,::2,::-1]), (8,2,1)) ) #display the image ysize = 9. xsize = ysize*float(img_ml.shape[1])/float(img_ml.shape[0]) plt.ion() fig, ax = plt.subplots(figsize=(xsize,ysize)) fig.subplots_adjust(0,0,1,1) fig.canvas.set_window_title('modified Mona Lisa') ax.axis('off') im = ax.imshow(img_ml) fig.canvas.draw() plt.show(block=True)
def plot_cube(cube, cmap='bone', clim=None, median_filter=False, figsize=10): """ An interactive visualization of the data cube. Parameters ---------- cube : HyperCube An instance of the HyperCube class to be shown. cmap : matplotlib color map, optional The matplotlib color map to use. clim : 2-element list, optional The limits of the color stretch. median_filter : float, optional Set the width of the median filter on the spectra. figsize : float, optional The horizontal width of the figure in inches. """ # -- set the flag to freeze the spectrum def toggle_hold(event): if event.button == 1 and event.inaxes == ax[0]: hold_spec[0] = not hold_spec[0] return # -- mouseover event updates the spectrum def show_spectrum(event): if hold_spec[0]: return if event.inaxes == ax[0]: cind = int(round(event.xdata)) rind = int(round(event.ydata)) mn = cube.data[:, rind, cind].mean() sd = cube.data[:, rind, cind].std() if not median_filter: lin[0].set_data(waves, cube.data[:, rind, cind]) else: lin[0].set_data(waves, mf(cube.data[:, rind, cind], median_filter)) ax[1].set_ylim([ min(-10, cube.data[:, rind, cind].min()), max(20, 1.2 * cube.data[:, rind, cind].max()) ]) pos_text.set_y(ax[1].get_ylim()[1]) pos_text.set_text('(row,col) = ({0:4},{1:4})'.format(rind, cind)) fig.canvas.draw() return # -- utilities waves = cube.wavelength * 1e-3 if not cube.indexing else np.arange( cube.nwav) xlab = 'wavelength [micron]' if not cube.indexing else 'index' arat = float(cube.nrow) / float(cube.ncol) rat = arat * 3. / 5. med = np.median(cube.img_L) sig = cube.img_L.std() scl = 0.2 if clim == None: clim = [ scl * max(med - 2 * sig, cube.img_L.min()), scl * min(med + 10 * sig, cube.img_L.max()) ] # -- initialize the figure fig = plt.figure(figsize=[figsize, figsize * rat]) fig.subplots_adjust(0, 0, 1, 1, 0, 0) ax = [] ax.append(fig.add_axes([0.1, 0.35, 0.85, 0.6])) ax.append(fig.add_axes([0.1, 0.1, 0.85, 0.2])) fig.set_facecolor('ivory') ax[0].axis('off') ax[1].set_ylim([-10, 20]) ax[1].grid(1, color='white', ls='-', lw=1.5) ax[1].set_axis_bgcolor('lightgray') ax[1].set_xlabel(xlab) ax[1].set_xlim([waves.min(), waves.max()]) ax[1].set_ylabel('intensity\n[arb units]') ax[1].set_axisbelow(True) # -- show the grayscale iamge ax[0].imshow(cube.img_L, clim=clim, cmap=cmap, aspect=0.6 / 0.85 * rat / arat) # -- plot the spectrum if not median_filter: lin = ax[1].plot(waves, cube.data[:, 0, 0], color='#E24A33', lw=1.5) else: lin = ax[1].plot(waves, mf(cube.data[:, 0, 0], median_filter), color='#E24A33', lw=1.5) # -- show the position of the spectrum pos_text = ax[1].text(ax[1].get_xlim()[1], ax[1].get_ylim()[1], '(row,col) = ({0:4},{1:4})'.format(0, 0), ha='right', va='bottom') # -- initialize hold flag and connect events hold_spec = [False] fig.canvas.mpl_connect('button_press_event', toggle_hold) fig.canvas.mpl_connect('motion_notify_event', show_spectrum) return