def paramChanged(param, changes): for param, changeType, newVal in changes: print("Handling name: {}, changeType: {}, newVal: {}".format(param.name, changeType, newVal)) name=param.name() if changeType=='activated': if name=="Capture Once": capture() if name=="Least-squares Fit": crp.updateFit() if name=="Record Background": main.setBG() if name=="Reset Crop": main.resetCrop() if name=="Show BG": pg.image(main.bg) elif name=='Acquire Continuous': global bCaptureContinuous bCaptureContinuous=newVal elif name=='full fit': crp.bDoFullFit=newVal elif name=='Subtract BG': main.bSubtractBG=newVal elif name=='Update Projections': main.bUpdateProjections=newVal elif name=='Auto fit': crp.bAutoFit=newVal elif name=='Averages': cam.Naves=newVal else: print("Somehow missed handling '{}'".format(name))
def simplePlot(): data = np.random.normal(size=1000) pg.plot(data, title="Simplest possible plotting example") data = np.random.normal(size=(500,500)) pg.image(data, title="Simplest possible image example") pg.QtGui.QApplication.exec_()
def reconstruct(self): self.recon.lbl.setText("Reconstruction is currently running") self.d= tomopy.xtomo_dataset(log='debug') self.reconelement=self.recon.combo.currentIndex() self.d.data=self.data[self.reconelement,:,:,:] self.d.data[self.d.data==inf]=0.01 self.d.data[np.isnan(self.d.data)]=0.01 ###TEMP if self.recon.reconvalue==0: self.d.data = (np.exp(-0.0001*self.d.data)).astype('float32') else: print "transmission" #self.d.center=128 ###TEMP self.d.center=self.p1[2] if self.recon.method.currentIndex()==0: self.d.dataset(self.d.data, theta=self.theta*np.pi/180) #self.d.optimize_center() self.d.mlem() elif self.recon.method.currentIndex()==1: self.d.dataset(self.d.data, theta=self.theta) #self.d.optimize_center() self.d.gridrec() elif self.recon.method.currentIndex()==2: self.d.dataset(self.d.data, theta=self.theta*np.pi/180) #self.d.optimize_center() self.d.art() print self.d.center pg.image(self.d.data_recon) self.recon.lbl.setText("Done") self.recon.save.setHidden(False)
def Image_Background(self): self.background=[] background = self.imageData[self.times<1] pg.image(np.mean(background[1:],axis=0), title='average background ') self.background = np.mean(background,axis=0) return
def test_mask_data(): # create Gaussian image: img_size = 500 x = np.arange(img_size) y = np.arange(img_size) X, Y = np.meshgrid(x, y) center_x = img_size / 2 center_y = img_size / 2 width = 30000.0 intensity = 5000.0 img_data = intensity * \ np.exp(-((X - center_x) ** 2 + (Y - center_y) ** 2) / width) mask_data = MaskData(img_data.shape) # test the undo and redo commands mask_data.mask_above_threshold(img_data, 4000) mask_data.mask_below_threshold(img_data, 230) mask_data.undo() mask_data.undo() mask_data.redo() mask_data.redo() mask_data.undo() mask_data.mask_rect(200, 400, 400, 100) mask_data.mask_QGraphicsRectItem( QtGui.QGraphicsRectItem(100, 10, 100, 100)) mask_data.undo() mask_data.mask_polygon( np.array([0, 100, 150, 100, 0]), np.array([0, 0, 50, 100, 100])) mask_data.mask_QGraphicsPolygonItem( QtGui.QGraphicsEllipseItem(350, 350, 20, 20)) # performing the plot pg.image(mask_data.get_img())
def Image_Background(self): self.background=[] background = self.imageData[:50] print 'shape of background:', np.shape(background) pg.image(np.mean(background[10:49],axis=0), title='average background ') self.background = np.mean(background,axis=0) return
def updateAvgStdImage(self): """ update the reference image types and then make sure display agrees. """ self.aveImage = np.mean(self.imageData, axis=0) self.stdImage = np.std(self.imageData, axis=0) pg.image(self.aveImage, title='mean after registration') pg.image(self.stdImage, title='std after registration') return
def simplePlot(): data = np.random.normal(size=1000) pg.plot(data, title="Simplest possible plotting example") data = np.random.normal(size=(500,500)) pg.image(data, title="Simplest possible image example") ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
def load_file(self, repnum): global options global basepath if repnum < 10: upf = basepath + options.upfile + "/00" + str(repnum) + "/Camera/frames.ma" else: upf = basepath + options.upfile + "/0" + str(repnum) + "/Camera/frames.ma" # upf = basepath + options.upfile + '/Camera/frames.ma' im = [] self.imageData = [] print "loading data from ", upf try: im = MetaArray(file=upf, subset=(slice(0, 2), slice(64, 128), slice(64, 128))) except: print "Error loading upfile: %s\n" % upf return print "data loaded" self.times = im.axisValues("Time").astype("float32") self.imageData = im.view(np.ndarray).astype("float32") pg.image(self.imageData, title=str(repnum)) # self.ProcessImage() print "imageData shape:", np.shape(self.imageData) # self.imageData = self.imageData[np.where(self.times>1)] back = self.imageData[np.where(np.logical_and(self.times > 2, self.times < 3))] print "size of back", np.shape(back) self.background = np.mean(back[5:], axis=0) # self.times= self.times-1 # interval1=self.imageData[np.where(np.logical_and(self.times>=1, self.times<=1.25))] # print 'interval1 shape:', np.shape(interval1) # interval2=self.imageData[np.where(np.logical_and(self.times>=2, self.times<=2.25))] # print 'interval2 shape:', np.shape(interval2) # interval3=self.imageData[np.where(np.logical_and(self.times>=3, self.times<=3.25))] # print 'interval3 shape:', np.shape(interval3) # interval4=self.imageData[np.where(np.logical_and(self.times>=4, self.times<=4.25))] # print 'interval4 shape:', np.shape(interval4) # interval5=self.imageData[np.where(np.logical_and(self.times>=5, self.times<=5.25))] # print 'interval5 shape:', np.shape(interval5) # back=self.imageData[np.where(np.logical_and(self.times>0, self.times<1))] # background=np.mean(back,axis=0) # meanimg=np.mean(self.imageData, axis=0) # pg.image(meanimg, title='mean image') # self.imageData = ((interval1+interval2+interval3+interval4+interval5)/5-background)/background print "imageData shape:", np.shape(self.imageData) # pg.image(background, title='background') # self.imageData=scipy.ndimage.gaussian_filter(self.imageData, sigma=[1,3,3], order=0,mode='reflect',truncate=4.0) return
def test_nan_image(): img = np.ones((10,10)) img[0,0] = np.nan v = pg.image(img) v.imageItem.getHistogram() app.processEvents() v.window().close()
def getErr(self, p=None, bShow=False): if p is None: p=self.getP() guess=self.getFramePar(p) #figure(2) #guess=gauss(X, [sqrt(p[0]), p[1], p[3]])*gauss(Y, [sqrt(p[0]), p[2], p[3]]) err = ((guess-self.targetFrame)**2).sum() if bShow: pg.image(guess, title='guess') pg.image(self.targetFrame, title='frame') #imshow(guess) #draw() #print("Params: {0}".format(p)) if err==0: err=1e-12 err=np.log(err) print("err, height: {}, {}".format(err, p[0])) return err;
def test_dividebyzero(): import pyqtgraph as pg im = pg.image(pg.np.random.normal(size=(100,100))) im.imageItem.setAutoDownsample(True) im.view.setRange(xRange=[-5+25, 5e+25],yRange=[-5e+25, 5e+25]) app.processEvents() QtTest.QTest.qWait(1000) # must manually call im.imageItem.render here or the exception # will only exist on the Qt event loop im.imageItem.render()
def _CompareGoodnessCorrelation(self): locs = self._postProcessedLocs[:] distXYs = np.array([loc.distXY for loc in locs]) prop = {} prop["lsError"] = np.array([loc.lsError for loc in locs]) prop["photons"] = np.array([loc.photons for loc in locs]).ravel() prop["amp"] = np.array([loc.amp for loc in locs]).ravel() prop["minFitDistXY"] = np.array([loc.minFitDistXY for loc in locs]).ravel() prop["sigmaX"] = np.array([loc.sigmaX for loc in locs]).ravel() prop["sigmaY"] = np.array([loc.sigmaY for loc in locs]).ravel() prop["offset"] = np.array([loc.offset for loc in locs]).ravel() prop["distXY"] = np.array([loc.distXY for loc in locs]).ravel() prop["fitStdAmp"] = np.array([loc.fitStdAmp for loc in locs]).ravel() prop["fitStdX0"] = np.array([loc.fitStdX0 for loc in locs]).ravel() prop["fitStdY0"] = np.array([loc.fitStdY0 for loc in locs]).ravel() prop["fitStdZ0"] = np.array([loc.fitStdZ0 for loc in locs]).ravel() prop["fitStdOffset"] = np.array([loc.fitStdOffset for loc in locs]).ravel() prop["pixels"] = np.array([float(loc.nrOfPixels) for loc in locs]).ravel() rValues = [] for k, v in prop.iteritems(): slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(distXYs, v) # print k, slope, intercept, "R2", r_value ** 2.0 func = lambda d: slope * d + intercept rValues.append((k, slope, r_value ** 2.0)) plt = pg.PlotItem() imv = pg.image(view = plt) plt.plot(distXYs, v, pen = None, symbol = "x", symbolSize = 2.0) plt.plot(distXYs, func(distXYs), pen = "r") plt.addLine(y = np.mean(v)) plt.addLine(y = np.mean(v) + np.std(v)) plt.addLine(y = np.mean(v) - np.std(v)) plt.setLabels(bottom = ("distXY", "m"), left = (k)) hist, xedges, yedges = np.histogram2d(distXYs, v, bins = 100) xStep, yStep = xedges[1] - xedges[0], yedges[1] - yedges[0] transform = QtGui.QTransform() transform.translate(xedges[0], yedges[0]) transform.scale(xStep, yStep) imv.view.invertY(False) imv.view.setAspectLocked(False) imv.setImage(hist, transform = transform) # plt.setRange(xRange = [0.0, 20e-9]) print print "Sorted R2" rValues.sort(key = lambda x:-x[-1]) print "\n".join(["%s: slope %f, R2 %.3f" % (k, s, r2) for k, s, r2 in rValues])
def mkData(): with pg.BusyCursor(): global data, cache, ui frames = ui.framesSpin.value() width = ui.widthSpin.value() height = ui.heightSpin.value() dtype = (ui.dtypeCombo.currentText(), ui.rgbCheck.isChecked(), frames, width, height) if dtype not in cache: if dtype[0] == 'uint8': dt = np.uint8 loc = 128 scale = 64 mx = 255 elif dtype[0] == 'uint16': dt = np.uint16 loc = 4096 scale = 1024 mx = 2**16 elif dtype[0] == 'float': dt = np.float loc = 1.0 scale = 0.1 if ui.rgbCheck.isChecked(): data = np.random.normal(size=(frames,width,height,3), loc=loc, scale=scale) data = pg.gaussianFilter(data, (0, 6, 6, 0)) else: data = np.random.normal(size=(frames,width,height), loc=loc, scale=scale) data = pg.gaussianFilter(data, (0, 6, 6)) pg.image(data) if dtype[0] != 'float': data = np.clip(data, 0, mx) data = data.astype(dt) cache = {dtype: data} # clear to save memory (but keep one to prevent unnecessary regeneration) data = cache[dtype] updateLUT() updateSize()
def badpix_from_darkcal(filename="", qtmainwin=None): # Use dialog_pickfile() if no filename is provided if filename is "": filename = cfel_file.dialog_pickfile(filter='*.h5', qtmainwin=qtmainwin) if filename is "": return # Determine what type of detector we are using # CsPad only for now - make fancy later (or use a selection box) detector = 'cspad' # Call routine for appropriate detector system if detector == 'cspad': mask = cfel_cspad.badpix_from_darkcal(filename) # Display mask (pyqtgraph.show) temp = mask.astype(int) pyqtgraph.image(temp, levels=(0,1)) #pg.imageView.ui.menuBtn.hide() #pg.imageView.ui.roiBtn.hide() # Save mask outfile = cfel_file.dialog_pickfile(write=True, path='../calib/mask', filter='*.h5', qtmainwin=qtmainwin) if outfile is not '': print("Saving mask: ", outfile) cfel_file.write_h5(mask, outfile, field='data/data')
def in_vs_out_widget(A, B, f = None, title = ''): if (A is None) and (B is None) : return None import pyqtgraph as pg A_in_out_plots = pg.image(title = title) print title A_in_out = hstack_if_not_None(A, B) if f is not None : A_in_out = f(A_in_out) if len(A_in_out.shape) == 2 : A_in_out_plots.setImage(A_in_out.T) elif len(A_in_out.shape) == 3 : A_in_out_plots.setImage(A_in_out) return A_in_out_plots
def dphaseReshape(self, data): altdphase = data for i in range(altdphase.shape[0]): for j in range(altdphase.shape[1]): #for k in range(dphase.shape[2]): if altdphase[i,j]<-4*np.pi/5 or altdphase[i,j]>4*np.pi/5: altdphase[i,j] = 10 elif altdphase[i,j]<-2*np.pi/5: altdphase[i,j] = 20 elif altdphase[i,j]<0: altdphase[i,j] = 30 elif altdphase[i,j]<2*np.pi/5: altdphase[i,j] = 40 else: altdphase[i,j] = 50 self.redphase = pg.image(altdphase, title="transformed 2X Phi map", levels=(10, 50)) return
def parse_and_go(self, argsin = None): global period global binsize parser=OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar='FILE', help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar='FILE', help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar='FILE', help="Use directory for data") parser.add_option("-t", "--test", dest="test", action='store_true', help="Test mode to check calculations", default=False) parser.add_option("-p", '--period', dest = "period", default=4.25, type="float", help = "Stimulus cycle period") parser.add_option("-c", '--cycles', dest = "cycles", default=0, type="int", help = "# cycles to analyze") parser.add_option("-b", '--binning', dest = "binsize", default=0, type="int", help = "bin reduction x,y") parser.add_option("-g", '--gfilter', dest = "gfilt", default=0, type="float", help = "gaussian filter width") parser.add_option("-f", '--fdict', dest = "fdict", default=0, type="int", help = "Use dictionary entry") if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() if options.test is True: print "Running Test Sample" period = 8.0 # period and frame sample rate can be different framerate = 8.0 nper = 1 d = 10.0*numpy.random.normal(size=(2500,128,128)).astype('float32') ds = d.shape self.nFrames = d.shape[0] self.nPhases = 10 maxdel = 50 self.phasex = [] self.phasey = [] for i in range(0,self.nPhases): dx = i*ds[1]/self.nPhases # each phase is assigned to a region baseline = 0.0 self.resp = numpy.zeros((self.nFrames,)) phaseDelay = 0.25*period+period*(float(i)/self.nPhases) # phase delay for this region from 0 to nearly the stimulus repeat period # print '********phase delay: ', phaseDelay for j in range(0, nper): # for each period tdelay = (float(j) * period) + phaseDelay # time to phase delay point idelay = int(numpy.floor(tdelay*framerate)) # convert to frame position in frame space # print ' tdel: ', tdelay, ' idel: ', idelay # if idelay < self.nFrames-maxdel: # self.resp[idelay:idelay+maxdel] = (i+1)*numpy.exp(-numpy.linspace(0, 2, maxdel)) # marks amplitudes as well self.resp = 1000.0*numpy.sin( numpy.linspace(0, 2.0*numpy.pi*self.nFrames/(period*framerate), self.nFrames)+i*numpy.pi/8.0 - numpy.pi/2.0) d[:, dx:dx+int(ds[1]/self.nPhases), 5:int(ds[2]/2)] += self.resp[:, numpy.newaxis, numpy.newaxis] self.phasex.append( (2+(dx+int(ds[1]/self.nPhases))/2)) self.phasey.append((6+int(ds[2]/2)/2)) # make the signal equivalent of digitized one (baseline 3000, signal at 1e-4 of baseline) d = (d*3000.0*1e-4)+3000.0 # scale and offset to match data scaling coming in self.imageData = d.astype('int16') # reduce to a 16-bit map to match camera data type self.times = numpy.arange(0, self.nFrames/framerate, 1.0/framerate) print "Test Image Created" getout2 = fac_lift(self.imageData, self.times) self.imageData=getout2 self.Analysis_FourierMap_TFR(period=period, target = 1, mode=1, bins=binsize) print "Completed Analysis FourierMap" self.plotmaps_pg(mode = 2, gfilter = 0) print "Completed plot maps" if options.period is not None: measuredPeriod = options.period if options.cycles is not None: self.nCycles = options.cycles if options.binsize is not None: binsize = options.binsize if options.gfilt is not None: gfilt = options.gfilt print 'DB keys', DB.keys() if options.fdict is not None: if options.fdict in DB.keys(): # populate options options.upfile = DB[options.fdict][0] options.downfile = DB[options.fdict][1] options.period = DB[options.fdict][4] else: print "File %d NOT in DBase\n" % options.fdict return if options.directory is not None: self.directory = options.directory if options.upfile is not None: self.upfile = options.upfile target = 1 if options.downfile is not None: self.downfile = options.downfile target = 2 target = 0 videoupf = None videodwnf = None audioupf = None audiodwnf = None if options.upfile is not None: videoupf = videobasepath + options.upfile + '.ma' audioupf = audiobasepath + options.upfile + '/DaqDevice.ma' if options.downfile is not None: videodwnf = videobasepath + options.downfile + '.ma' audiodwnf = audiobasepath + options.downfile + '/DaqDevice.ma' # indexFile = configfile.readConfigFile(basepath+'.index') # time = indexFile.__getitem__('video_019.ma')[u'__timestamp__'] #indexFile = configfile.readConfigFile(basepath+'.index') #print 'indexfile', indexfile for file in (videoupf, videodwnf): #if options.upfile is not None and options.downfile is not None: if file is None: break im=[] self.imageData = [] print "loading data from ", file try: im = MetaArray(file = file, subset=(slice(0,2), slice(64,128), slice(64,128))) except: print "Error loading upfile: %s\n" % file return print "data loaded" target = target + 1 # dir = acq4.util.DataManager.getHandle(basepath) # time = dir.info()['__timestamp__'] # print 'time:', time #print 'im:', im # dir(im) rawtimes=[] rawimageData=[] rawtimes = im.axisValues('Time').astype('float32') # print 'time', rawtimes rawimageData = im.view(np.ndarray).astype('float32') # print 'shape of ra image data:', rawimageData.shape ## videobasepath = /......./2016.10.08_000/Intrinsic_Mapping/video_' ## indexFile = configFile.readConfigFile('/...../2016.10.08_000/Intrinsic_Mapping/.index') -> a dictionary # dir = acq4.util.DataManager.getHandle(videoupf) # time = dir.info()['__timestamp__'] # #timestampup = timestamp[options.fdict][0] # audioupstamp = timestamp[options.fdict][1] # #timestampdown = timestamp[options.fdict][2] # audiodownstamp = timestamp[options.fdict][3] # #print 'optioins.dict', options.fdict[0] #reads the timestamps from the files indexFile = configfile.readConfigFile(basepath+'.index') timestampup = indexFile.__getitem__('video_'+DB[options.fdict][0]+'.ma')[u'__timestamp__'] timestampdown = indexFile.__getitem__('video_'+DB[options.fdict][1]+'.ma')[u'__timestamp__'] audioupindex = configfile.readConfigFile(audiobasepath+DB[options.fdict][0]+'/.index') # audioupstamp = audioupindex.__getitem__(u'.')[u'__timestamp__'] audioupstamp = audioupindex.__getitem__('DaqDevice.ma')[u'__timestamp__'] - 13.5 audiodownindex = configfile.readConfigFile(audiobasepath+DB[options.fdict][1]+'/.index') #audiodownstamp = audiodownindex.__getitem__(u'.')[u'__timestamp__'] audiodownstamp = audiodownindex.__getitem__('DaqDevice.ma')[u'__timestamp__'] -13.5 diffup = audioupstamp - timestampup diffdown = audiodownstamp - timestampdown if file is videoupf: audio = MetaArray(file = audioupf, subset=(slice(0,2), slice(64,128), slice(64,128))) audiotime = audio.axisValues('Time').astype('float32') audiomin = np.min(audiotime) + diffup audiomax = np.max(audiotime) + diffup elif file is videodwnf: audio = MetaArray(file = audiodwnf, subset=(slice(0,2), slice(64,128), slice(64,128))) audiotime = audio.axisValues('Time').astype('float32') audiomin = np.min(audiotime) + diffdown audiomax = np.max(audiotime) + diffdown else: print 'ERROR! Unable to load audio file' print 'audiomin', audiomin print 'audiomax', audiomax adjustedtime = rawtimes[np.logical_and(rawtimes <= audiomax+4, rawtimes >= audiomin)] adjustedimagedata = rawimageData[np.logical_and(rawtimes <= audiomax+4, rawtimes >= audiomin)] # print 'adjtime', adjustedtime self.times = [x-np.min(adjustedtime) for x in adjustedtime] self.imageData = adjustedimagedata background = rawimageData[5:25] background = np.mean(background,axis=0) print 'dimensions of background', np.shape(background) pg.image(background, title='mean background') subtracted = np.zeros(np.shape(self.imageData), float) for i in range(self.imageData.shape[0]): subtracted[i,:,:] = (self.imageData[i,:,:]-background) subtracted=subtracted/subtracted.mean() self.imageData = subtracted #print 'self.times:', self.times # print 'length of self.times', np.shape(self.times) # print 'shape of image data', np.shape(self.imageData) #analyze a quarter of the image #xcut = (self.imageData.shape[1]+1)/8 #ycut = (self.imageData.shape[2]+1)/8 #self.imageData=self.imageData[:,3*xcut-1:7*xcut-1,ycut-1:7*ycut-1] im=[] if file is videoupf: upflag = 1 else: upflag = 0 #print 'target:', target measuredPeriod=4.25 #self.subtract_Background(diffup=diffup) self.Analysis_FourierMap(period=measuredPeriod, target = target, bins=binsize, up=upflag) print 'target:', target if target > 0: self.plotmaps_pg(mode = 1, target = target, gfilter = gfilt) return
yd = yd[w] data = data[w] xi, yi = np.array(np.meshgrid(xbins, ybins, indexing='ij')) zi = xi * 0 zi[xd, yd] = data return zi prefix = "data/ISCCP.DX.0.GOE-7.1991.01.01." times = np.arange(0, 22, 3) * 100 xbins = np.arange(501) ybins = np.arange(501) zi = np.zeros((len(times), 501, 501)) for i in np.arange(len(times)): print "Time # {}".format(times[i]) filename = "{:s}{:04d}.AES".format(prefix, times[i]) stdat = pydx.dxread(filename) irads = np.array([o.irad for o in stdat.dxs1s]) zi[i, :, :] = pos2Grid(stdat.x, stdat.y, irads, xbins=xbins, ybins=ybins) zi = zi[:, :, ::-1] #3d image plots as time series, use scroll bar to cycle through images pg.image(zi) #1 day average of cloud cover zavg = np.average(zi, axis=0) pg.image(zavg)
import pyqtgraph as pg import sys, os from IPython import embed pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') data_path = sys.argv[1] ########################### PS or ACF visualization ##################### if os.stat(data_path).st_size < 10000000: # Checking file size data = np.load(data_path) data_title = data_path if data.max() > 1e12: data = data / 1e7 data_title = 'Data / 1e7' imv = pg.image(data, title = data_title) imv.ui.normBtn.hide() # imv.roi.setPen(pen={'width': 1.3}) # imv.roiCurve.setPen(pen={'color': 'r'}) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_() #### To save image if raw_input('Do you want to save image? y/[n]: ') == 'y': data_min = input('Enter min value: ') data_max = input('Enter max value: ') data = np.rot90(data)
def plot_movie(self): """Use pyqtgraph to make a movie quickly.""" pg.image(self.cells_t) QtGui.QApplication.instance().exec_()
def computeParameters(self, dt_audio=1/80000, dt_video=1/4000, debug=False): """Compute parameters from GAW :param dt_audio: audio sampling time in seconds, defaults to 1/80000 :type dt_audio: float, optional :param dt_video: video sampling time in seconds, defaults to 1/4000 :type dt_video: float, optional :param debug: shows debugging information and plots, defaults to False :type debug: bool, optional """ # Convert raw segmentations to binary masks seg = np.asarray(self.segmentations).round().astype(np.bool) # Predict midline from segmentation M = Midline(seg) M.predict() # Use midline for left and right GAW gaws = M.side() left_gaw = gaws[..., 0] right_gaw = gaws[..., 1] # Compute and show values gaw = GAW(seg.sum((1,2)), use_filtered_signal=False, use_hanning=False, dt=dt_video) gaw.setLeftRightGAW(left_gaw, right_gaw) params_GAW = gaw.computeParameters() # Create summary table for parameters self.t = Table(params_GAW, title="GAW parameters") self.t.show() if debug: # Show complete segmentation with midline im = pg.image(seg.transpose(0, 2, 1), title="Segmentation with midline") line = pg.LineSegmentROI([M.coordinates[0, :2], M.coordinates[0, 2:],], pen="y") im.getView().addItem(line) # Show complete GAW plot with detected cycles gaw_plot = pg.plot(gaw.t, gaw.raw_signal, title="GAW with cycles") cs = [(241, 196, 15), (231, 76, 60)] i = 0 for o, c in zip(gaw.opening, gaw.closing): i1 = pg.PlotCurveItem(gaw.t[o:c], np.zeros_like(gaw.t[o:c])) i2 = pg.PlotCurveItem(gaw.t[o:c], gaw.raw_signal[o:c]) between = pg.FillBetweenItem(i1, i2, brush=cs[i % len(cs)]) gaw_plot.getPlotItem().addItem(between) i += 1 # Show left and right gaw LR_plot = pg.plot(title="Left and right GAW") LR_plot.plot(gaw.t, left_gaw) LR_plot.plot(gaw.t, -right_gaw) # Compute and show phonovibrogram pvg = M.pvg() pg.image(pvg, title="Phonovibrogram") # If audio data is available if type(self.synced_audio) != type(None): if debug: pg.plot(self.synced_audio, title="Synchronized audio") a = Audio(self.synced_audio, dt=dt_audio) params_Audio = a.computeParameters() self.t2 = Table(params_Audio, title="Audio parameters") self.t2.show() else: params_Audio = None return dict(GAW=params_GAW, Audio=params_Audio)
yd = np.digitize(y, ybins) yd -= 1 yd = yd[::-1] #reverse order (w, ) = np.where((xd != 0) & (yd != 0)) xd = xd[w] yd = yd[w] irads = irads[w] vrads = vrads[w] nodays = nodays[w] bxshors = bxshors[w] vcslogs = vcslogs[w] xi, yi = np.array(np.meshgrid(xbins, ybins, indexing='ij')) IRADS = np.zeros(xi.shape) BXSHORS = np.zeros(xi.shape) NODAYS = np.zeros(xi.shape) VRADS = np.zeros(xi.shape) VCSLOGS = np.zeros(xi.shape) IRADS[xd, yd] = irads #IR radiance (day and night) BXSHORS[xd, yd] = bxshors #shoreline NODAYS[xd, yd] = nodays #night time VRADS[xd, yd] = vrads VCSLOGS[xd, yd] = vcslogs pg.image(IRADS, title="IR Radiance") pg.image(BXSHORS, title="Shorelines") pg.image(NODAYS, title="Night time") pg.image(VRADS, title="Visible Radiance") pg.image(VCSLOGS, title="Cloudiness")
phaseMaps = np.zeros_like(phaseMapsOriginal) for i in range(0, 17): phaseMaps[i, :, :] = unwrap_phase(phaseMapsOriginal[i, :, :], seed=100) phaseMapsCropped = phaseMaps[0:17, 49:113, 50:114] MMapsCropped = MMaps[0:17, 49:113, 50:114] # #pg.image(MMapsCropped, title='phase') # phaseMapsCropped_recentered_QA_motion = np.zeros_like(phaseMapsCropped) for i, pmc in enumerate(phaseMapsCropped): phaseMapsCropped_recentered_QA_motion[i] = pmc - np.average(pmc[18:22, 30:34]) pg.image(phaseMapsCropped_recentered_QA_motion) # #%% completed_images = [] original_images = [] phaseMapsCroppedTest = phaseMapsCropped_recentered_QA_motion OldRange = (np.max(phaseMapsCroppedTest) - np.min(phaseMapsCroppedTest)) NewRange = (2**8 - 1) - 0 for filename in sorted(glob.glob( r"C:\Users\plettlk\DCGAN_Image_Completion\120120\8bit_QA_test_30W_heating_w_motion\*.png" ), key=numericalSort): im = cv2.imread(filename, -1) im_ = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
random_state=42) num_comp = 50 print "Extracting the top %d eigen_images from %d training images" % ( num_comp, num_features) t0 = time() svd = TruncatedSVD(n_components=num_comp) svd.fit(X_train) # pca = RandomizedPCA(n_components = num_comp, whiten=True).fit(X_train) print "done in %0.3fs" % (time() - t0) eigen_images = svd.components_.reshape( (num_comp, img_shape[0], img_shape[1])) pg.image(eigen_images) print "Projecting the input data on the eigen_images orthonormal basis" t0 = time() X_train_pca = svd.transform(X_train) X_test_pca = svd.transform(X_test) print "done in %0.3fs" % (time() - t0) print "Fitting the classifier to the training set" t0 = time() # param_grid = { # 'C': [5,10,50,100,500], # 'gamma': [1e-8,5e-8,1e-7,5e-7], # }
phaseMaps[i,:,:] = unwrap_phase(phaseMaps2[i,:,:], seed=100) phaseMapsCropped2 = phaseMaps[0:709, 42:106, 39:103] phaseMaps3 = sonalleveNativeData3[:,:,0,0,0,1,:].swapaxes(0,2) MMaps3 = sonalleveNativeData3[:,:,0,0,0,0,:].swapaxes(0,2) phaseMaps=np.zeros_like(phaseMaps3) for i in range(0,771): phaseMaps[i,:,:] = unwrap_phase(phaseMaps3[i,:,:], seed=100) phaseMapsCropped3 = phaseMaps[0:771, 42:106, 39:103] phaseMapsCropped = np.vstack((phaseMapsCropped1, phaseMapsCropped2, phaseMapsCropped3)) phaseMapsCropped_recentered_tofu = np.zeros_like(phaseMapsCropped) for i,pmc in enumerate(phaseMapsCropped): phaseMapsCropped_recentered_tofu[i] = pmc-np.average(pmc[30:34,30:34]) pg.image(phaseMapsCropped_recentered_tofu) #%% completed_images = [] original_images = [] phaseMapsCroppedTest = phaseMapsCropped_recentered_tofu[100::100, :,:] #every 100th image for new test set OldRange = (np.max(phaseMapsCroppedTest) - np.min(phaseMapsCroppedTest)) NewRange = (2**8-1) - 0 ''' importing images ''' for filename in sorted(glob.glob(r"C:\Users\plettlk\DCGAN_Image_Completion\outputImages\completed\completed-8bit-tofu-50epochs-baseline\completed\*.png"), key=numericalSort): im=cv2.imread(filename, -1) im_ = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) completed_images.append(im_) completed_images_array_50 = np.array(completed_images)
MMaps = sonalleveNativeData[:, :, 0, 0, 0, 0, :].swapaxes(0, 2) phaseMaps = np.zeros_like(phaseMapsOriginal) # # for i in range(9, 26): phaseMaps[i, :, :] = unwrap_phase(phaseMapsOriginal[i, :, :], seed=100) phaseMapsCropped = phaseMaps[9:26, 42:106, 39:103] phaseMapsCropped_recentered_tofu_heated = np.zeros_like(phaseMapsCropped) for i, pmc in enumerate(phaseMapsCropped): phaseMapsCropped_recentered_tofu_heated[i] = pmc - np.average(pmc[30:34, 30:34]) pg.image(phaseMapsCropped_recentered_tofu_heated) alpha = -10.3e-9 gamma = 0.267513e9 B0 = 3 echoTime = 19.5e-3 completed_images = [] original_images = [] phaseMapsCroppedTest = phaseMapsCropped_recentered_tofu_heated OldRange = (np.max(phaseMapsCroppedTest) - np.min(phaseMapsCroppedTest)) NewRange = (2**16 - 1) - 0 for filename in sorted(glob.glob( r"C:\Users\plettlk\DCGAN_Image_Completion\111219\16bit_tofu_test_set_recentered_heated\*.png"
def test_tomoworkflow(): read = read_APS2BM() read.path.value = '/Users/hari/test.hdf' read.sino.value = (1050, 1051) norm = Normalize() read.arr.connect(norm.arr) read.flat.connect(norm.flats) read.dark.connect(norm.darks) outliers = RemoveOutlier() norm.normalized.connect(outliers.arr) outliers.dif.value = 500 outliers.size.value = 5 # maximum = ArrayMax() # outliers.corrected.connect(maximum.arr) # maximum.floor.value = 1e-16 # neglog = MinusLog() # maximum.out.connect(neglog.arr) # phase = RetrievePhase() # maximum.out.connect(phase.arr) # phase.pixel_size.value=6.5e-5 # phase.dist.value=3 # phase.energy.value=27 stripe = RemoveStripeFw() outliers.corrected.connect(stripe.tomo) stripe.level.value = 8 stripe.wname.value = 'db5' stripe.sigma.value = 4 stripe.pad.value = True padding = Pad() stripe.corrected.connect(padding.arr) padding.axis.value = 2 padding.npad.value = 448 padding.mode.value = 'edge' # angles = Angles() # angles.nang.value=0 # angles.ang1.value=90 # angles.ang2.value=180 gridrec = Recon() padding.padded.connect(gridrec.tomo) read.angles.connect(gridrec.theta) gridrec.filter_name.value = 'butterworth' gridrec.algorithm.value = 'gridrec' gridrec.center.value = np.array([1295 + 448]) # 1295 gridrec.filter_par.value = np.array([0.2, 2]) # gridrec.sinogram_order.value = True crop = Crop() gridrec.reconstructed.connect(crop.arr) crop.p11.value = 448 crop.p22.value = 448 crop.p12.value = 448 crop.p21.value = 448 crop.axis.value = 0 divide = ArrayDivide() circularmask = CircMask() crop.croppedarr.connect(circularmask.arr) circularmask.val.value = 0 circularmask.axis.value = 0 circularmask.ratio.value = 1 writetiff = WriteTiffStack() workflow = Workflow('Tomography') for process in [read, norm, outliers, # maximum, # neglog, # phase, stripe, padding, # angles, gridrec, crop, # divide, circularmask, # writetiff ]: workflow.addProcess(process) dsk = DaskExecutor() result = dsk.execute(workflow) print(result) import pyqtgraph as pg pg.image(result[0]['normalized'].value.squeeze()) from qtpy.QtWidgets import QApplication app = QApplication([]) app.exec_()
sino_center = im_size / 2 #1280 num_angles = 512 #1024 gpu_device = 2 oversamp_factor = 1.5 num_iter = 150 p = 1.2 sigma = .075 obj = tomopy.shepp3d((num_slice, im_size, im_size)) # Generate an object. theta = tomopy.angles(num_angles) # Generate uniformly spaced tilt angles. ### Comparing to tomopy tomo = tomopy.project(obj, theta) proj_dim = tomo.shape[2] tomo = tomo[:, :, proj_dim / 2 - im_size / 2:proj_dim / 2 + im_size / 2] pg.image(tomo) pg.QtGui.QApplication.exec_() ################## GPU MBIR ###################### input_params = {} input_params['gpu_device'] = gpu_device input_params['oversamp_factor'] = oversamp_factor input_params['num_iter'] = num_iter input_params['p'] = p input_params['smoothness'] = sigma t = time.time() #rec_sirt = gpuSIRT(tomo,theta,sino_center,input_params); rec_mbir = gpuMBIR(tomo, theta, sino_center, input_params) elapsed_time = (time.time() - t) print('Time for reconstucting using GPU-MBIR of %d slices with %d iter : %f' % (num_slice, num_iter, elapsed_time)) pg.image(rec_mbir)
fy = np.fft.rfft(sw)[1:max_range_index+1] fy = fy/bit_depth fy = 20*np.log(abs(fy)) fy = np.clip(fy, -40, float('inf')) m = max(m,max(fy)) im[:,e] = np.array(fy) if 1: f = sample_rate/2.0 xx, yy = np.meshgrid( np.linspace(0,decimate_sweeps*2*lines*sw_len/sample_rate, im.shape[1]), #np.linspace(0, im.shape[1], im.shape[1]), np.linspace(0, 3e8*max_range_index*sample_rate/(2*sw_len)/((bw/sweep_length)), im.shape[0])) plt.ylabel("Range [m]") plt.xlabel("Time [s]") imgplot = plt.pcolormesh(xx,yy,im) imgplot.set_clim(m-100,m) plt.colorbar() image.imsave('range_time_raw.png', np.flipud(im)) plt.savefig('range_time.png', dpi=500) plt.show() if 0: app = QtGui.QApplication([]) pg.image(im) if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
for key, val in dict(g).items(): subg = val name, shape, found = get_h5_item_structure(subg, name, shape, found) return name, shape, found """The following is only to test the functions. It will find a dataset and display it """ if __name__ == "__main__": import sys import pyqtgraph as pg import qtpy.QtCore from qtpy.QtWidgets import QApplication # this h5 file must contain a dataset composed by an array or an image file_name = 'D:\\data\\PROCHIP\\temp\\test.h5' stack = get_dataset(file_name) pg.image(stack, title="Stack of images") #keeps the window open running a QT application if sys.flags.interactive != 1 or not hasattr(qtpy.QtCore, 'PYQT_VERSION'): QApplication.exec_() sys.exit("End of test")
(0x40, 183, 0x28 , 0x35, 10, 0 ), (0x40, 183, 0x34 , 0x9 , 10, 0 ), (0x40, 181, 0xa0 , 0 , 10, 0 ), (0x40, 183, 0x10 , 0x35, 10, 0 ), # set gain (0x40, 183, 0xbf7, 0x9 , 10, 0 ), # set exposure ] for ct in setup: if ct[0] & 0x80 > 0: dev.ctrl_transfer(bmRequestType=ct[0], bRequest=ct[1], wValue=ct[2], wIndex=ct[3], data_or_wLength=ct[5]) print ct else: result = dev.ctrl_transfer(bmRequestType=ct[0], bRequest=ct[1], wValue=ct[2], wIndex=ct[3]) print ct, '==>', result imv = pg.image() def showframe(): global ep, imv # read one frame rawdata = ep.read(640*480 + 512) dev.ctrl_transfer(bmRequestType=0x40, bRequest=179, wValue=0, wIndex=0) # Colors are in bayer filter pattern: # RGRGRG # GBGBGB # RGRGRG # GBGBGB d1 = np.array(rawdata) d2 = d1[512:].reshape(480, 640) #imv.setImage(d2.T)
def plot_transform(transform, scales=None, multiview=False): """ Display the different bands on the requested scales. Parameters ---------- transform: WaveletTransformBase derived instance a wavelet decomposition. scales: list of int, default None the desired scales, if None compute at all scales. multiview: bool, default False if True use a slider to select a specific band. """ # Set default scales scales = scales or range(transform.nb_scale) # Create application and tab widget app = pyqtgraph.mkQApp() tabs = QtGui.QTabWidget() tabs.setWindowTitle("Wavelet Transform") # Go through each scale pen = pyqtgraph.intColor(2) for scale in scales: # Create the plots for this scales with scrolling possibilities scroller = QtGui.QScrollArea() tabs.addTab(scroller, "Scale {0}".format(scale)) # Go through each band of the current scale # > using multiview # TODO: update this code if multiview: raise NotImplementedError( "Multiview transform view not yet implemented.") window = pyqtgraph.image(numpy.asarray(transform[scale])) scroller.setWidget(window) # > using mosaic else: window = pyqtgraph.GraphicsWindow() scroller.setWidget(window) scale_data = transform[scale] if not isinstance(scale_data, list): scale_data = [scale_data] for subband_data in scale_data: # Deal with complex data if numpy.iscomplex(subband_data).any(): subband_data = numpy.abs(subband_data) subband_data = numpy.lib.pad( subband_data, 1, "constant", constant_values=subband_data.max()) # Select viewer if subband_data.ndim == 1: ax = window.addPlot() ax.plot(subband_data, pen=pen) elif subband_data.ndim == 2: box = window.addViewBox() box.setAspectLocked(True) image = pyqtgraph.ImageItem(subband_data) box.addItem(image) else: raise ValueError("This function currently support only " "1D or 2D data.") window.nextRow() # Display the tab tabs.show() # Run application app.exec_()
#!/usr/bin/env python3 # Monitors if the TOF and MCP datastreams are alive # Stephan Kuschel, Matt Ware, Catherine Saladrigas, 2019 import numpy as np import pyqtgraph as pg import sqs_nqs_tools.online as online import time _daqaliveplot = pg.image(title='DAQ alive: Green good, red bad') CLRS = ['r', 'g'] cmap = pg.ColorMap(np.array([0., 1.]), np.array([pg.colorTuple(pg.Color(c)) for c in CLRS])) _daqaliveplot.setColorMap(cmap) def plotdaqalive(status): ''' Plots red/green image depending on value of status Input: ds Output: None, updates plot window ''' im = np.ones((3, 3)) * float(status) _daqaliveplot.setImage(im, autoLevels=False) pg.QtGui.QApplication.processEvents() def isAlive(ds): # Attempt to get the detector
def plotmaps_pg(self, mode = 0, target = 1, gfilter = 0): # # ## Set up plots/images in window # self.view = pg.GraphicsView() # l = pg.GraphicsLayout(border=(100,100,100)) # self.view.setCentralItem(l) # self.amp1View = l.addViewBox(lockAspect=True) # self.amp2View = l.addViewBox(lockAspect=True) # self.waveformPlot = l.addPlot(title="Waveforms") # l.nextRow() # self.phase1View = l.addViewBox(lockAspect=True) # self.phase2View = l.addViewBox(lockAspect=True) # self.fftPlot = l.addPlot(title="FFTs") # self.phiView = l.addViewBox(lockAspect=True) global D max1 = numpy.amax(self.amplitudeImage1) if target > 1: max1 = numpy.amax([max1, numpy.amax(self.amplitudeImage2)]) max1 = 10.0*int(max1/10.0) # pylab.figure(1) # pylab.subplot(2,3,1) # pylab.title('Amplitude Map1') # #scipy.ndimage.gaussian_filter(self.amplitudeImage1, 2, order=0, output=self.amplitudeImage1, mode='reflect') ampimg = scipy.ndimage.gaussian_filter(self.amplitudeImage1,gfilt, order=0, mode='reflect') #self.amp1View.addItem(pg.ImageItem(ampimg)) self.amp1 = pg.image(ampimg, title="Amplitude Map 1", levels=(0.0, max1)) #imga1 = pylab.imshow(ampimg) #pylab.colorbar() #imga1.set_clim = (0.0, max1) #pylab.subplot(2,3,4) #pylab.title('Phase Map1') phsmap=scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0,mode='reflect') #self.phase1View.addItem(pg.ImageItem(phsmap)) self.phs1 = pg.image(phsmap, title='Phase Map 1') #self.phs1.getHistogramWidget().item.gradient. #imgp1 = pylab.imshow(phsmap, cmap=matplotlib.cm.hsv) #pylab.colorbar() print "plotmaps Block 1" print "mode:", mode self.wavePlt = pg.plot(title='Waveforms') if mode == 0 or mode == 2: self.fftPlt = pg.plot(title = 'FFTs') if mode == 0: #pylab.subplot(2,3,3) for i in range(0, self.nPhases): self.wavePlt.plot(ta.n_times, D[:,5,5].view(ndarray)) #pylab.plot(ta.n_times, D[:,5,5].view(ndarray)) #pylab.plot(self.n_times, D[:,i*55+20, 60]) #pylab.hold('on') #pylab.title('Waveforms') #pylab.subplot(2,3,6) for i in range(0, self.nPhases): self.fftPlt.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(self.DF[:,i*55+20, 60]) #pylab.hold('on') #pylab.title('FFTs') print "plotmaps Block 2" if mode == 1 and target > 1: #pylab.subplot(2,3,2) #pylab.title('Amplitude Map2') #scipy.ndimage.gaussian_filter(self.amplitudeImage2, 2, order=0, output=self.amplitudeImage2, mode='reflect') ampImg2 = scipy.ndimage.gaussian_filter(self.amplitudeImage2,gfilt, order=0, mode='reflect') #imga2 = pylab.imshow(ampImg2) #self.amp2View.addItem(pg.ImageItem(ampImg2)) self.amp2 = pg.image(ampImg2, title='Amplitude Map 2', levels=(0.0, max1)) #imga2.set_clim = (0.0, max1) #pylab.colorbar() #pylab.subplot(2,3,5) phaseImg2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0,mode='reflect') #self.phase2View.addItem(pg.ImageItem(phaseImg2)) self.phs2 = pg.image(phaseImg2, title="Phase Map 2", levels=(-np.pi/2.0, np.pi/2.0)) #imgp2 = pylab.imshow(phaseImg2, cmap=matplotlib.cm.hsv) #pylab.colorbar() #imgp2.set_clim=(-numpy.pi/2.0, numpy.pi/2.0) #pylab.title('Phase Map2') ### doubled phase map #pylab.subplot(2,3,6) #scipy.ndimage.gaussian_filter(self.phaseImage2, 2, order=0, output=self.phaseImage2, mode='reflect') np1 = scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0, mode='reflect') np2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0, mode='reflect') dphase = np1 + np2 #dphase = self.phaseImage1 - self.phaseImage2 #scipy.ndimage.gaussian_filter(dphase, 2, order=0, output=dphase, mode='reflect') #self.phiView.addItem(pg.ImageItem(dphase)) self.phi = pg.image(dphase, title="2x Phi map", levels=(-np.pi, np.pi)) #imgpdouble = pylab.imshow(dphase, cmap=matplotlib.cm.hsv) #pylab.title('2x Phi map') #pylab.colorbar() #imgpdouble.set_clim=(-numpy.pi, numpy.pi) print "plotmaps Block 3" if mode == 2 or mode == 1: if self.phasex == []: self.phasex = numpy.random.randint(0, high=D.shape[1], size=D.shape[1]) self.phasey = numpy.random.randint(0, high=D.shape[2], size=D.shape[2]) #pylab.subplot(2,3,3) sh = D.shape spr = sh[2]/self.nPhases wvfms=[] for i in range(0, self.nPhases): Dm = self.avgimg[i*spr,i*spr] # diagonal run wvfms=self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm) #pylab.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) self.wavePlt.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) #pylab.hold('on') #self.plotlist.append(pg.image(wvfms, title="Waveforms")) #print "it worked" #pylab.title('Waveforms') print "plotmaps Block 4" if mode == 2: #pylab.subplot(2,3,6) for i in range(0, self.nPhases): #pylab.plot(self.DF[1:,80, 80]) #self.fftPlt.plot(self.DF[1:,80,80]) ## causing errors and i'm not sure what the desired thing is, Exception: Can not plot complex data types. pass #pylab.hold('on') #pylab.title('FFTs') print "plotmaps Block 5"
nikon_10x_0p25 = Objective(10, 0.25, 200) """ qxga = SLM((1536, 2048), (8.2, 8.2), 350) mask = AnnularMask(3.824, 2.689) so_29x_0p7 = Objective(28.6, 0.71, 70) """ field = Field(qxga, nikon_10x_0p25, 0.488, 60) # field = Lattice(3.54025, 2.689, 7, 3)(field) field = Bessel(mask.d_out, mask.d_in)(field) field = Defocus(7)(field) synth = Synthesizer(field, mask) options = ["excitation_xy"] results = synth.simulate( options, bounded=True, crop=False, zrange=(-50, 50), zstep=2, cf=0.0 ) w = pg.image(results["excitation_xy"]) w.getView().setAspectLocked(ratio=2 / (8.2 / 60)) w = pg.image(results["excitation_xz"]) w.getView().setAspectLocked() # write_pattern_bmp("pattern.bmp", slm_pattern) app = pg.mkQApp() app.instance().exec_()
#prepare dtm clip=[-124.17, -122.65, 37.80, 39.30] xmin = int((clip[0] - gt[0]) / gt[1]) ymin =int((clip[3] - gt[3]) / gt[5]) xmax = int((clip[1] - gt[0]) / gt[1]) ymax =int((clip[2] - gt[3]) / gt[5]) win_xsize=xmax-xmin win_ysize=ymax-ymin x_buff=150 #new resolution y_buff=150 #new resolution data = np.transpose(layer.GetRasterBand(1).ReadAsArray(xmin,ymin, win_xsize,win_ysize, x_buff,y_buff)) # Disconnect old ROI imv = pg.image(data) # Create new ROI and install exactly as done in ImageView.__init__ # imv.roi.sigRegionChanged.disconnect(imv.roiChanged) imv.roi = pg.LineROI((80, 80), (100, 100), 1) # imv.roi.setZValue(20) imv.view.addItem(imv.roi) imv.roi.hide() imv.roi.sigRegionChanged.connect(imv.roiChanged) ## Start Qt event loop unless running in interactive mode.
def parse_and_go(self, argsin=None): global period global binsize global options global basepath parser = OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar='FILE', help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar='FILE', help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar='FILE', help="Use directory for data") parser.add_option("-t", "--test", dest="test", action='store_true', help="Test mode to check calculations", default=False) parser.add_option("-p", '--period', dest="period", default=4.25, type="float", help="Stimulus cycle period") parser.add_option("-c", '--cycles', dest="cycles", default=0, type="int", help="# cycles to analyze") parser.add_option("-g", '--gfilter', dest="gfilt", default=0, type="float", help="gaussian filter width") parser.add_option("-f", '--fdict', dest="fdict", default=0, type="int", help="Use dictionary entry") parser.add_option("-T", "--tiff", dest="tifffile", default=fn, type="str", help="load a tiff file") parser.add_option("-b", '--binning', dest="binsize", default=self.binsize, type="int", help="bin reduction x,y") parser.add_option("-z", '--zbinning', dest="zbinsize", default=self.zbinsize, type="int", help="bin reduction z") if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() if options.tifffile is not None: self.tifffile = options.tifffile if options.binsize is not None: self.binsize = options.binsize if options.zbinsize is not None: self.zbinsize = options.zbinsize # divided=np.zeros((4,100,512,512),float) if options.tifffile is not None: n2 = self.tifffile + '_MMStack_Pos0.ome.tif' # matfile = sio.loadmat(os.path.join(basepath,self.tifffile,'updown_data.mat')) self.read_tiff_stack( filename=os.path.join(basepath, self.tifffile, n2)) im = self.imageData pg.image(im, title='raw image') pg.image(np.std(im, axis=0), title='standard deviation') pg.plot(im[:, 50, 60], title='50,60') pg.plot(im[:, 60, 50], title='60,50') print 'image shape: ', np.shape(im) # self.binReps() # self.avg_over_trials() # self.binToStim() # self.Image_Background() # self.Image_Divided() pylab.show() return
def parse_and_go(self, argsin = None): global period global binsize global options global basepath parser=OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar='FILE', help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar='FILE', help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar='FILE', help="Use directory for data") parser.add_option("-t", "--test", dest="test", action='store_true', help="Test mode to check calculations", default=False) parser.add_option("-p", '--period', dest = "period", default=4.25, type="float", help = "Stimulus cycle period") parser.add_option("-c", '--cycles', dest = "cycles", default=0, type="int", help = "# cycles to analyze") parser.add_option("-b", '--binning', dest = "binsize", default=0, type="int", help = "bin reduction x,y") parser.add_option("-g", '--gfilter', dest = "gfilt", default=0, type="float", help = "gaussian filter width") parser.add_option("-f", '--fdict', dest = "fdict", default=0, type="int", help = "Use dictionary entry") done_deal=np.zeros((4,256,256),float) if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() print 'DB keys', DB.keys() if options.fdict is not None: if options.fdict in DB.keys(): # populate options options.upfile = DB[options.fdict][0] options.stimtype = DB[options.fdict][1] options.reps = DB[options.fdict][2] options.freq = DB[options.fdict][6] options.datadate = DB[options.fdict][5] else: print "File %d NOT in DBase\n" % options.fdict return if options.directory is not None: self.directory = options.directory print 'options.upfile', options.upfile if options.stimtype is not None: # basepath = '/Volumes/TROPPDATA/data/2016.06.28_000/' + options.stimtype+'_' basepath = '/Volumes/TROPPDATA/data/' + options.datadate+'_000/' + options.stimtype+'_' print 'set up stimtype' # divided=np.zeros((4,100,512,512),float) if options.reps is not None: #for nn in [0,1,2,3,4,5,6,11]: for nn in range(options.reps): self.load_file(nn) self.RegisterStack() self.ProcessImage() #self.ProcessImage() if nn == 0: #check the shape of imagedata and alter divided if necessary imshape = np.shape(self.imageData) divided=np.zeros((options.reps,imshape[0],imshape[1],imshape[2]),float) #processed=np.zeros((options.reps,85,imshape[1],imshape[2]),float) # self.Image_Background() # self.Image_Divided() # print 'divided', np.shape(self.divided) # self.divided= self.imageData divided[nn] = self.imageData self.imageData=[] #processed[nn] = self.ProcessedImageData print 'shape of divided: ', np.shape(divided) self.AvgFrames=np.mean(divided, axis=0) print 'shape of AvgFrames: ', np.shape(self.AvgFrames) temp = self.AvgFrames[:,110:210,70:170] # self.AvgFrames = [] # self.AvgFrames = temp stim1=self.AvgFrames[0:19] stim2=self.AvgFrames[20:39] stim3=self.AvgFrames[40:59] stim4=self.AvgFrames[60:79] stim5=self.AvgFrames[80:99] averagestim = (stim1+stim2+stim3+stim4+stim5)/5 pg.image(averagestim) pg.image(averagestim, title='average across all stimuli') pg.image(np.max(stim1,axis=0),title='Max Stimulus 1') pg.image(np.max(stim2,axis=0),title='Max Stimulus 2') pg.image(np.max(stim3,axis=0),title='Max Stimulus 3') pg.image(np.max(stim4,axis=0),title='Max Stimulus 4') pg.image(np.max(stim5,axis=0),title='Max Stimulus 5') pg.image(np.sum(stim1,axis=0),title='Sum Stimulus 1') # pg.image(np.max(self.AvgFrames[59:82],axis=0),title='Max response') # pg.image(np.mean(divided, axis=0), title='divided image') # pg.image(np.std(divided, axis=0), title='standard deviation of the image') # imagestd=np.std(divided) # gf = scipy.ndimage.gaussian_filter(np.mean(divided,axis=0), [0.05,.01,.01], order=0, mode='reflect') # pg.image(np.max(gf,axis=0),title='filtered max') # pg.image(np.mean(processed, axis=0), title='processed, not divided') # backproc = np.mean(processed[:,5:,:,:],axis=1) # divproc = (processed-backproc)/backproc # pg.image(np.mean(divproc),axis=0) return
that is updated continuously like a video. For a super-basic example see surfacePlotExample.py; the code below is a little more elaborate. Rob Campbell - SWC 2020 ''' import numpy as np from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph as pg ## Create a smoothed random image img = pg.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 20 + 100 ## Display the data imview = pg.image(img) # Remove the buttons beneath to histogram imview.ui.roiBtn.hide() imview.ui.menuBtn.hide() # So the histogram does not bounce arond like crazy imview.ui.graphicsView.autoPixelRange = False imview.ui.histogram.autoPixelRange = False updateTime = pg.ptime.time() fps = 0 def updateData(): global updateTime, fps
def parse_and_go(self, argsin=None): global period parser = OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar="FILE", help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar="FILE", help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar="FILE", help="Use directory for data") parser.add_option( "-t", "--test", dest="test", action="store_true", help="Test mode to check calculations", default=False ) parser.add_option("-p", "--period", dest="period", default=8.0, type="float", help="Stimulus cycle period") parser.add_option("-c", "--cycles", dest="cycles", default=0, type="int", help="# cycles to analyze") parser.add_option("-b", "--binning", dest="binsize", default=0, type="int", help="bin reduction x,y") parser.add_option("-g", "--gfilter", dest="gfilt", default=0, type="float", help="gaussian filter width") parser.add_option("-f", "--fdict", dest="fdict", default=0, type="int", help="Use dictionary entry") if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() if options.period is not None: measuredPeriod = options.period if options.cycles is not None: self.nCycles = options.cycles if options.binsize is not None: binsize = options.binsize if options.gfilt is not None: gfilt = options.gfilt # TFR- this code generates a test signal for running a test analysis sequence print options.test if options.test is True: print "Running Test Sample" period = 8.0 # period and frame sample rate can be different framerate = 8.0 nper = 1 d = 10.0 * numpy.random.normal(size=(2500, 128, 128)).astype("float32") ds = d.shape self.nFrames = d.shape[0] self.nPhases = 10 maxdel = 50 self.phasex = [] self.phasey = [] for i in range(0, self.nPhases): dx = i * ds[1] / self.nPhases # each phase is assigned to a region baseline = 0.0 self.resp = numpy.zeros((self.nFrames,)) phaseDelay = 0.25 * period + period * ( float(i) / self.nPhases ) # phase delay for this region from 0 to nearly the stimulus repeat period # print '********phase delay: ', phaseDelay for j in range(0, nper): # for each period tdelay = (float(j) * period) + phaseDelay # time to phase delay point idelay = int(numpy.floor(tdelay * framerate)) # convert to frame position in frame space # print ' tdel: ', tdelay, ' idel: ', idelay # if idelay < self.nFrames-maxdel: # self.resp[idelay:idelay+maxdel] = (i+1)*numpy.exp(-numpy.linspace(0, 2, maxdel)) # marks amplitudes as well self.resp = numpy.sin( numpy.linspace(0, 2.0 * numpy.pi * self.nFrames / (period * framerate), self.nFrames) + i * numpy.pi / 8 - numpy.pi / 2.0 ) d[:, dx : dx + int(ds[1] / self.nPhases), 5 : int(ds[2] / 2)] += self.resp[ :, numpy.newaxis, numpy.newaxis ] self.phasex.append((2 + (dx + int(ds[1] / self.nPhases)) / 2)) self.phasey.append( (6 + int(ds[2] / 2) / 2) ) # make the signal equivalent of digitized one (baseline 3000, signal at 1e-4 of baseline) d = (d * 3000.0 * 1e-4) + 3000.0 # scale and offset to match data scaling coming in self.imageData = d.astype("int16") # reduce to a 16-bit map to match camera data type self.times = numpy.arange(0, self.nFrames / framerate, 1.0 / framerate) print "Test Image Created" self.Analysis_FourierMap(period=period, target=1, mode=1, bins=binsize) print "Completed Analysis FourierMap" self.plotmaps_pg(mode=2, gfilter=gfilt) print "Completed plot maps" return if options.fdict is not None: if options.fdict in DB.keys(): # populate options options.upfile = DB[options.fdict][0] options.downfile = DB[options.fdict][1] options.period = DB[options.fdict][4] else: print "File %d NOT in DBase\n" % options.fdict return if options.directory is not None: self.directory = options.directory if options.upfile is not None: self.upfile = options.upfile target = 1 if options.downfile is not None: self.downfile = options.downfile target = 2 target = 0 upf = None dwnf = None if options.upfile is not None: upf = basepath + options.upfile + "/Camera/frames.ma" if options.downfile is not None: dwnf = basepath + options.downfile + "/Camera/frames.ma" for file in (upf, dwnf): # if options.upfile is not None and options.downfile is not None: if file is None: break im = [] self.imageData = [] print "loading data from ", file try: im = MetaArray(file=file, subset=(slice(0, 2), slice(64, 128), slice(64, 128))) except: print "Error loading upfile: %s\n" % file return print "data loaded" target = target + 1 self.times = im.axisValues("Time").astype("float32") self.imageData = im.view(np.ndarray).astype("float32") im = [] if file is upf: upflag = 1 else: upflag = 0 measuredPeriod = 1.25 self.Analysis_FourierMap(period=measuredPeriod, target=target, bins=binsize, up=upflag) if target > 0: self.plotmaps_pg(mode=1, target=target, gfilter=gfilt) self.firstframe = pg.image(self.imageData[0], title="first frame of image")
im_size = 512 #2560 #A n X n X n volume sino_center = im_size / 2 #1280 num_angles = 512 #1024 gpu_device = 2 oversamp_factor = 1.5 num_iter = 150 p = 1.2 sigma = .1 obj = tomopy.shepp3d((num_slice, im_size, im_size)) # Generate an object. theta = tomopy.angles(num_angles) # Generate uniformly spaced tilt angles. ### Comparing to tomopy tomo = tomopy.project(obj, theta) proj_dim = tomo.shape[2] tomo = tomo[:, :, proj_dim / 2 - im_size / 2:proj_dim / 2 + im_size / 2] pg.image(tomo) pg.QtGui.QApplication.exec_() ################## GPU MBIR ###################### input_params = {} input_params['gpu_device'] = gpu_device input_params['oversamp_factor'] = oversamp_factor input_params['num_iter'] = num_iter input_params['p'] = p input_params['smoothness'] = sigma t = time.time() rec_sirt = gpuSIRT(tomo, theta, sino_center, input_params) elapsed_time = (time.time() - t) print('Time for reconstucting using GPU-SIRT of %d slices with %d iter : %f' % (num_slice, num_iter, elapsed_time)) pg.image(rec_sirt) pg.QtGui.QApplication.exec_()
def Image_Divided(self): self.divided = (self.imageData - self.background) / self.background self.imageData = self.divided pg.image(self.divided[1:], title='divide image') return
print("Median:", np.median(lengths)) # Read the syllables and generate features, also zero padding short syllables nlevels = 5 featuresw = [] n_mfcc = 40 n_bins = 32 n_chroma = 12 featuresm = [] featuresc = [] # featuresc = [] featuress = [] featuresa = [] labels = [] count = 0 imagewindow = pg.image() for record in dataset: # # 1) compute features over whole syllables # audiodata = loadFile(filename=record[0], duration=record[2][1] - record[2][0], offset=record[2][0], fs=fs, # denoise=False, f1=0, f2=0) # audiodata = audiodata.tolist() # featuresa.append([audiodata, record[1][2], record[1][3], record[-1]]) # # mfcc = librosa.feature.mfcc(y=np.asarray(audiodata), sr=fs, n_mfcc=40) # mfcc_delta = librosa.feature.delta(mfcc, mode='nearest') # mfcc = np.concatenate((mfcc, mfcc_delta), axis=0) # mfcc = [i for sublist in mfcc for i in sublist] # featuresm.append([mfcc, record[1][2], record[1][3], record[-1]]) # # ws = WaveletSegment.WaveletSegment(spInfo={}) # we = ws.computeWaveletEnergy(data=audiodata, sampleRate=fs, nlevels=5, wpmode='new',
#if 1: #bin_fp = open("e:/zhuang/test.bin", "wb") if 0: hcam.startAcquisition() print("Gooooo") time.sleep(5) for i in range(hcam.number_frames): # Get frames. [frames, dims] = hcam.getFrames() # Save frames. for aframe in frames: np_data = aframe.getData() pg.image(np.reshape(np_data,(vsize, hsize)).T,) #np_data.tofile(bin_fp) # Print backlog. print (i, len(frames)) #print(np_data) #pg.image(np.reshape(np_data,(vsize, hsize)).T) #.T do the transpose, otherwise the image is inverted (due to how data are put in the buffer) #if (len(frames) > 20): # exit() hcam.stopAcquisition() #bin_fp.close() hcam.shutdown() error_uninit = dcam.dcamapi_uninit() if (error_uninit != DCAMERR_NOERROR):
""" Display a plot and an image with minimal setup. pg.plot() and pg.image() are indended to be used from an interactive prompt to allow easy data inspection (but note that PySide unfortunately does not call the Qt event loop while the interactive prompt is running, in this case it is necessary to call QApplication.exec_() to make the windows appear). """ import initExample ## Add path to library (just for examples; you do not need this) import numpy as np import pyqtgraph as pg data = np.random.normal(size=1000) pg.plot(data, title="Simplest possible plotting example") data = np.random.normal(size=(500,500)) pg.image(data, title="Simplest possible image example") if __name__ == '__main__': pg.mkQApp().exec_()
import pyqtgraph as pg from scopetek import Scopetek # Initialize camera cam = Scopetek() # Set camera parameters cam.setup(resolution=(640,480), fast=True, exposure=131e-3, gain=1) imv = pg.image() while True: frame = cam.readframe() rgb = cam.bayer_to_rgb(frame) imv.setImage(rgb.transpose(1, 0, 2)) pg.QtGui.QApplication.processEvents() if not imv.isVisible(): cam.stop() break
def __init__(self, fwritename, soft_version, raw_spts, nucs_dil, nucs_3d_det, spts_segm, spts_mature, bkg_cages, raw_data_fname, int_thr_value): mycmap = np.fromfile('mycmap.bin', 'uint16').reshape((10000, 3)) nucs_dil_3c = label2rgb(nucs_dil, bg_label=0, bg_color=[0, 0, 0], colors=mycmap) w = pg.image(nucs_dil_3c) txt_pos = regionprops( nucs_dil ) # regionprops of the nuclei: we use the centroids coordinates to print text on image and in the excel for t in range(len( txt_pos)): # map of dilated nuclei with tag-numbers on the top a = pg.TextItem(str(txt_pos[t]['label']), 'k') w.addItem(a) a.setPos(txt_pos[t]['centroid'][0] - 30, txt_pos[t]['centroid'][1] - 30) mtx_mature = np.zeros(nucs_3d_det.nucs_lbls.shape ) # 3D matrix of all the spots center of mass steps = nucs_3d_det.nucs_lbls.shape[0] for k in range(spts_mature.shape[1]): # populating the matrix mtx_mature[int(spts_mature[3, k]), int(spts_mature[4, k]), int(spts_mature[5, k])] = 1 mtx_mature_int = mtx_mature * np.sign(nucs_3d_det.nucs_lbls) mtx_mature_ext = mtx_mature * (1 - np.sign(nucs_3d_det.nucs_lbls)) idxs = np.unique(nucs_dil)[1:] # list of the nuclei tags book = xlwt.Workbook(encoding='utf-8') sheet1 = book.add_sheet("Internal") sheet2 = book.add_sheet("External") sheet3 = book.add_sheet("Tot") print(a) sheet1.write(0, 0, "Nuc_id") sheet1.write(1, 0, "X coord") sheet1.write(2, 0, "Y coord") sheet1.write(3, 0, "Numb of Spts") sheet1.write(4, 0, "Region Volume") sheet1.write(5, 0, "Nucleus Volume") sheet1.write(6, 0, "Spots Intensity") sheet2.write(0, 0, "Nuc_id") sheet2.write(1, 0, "X coord") sheet2.write(2, 0, "Y coord") sheet2.write(3, 0, "Numb of Spts") sheet2.write(4, 0, "Region Volume") sheet2.write(5, 0, "Nucleus Volume") sheet2.write(6, 0, "Spots Intensity") sheet3.write(0, 0, "Nuc_id") sheet3.write(1, 0, "X coord") sheet3.write(2, 0, "Y coord") sheet3.write(3, 0, "Numb of Spts") sheet3.write(4, 0, "Region Volume") sheet3.write(5, 0, "Nucleus Volume") sheet3.write(6, 0, "Spots Intensity") book_b = xlwt.Workbook(encoding='utf-8') sheet1_b = book_b.add_sheet("Internal") sheet2_b = book_b.add_sheet("External") sheet3_b = book_b.add_sheet("Tot") sheet1_b.write(0, 0, "Nuc_id") sheet1_b.write(1, 0, "X coord") sheet1_b.write(2, 0, "Y coord") sheet1_b.write(3, 0, "Numb of Spts") sheet1_b.write(4, 0, "Region Volume") sheet1_b.write(5, 0, "Nucleus Volume") sheet1_b.write(6, 0, "Spots Intensity/Bkg") sheet2_b.write(0, 0, "Nuc_id") sheet2_b.write(1, 0, "X coord") sheet2_b.write(2, 0, "Y coord") sheet2_b.write(3, 0, "Numb of Spts") sheet2_b.write(4, 0, "Region Volume") sheet2_b.write(5, 0, "Nucleus Volume") sheet2_b.write(6, 0, "Spots Intensity/Bkg") sheet3_b.write(0, 0, "Nuc_id") sheet3_b.write(1, 0, "X coord") sheet3_b.write(2, 0, "Y coord") sheet3_b.write(3, 0, "Numb of Spts") sheet3_b.write(4, 0, "Region Volume") sheet3_b.write(5, 0, "Nucleus Volume") sheet3_b.write(6, 0, "Spots Intensity/Bkg") pbar1 = ProgressBar(total1=idxs.size) pbar1.show() for q in range(idxs.size): # print(q) pbar1.update_progressbar(q) sheet1.write(0, q + 1, float(idxs[q])) # writing the id sheet1.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet1.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet1.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet1.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet1.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume sheet2.write(0, q + 1, float(idxs[q])) # writing the id sheet2.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet2.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet2.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet2.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet2.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume sheet3.write(0, q + 1, float(idxs[q])) # writing the id sheet3.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet3.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet3.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet3.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet3.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume sheet1_b.write(0, q + 1, float(idxs[q])) # writing the id sheet1_b.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet1_b.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet1_b.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet1_b.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet1_b.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume sheet2_b.write(0, q + 1, float(idxs[q])) # writing the id sheet2_b.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet2_b.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet2_b.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet2_b.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet2_b.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume sheet3_b.write(0, q + 1, float(idxs[q])) # writing the id sheet3_b.write( 1, q + 1, txt_pos[q]['centroid'][0]) # x coordinate of nuclei centroid sheet3_b.write( 2, q + 1, txt_pos[q]['centroid'][1]) # y coordinate of nuclei centroid sheet3_b.write(3, q + 1, np.sum( (nucs_dil == idxs[q]) * mtx_mature)) # number of spots sheet3_b.write(4, q + 1, float( (nucs_dil == idxs[q]).sum() * steps)) # region nuclei volume sheet3_b.write( 5, q + 1, float( ((nucs_dil == idxs[q]) * np.sign(nucs_3d_det.nucs_lbls)).sum())) # nucleus volume pbar1.close() pbar2 = ProgressBar(total1=idxs.size) pbar2.show() for j in range(idxs.size): # print(j) pbar2.update_progressbar(j) idxs_ins = np.unique( (nucs_dil == idxs[j]) * mtx_mature_int * spts_segm )[1:] # tags for the spots inside the dilated nucleus (nuclear region) jj = -1 # this is just for paging purposes for jj in range(idxs_ins.size): a_jj = np.where(spts_mature[0, :] == idxs_ins[jj])[0] if a_jj.size > 0: sheet1.write(7 + jj, j + 1, float( spts_mature[1, a_jj[0]])) # intensity value of the spots sheet3.write(7 + jj, j + 1, float(spts_mature[1, a_jj[0]])) bkg_bff = (bkg_cages == spts_mature[0, a_jj[0]]) * raw_spts bkg_bff = bkg_bff[bkg_bff != 0].mean() sheet1_b.write(7 + jj, j + 1, float(spts_mature[1, a_jj[0]]) / bkg_bff) # intensity value of the spots sheet3_b.write(7 + jj, j + 1, float(spts_mature[1, a_jj[0]]) / bkg_bff) # this part is just to write the names of the files and the data: if statement is just for paging purposes if j == 0: try: sheet1.write(7 + jj + 2, 0, "File Name") sheet1.write(7 + jj + 3, 0, raw_data_fname) sheet1.write(7 + jj + 5, 0, "date") sheet1.write( 7 + jj + 6, 0, str(datetime.date.today().day) + '/' + str(datetime.date.today().month) + '/' + str(datetime.date.today().year)) sheet1.write(7 + jj + 8, 0, "Software Version") sheet1.write(7 + jj + 9, 0, soft_version) sheet1_b.write(7 + jj + 2, 0, "File Name") sheet1_b.write(7 + jj + 3, 0, raw_data_fname) sheet1_b.write(7 + jj + 5, 0, "date") sheet1_b.write( 7 + jj + 6, 0, str(datetime.date.today().day) + '/' + str(datetime.date.today().month) + '/' + str(datetime.date.today().year)) sheet1_b.write(7 + jj + 8, 0, "Software Version") sheet1_b.write(7 + jj + 9, 0, soft_version) except UnboundLocalError: sheet1.write(13, 0, "File Name") sheet1.write(14, 0, raw_data_fname) sheet1.write(16, 0, "date") sheet1.write( 17, 0, str(datetime.date.today().day) + '/' + str(datetime.date.today().month) + '/' + str(datetime.date.today().year)) sheet1.write(19, 0, "Software Version") sheet1.write(20, 0, soft_version) sheet1_b.write(13, 0, "File Name") sheet1_b.write(14, 0, raw_data_fname) sheet1_b.write(16, 0, "date") sheet1_b.write( 17, 0, str(datetime.date.today().day) + '/' + str(datetime.date.today().month) + '/' + str(datetime.date.today().year)) sheet1_b.write(19, 0, "Software Version") sheet1_b.write(20, 0, soft_version) idxs_exs = np.unique( (nucs_dil == idxs[j]) * mtx_mature_ext * spts_segm )[1:] # tags for the spots inside the dilated nucleus (nuclear region) for kk in range(idxs_exs.size): a_kk = np.where(spts_mature[0, :] == idxs_exs[kk])[0] if a_kk.size > 0: sheet2.write(7 + kk, j + 1, float( spts_mature[1, a_kk[0]])) # intensity value of the spots sheet3.write(7 + jj + kk + 1, j + 1, float(spts_mature[1, a_kk[0]])) bkg_bff = (bkg_cages == spts_mature[0, a_kk[0]]) * raw_spts bkg_bff = bkg_bff[bkg_bff != 0].mean() sheet2_b.write(7 + kk, j + 1, float(spts_mature[1, a_kk[0]]) / bkg_bff) # intensity value of the spots sheet3_b.write(7 + jj + kk + 1, j + 1, float(spts_mature[1, a_kk[0]]) / bkg_bff) book.save(fwritename + '/smiFish_journal.xls') book_b.save(fwritename + '/smiFish_background_journal.xls') steps, xsize, ysize = spts_segm.shape spts_segm = spts_segm.reshape(spts_segm.size) spts_segm = np.append(steps, spts_segm) spts_segm = np.append(xsize, spts_segm) spts_segm = np.append(ysize, spts_segm) spts_segm.astype("uint16").tofile( str(fwritename) + "/spots_segmented.bin") nucs_lbls = nucs_3d_det.nucs_lbls nucs_lbls = nucs_lbls.reshape(nucs_3d_det.nucs_lbls.size) nucs_lbls = np.append(steps, nucs_lbls) nucs_lbls = np.append(xsize, nucs_lbls) nucs_lbls = np.append(ysize, nucs_lbls) nucs_lbls.astype("uint16").tofile( str(fwritename) + "/nucs_segmented.bin") nucs_dil = nucs_dil.reshape(nucs_dil.size) nucs_dil = np.append(xsize, nucs_dil) nucs_dil = np.append(ysize, nucs_dil) nucs_dil.astype("uint16").tofile(str(fwritename) + "/nucs_dil.bin") pbar2.close()
def parse_and_go(self, argsin = None): global period global binsize global options global basepath parser=OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar='FILE', help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar='FILE', help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar='FILE', help="Use directory for data") parser.add_option("-t", "--test", dest="test", action='store_true', help="Test mode to check calculations", default=False) parser.add_option("-p", '--period', dest = "period", default=4.25, type="float", help = "Stimulus cycle period") parser.add_option("-c", '--cycles', dest = "cycles", default=0, type="int", help = "# cycles to analyze") parser.add_option("-b", '--binning', dest = "binsize", default=0, type="int", help = "bin reduction x,y") parser.add_option("-g", '--gfilter', dest = "gfilt", default=0, type="float", help = "gaussian filter width") parser.add_option("-f", '--fdict', dest = "fdict", default=0, type="int", help = "Use dictionary entry") done_deal=np.zeros((4,256,256),float) if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() print 'DB keys', DB.keys() if options.fdict is not None: if options.fdict in DB.keys(): # populate options options.upfile = DB[options.fdict][0] options.stimtype = DB[options.fdict][1] options.reps = DB[options.fdict][2] options.freq = DB[options.fdict][6] else: print "File %d NOT in DBase\n" % options.fdict return if options.directory is not None: self.directory = options.directory print 'options.upfile', options.upfile if options.stimtype is not None: basepath = '/Volumes/TROPPDATA/data/2016.06.14_000/' + options.stimtype+'_' print 'set up stimtype' # divided=np.zeros((4,100,512,512),float) if options.reps is not None: for nn in range(options.reps): self.load_file(nn) if nn == 0: #check the shape of imagedata and alter divided if necessary imshape = np.shape(self.imageData) divided=np.zeros((4,imshape[0],imshape[1],imshape[2]),float) # self.Image_Background() self.Image_Divided() # print 'divided', np.shape(self.divided) # self.divided= self.imageData divided[nn] = self.divided self.AvgFrames=np.mean(divided, axis=0) stim1=self.AvgFrames[0:19] stim2=self.AvgFrames[20:39] stim3=self.AvgFrames[40:59] stim4=self.AvgFrames[60:79] stim5=self.AvgFrames[80:99] pg.image(np.max(stim1,axis=0),title='Stimulus 1') pg.image(np.max(stim2,axis=0),title='Stimulus 2') pg.image(np.max(stim3,axis=0),title='Stimulus 3') pg.image(np.max(stim4,axis=0),title='Stimulus 4') pg.image(np.max(stim5,axis=0),title='Stimulus 5') pg.image(np.max(self.AvgFrames,axis=0),title='Max across all stimuli') return
if matrix[ neur_y, neur_x] == 70: ## THRESHOLD value. Change to change firing rate matrix[neur_y, neur_x] = 0 spike_matrix[neur_y, neur_x] = 1 # Pi_socket.sendto(str(neur_x)+' '+str(neur_y)+' ', (server, s_port)) #With each spike Pi receives something like '10 12 ' # Pi_socket.send(str(neur_x)+' '+str(neur_y)+' \n') #With each spike Pi receives something like '10 12 ' count_out += 1 # inc_str = Pi_socket.recv(1024) # inc_int = map(int, inc_str[0:len(inc_str)-1].split(' ')) # count_inc += len(inc_int) win.setImage(spike_matrix, autoRange=True) pg.QtGui.QApplication.processEvents() """ Here we initialize the plot window and plotting colors. """ pos = np.array([0.0, 1.0]) color = np.array([[0, 0, 255, 255], [255, 0, 0, 255]]) #, dtype=np.ubyte) color_map = pg.ColorMap(pos, color, mode=None) win = pg.image(matrix) win.view.setAspectLocked(False) win.setColorMap(color_map) win.resize(700, 500) while True: UDP_jAER() #finally: # DVS_socket.close() # Pi_socket.close()
def parse_and_go(self, argsin = None): global period global binsize global options global basepath parser=OptionParser() # command line options ##### parses all of the options inputted at the command line TFR 11/13/2015 parser.add_option("-u", "--upfile", dest="upfile", metavar='FILE', help="load the up-file") parser.add_option("-d", "--downfile", dest="downfile", metavar='FILE', help="load the down-file") parser.add_option("-D", "--directory", dest="directory", metavar='FILE', help="Use directory for data") parser.add_option("-t", "--test", dest="test", action='store_true', help="Test mode to check calculations", default=False) parser.add_option("-p", '--period', dest = "period", default=4.25, type="float", help = "Stimulus cycle period") parser.add_option("-c", '--cycles', dest = "cycles", default=0, type="int", help = "# cycles to analyze") parser.add_option("-b", '--binning', dest = "binsize", default=0, type="int", help = "bin reduction x,y") parser.add_option("-g", '--gfilter', dest = "gfilt", default=0, type="float", help = "gaussian filter width") parser.add_option("-f", '--fdict', dest = "fdict", default=0, type="int", help = "Use dictionary entry") done_deal=np.zeros((4,256,256),float) if argsin is not None: (options, args) = parser.parse_args(argsin) else: (options, args) = parser.parse_args() print 'DB keys', DB.keys() if options.fdict is not None: if options.fdict in DB.keys(): # populate options options.upfile = DB[options.fdict][0] options.stimtype = DB[options.fdict][1] options.reps = DB[options.fdict][2] options.freq = DB[options.fdict][6] else: print "File %d NOT in DBase\n" % options.fdict return if options.directory is not None: self.directory = options.directory print 'options.upfile', options.upfile if options.stimtype is not None: # basepath = '/Volumes/TROPPDATA/data/2016.06.28_000/' + options.stimtype+'_' basepath = '/Users/tjropp/Desktop/data/2016.06.14_000/' + options.stimtype+'_' print 'set up stimtype' # divided=np.zeros((4,100,512,512),float) if options.reps is not None: for nn in [0]: # for nn in range(options.reps): self.load_file(nn) #self.RegisterStack() self.ProcessImage() #self.ProcessImage() if nn == 0: #check the shape of imagedata and alter divided if necessary imshape = np.shape(self.imageData) divided=np.zeros((options.reps,imshape[0],imshape[1],imshape[2]),float) #processed=np.zeros((options.reps,85,imshape[1],imshape[2]),float) # self.Image_Background() self.Image_Divided() # print 'divided', np.shape(self.divided) # self.divided= self.imageData divided[nn] = self.divided #processed[nn] = self.ProcessedImageData print 'shape of divided: ', np.shape(divided) self.AvgFrames=np.mean(divided, axis=0) print 'shape of AvgFrames: ', np.shape(self.AvgFrames) stim1=np.sum(self.imageData[0:19,104:204,199:299],axis=0) stim2=np.sum(self.imageData[18:37,104:204,199:299],axis=0) stim3=np.sum(self.imageData[38:57,104:204,199:299],axis=0) stim4=np.sum(self.imageData[58:77,104:204,199:299],axis=0) stim5=np.sum(self.imageData[78:97,104:204,199:299],axis=0) stim6=np.sum(self.imageData[98:117,104:204,199:299],axis=0) stimuli=(stim2+stim3+stim4+stim5+stim6)/(5*stim1)-(stim1/stim1) stimuli=scipy.ndimage.gaussian_filter(stimuli,1) pg.image(stimuli,title='stimuli') ROI1=np.where(stim1[19,:]==np.max(stim1[19,:])) ROI2=np.where(np.max(stim1[47,:])) print 'ROI1:',ROI1 # pg.image(np.max(stim2,axis=0),title='Stimulus 2') # pg.image(np.max(stim3,axis=0),title='Stimulus 3') # pg.image(np.max(stim4,axis=0),title='Stimulus 4') # # pg.image(np.max(stim5,axis=0),title='Stimulus 5') # datasignal=self.imageData[np.where(np.logical_and(np.std(divided, axis=0)<0.021,np.std(divided,axis=0)>0.012))] # print 'size of datasignal', np.shape(datasignal) # # pg.image(np.mean(datasignal,axis=0)) pg.image(np.max(self.AvgFrames[59:82],axis=0),title='Max response') pg.image(np.mean(divided, axis=0), title='divided image') pg.image(np.std(divided, axis=0), title='standard deviation of the image') # imagestd=np.std(divided) # gf = scipy.ndimage.gaussian_filter(np.mean(divided,axis=0), [0.05,.01,.01], order=0, mode='reflect') # pg.image(np.max(gf,axis=0),title='filtered max') # pg.image(np.mean(processed, axis=0), title='processed, not divided') # backproc = np.mean(processed[:,5:,:,:],axis=1) # divproc = (processed-backproc)/backproc # pg.image(np.mean(divproc),axis=0) return
#_pgimage = pg.image(title='Current Image {}'.format(xfel.__version__)) def plotimage(d): ''' Plots current time of flight data from one shot. Updates _tofplot window Input: image data Output: None, updates plot window ''' _pgimage.setImage(d, autoRange=False) pg.QtGui.QApplication.processEvents() _pgimage2 = pg.image(title='AverageImage {}'.format(xfel.__version__)) _pghistplot = pg.plot(title='HistBrightness {}'.format(xfel.__version__)) _pgbrightestimg = pg.image(title='Brightest Shots {}'.format(xfel.__version__)) brightestlen = 15 imagehist = xfel.DataBuffer(brightestlen) tidhist = xfel.DataBuffer(brightestlen) brightnesshist = xfel.DataBuffer(1000) _brightlasttid = -1 def plotbrightest(d, tid=0): ''' Plots current time of flight data from one shot. Updates _tofplot window Input: image data
def plotmaps_pg(self, mode = 0, target = 1, gfilter = 0): pos = np.array([0.0, 0.33, 0.67, 1.0]) color = np.array([[0,0,0,255], [255,128,0,255], [255,255,0,255],[0,0,0,255]], dtype=np.ubyte) maps = pg.ColorMap(pos, color) lut = maps.getLookupTable(0.0, 1.0, 256) # # ## Set up plots/images in window # self.view = pg.GraphicsView() # l = pg.GraphicsLayout(border=(100,100,100)) # self.view.setCentralItem(l) # self.amp1View = l.addViewBox(lockAspect=True) # self.amp2View = l.addViewBox(lockAspect=True) # self.waveformPlot = l.addPlot(title="Waveforms") # l.nextRow() # self.phase1View = l.addViewBox(lockAspect=True) # self.phase2View = l.addViewBox(lockAspect=True) # self.fftPlot = l.addPlot(title="FFTs") # self.phiView = l.addViewBox(lockAspect=True) global D max1 = numpy.amax(self.amplitudeImage1) if target > 1: max1 = numpy.amax([max1, numpy.amax(self.amplitudeImage2)]) max1 = 10.0*int(max1/10.0) # pylab.figure(1) # pylab.subplot(2,3,1) # pylab.title('Amplitude Map1') # #scipy.ndimage.gaussian_filter(self.amplitudeImage1, 2, order=0, output=self.amplitudeImage1, mode='reflect') ampimg = scipy.ndimage.gaussian_filter(self.amplitudeImage1,gfilt, order=0, mode='reflect') #self.amp1View.addItem(pg.ImageItem(ampimg)) self.amp1 = pg.image(ampimg, title="Amplitude Map 1", levels=(0.0, max1)) #imga1 = pylab.imshow(ampimg) #pylab.colorbar() #imga1.set_clim = (0.0, max1) #pylab.subplot(2,3,4) #pylab.title('Phase Map1') phsmap=scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0,mode='reflect') #self.phase1View.addItem(pg.ImageItem(phsmap)) self.phs1 = pg.image(phsmap, title='Phase Map 1') #self.phs1.getHistogramWidget().item.gradient. #imgp1 = pylab.imshow(phsmap, cmap=matplotlib.cm.hsv) #pylab.colorbar() print "plotmaps Block 1" print "mode:", mode self.wavePlt = pg.plot(title='Waveforms') if mode == 0 or mode == 2: self.fftPlt = pg.plot(title = 'FFTs') if mode == 0: #pylab.subplot(2,3,3) # for i in range(0, self.nPhases): # self.wavePlt.plot(ta.n_times, D[:,5,5].view(ndarray)) # #pylab.plot(ta.n_times, D[:,5,5].view(ndarray)) # #pylab.plot(self.n_times, D[:,i*55+20, 60]) # #pylab.hold('on') # #pylab.title('Waveforms') #pylab.subplot(2,3,6) for i in range(0, self.nPhases): self.fftPlt.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(ta.n_times, self.DF[:,5,5].view(ndarray)) #pylab.plot(self.DF[:,i*55+20, 60]) #pylab.hold('on') #pylab.title('FFTs') print "plotmaps Block 2" if mode == 1 and target > 1: #pylab.subplot(2,3,2) #pylab.title('Amplitude Map2') #scipy.ndimage.gaussian_filter(self.amplitudeImage2, 2, order=0, output=self.amplitudeImage2, mode='reflect') ampImg2 = scipy.ndimage.gaussian_filter(self.amplitudeImage2,gfilt, order=0, mode='reflect') #imga2 = pylab.imshow(ampImg2) #self.amp2View.addItem(pg.ImageItem(ampImg2)) self.amp2 = pg.image(ampImg2, title='Amplitude Map 2', levels=(0.0, max1)) #imga2.set_clim = (0.0, max1) #pylab.colorbar() #pylab.subplot(2,3,5) phaseImg2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0,mode='reflect') #self.phase2View.addItem(pg.ImageItem(phaseImg2)) self.phs2 = pg.image(phaseImg2, title="Phase Map 2", levels=(-np.pi/2.0, np.pi/2.0)) #imgp2 = pylab.imshow(phaseImg2, cmap=matplotlib.cm.hsv) #pylab.colorbar() #imgp2.set_clim=(-numpy.pi/2.0, numpy.pi/2.0) #pylab.title('Phase Map2') ### doubled phase map #pylab.subplot(2,3,6) #scipy.ndimage.gaussian_filter(self.phaseImage2, 2, order=0, output=self.phaseImage2, mode='reflect') np1 = scipy.ndimage.gaussian_filter(self.phaseImage1, gfilt, order=0, mode='reflect') np2 = scipy.ndimage.gaussian_filter(self.phaseImage2, gfilt, order=0, mode='reflect') dphase = (np1 + np2)/2 print 'shape of dphase', dphase.shape #dphase = self.phaseImage1 - self.phaseImage2 print 'min phase', np.amin(dphase) print 'max phase', np.amax(dphase) # for i in range(dphase.shape[0]): # for j in range(dphase.shape[1]): # #for k in range(dphase.shape[2]): # if dphase[i,j]<0: # dphase[i,j] = dphase[i,j]+2*np.pi print 'min phase', np.amin(dphase) print 'max phase', np.amax(dphase) self.win = pg.GraphicsWindow() view = self.win.addViewBox() view.setAspectLocked(True) item = pg.ImageItem(dphase) view.addItem(item) item.setLookupTable(lut) item.setLevels([-np.pi,np.pi]) # self.colorlevels = pg.GradientEditorItem() # self.colorlevels.getLookupTable(17) # self.colorlevels.setColorMode('rgb') # self.colorlevels.setOrientation('right') # self.colorlevels.setPos(-10,0) # view.addItem(self.colorlevels) gradlegend = pg.GradientLegend((10,100),(0,0)) #gradlegend.setIntColorScale(0,255) #gradlegend.setGradient(self.creategradient()) gradlegend.setGradient(maps.getGradient()) view.addItem(gradlegend) #self.phiView.addItem(pg.ImageItem(dphase)) self.phi = pg.image(dphase, title="2x Phi map", levels=(-np.pi, np.pi)) #imgpdouble = pylab.imshow(dphase, cmap=matplotlib.cm.hsv) #pylab.title('2x Phi map') #pylab.colorbar() #imgpdouble.set_clim=(-numpy.pi, numpy.pi) print "plotmaps Block 3" # if mode == 2 or mode == 1: # # if self.phasex == []: # # self.phasex = numpy.random.randint(0, high=D.shape[1], size=D.shape[1]) # # self.phasey = numpy.random.randint(0, high=D.shape[2], size=D.shape[2]) # #pylab.subplot(2,3,3) # sh = D.shape # spr = sh[2]/self.nPhases # wvfms=[] # for i in range(0, self.nPhases): # Dm = self.avgimg[i*spr,i*spr] # diagonal run # wvfms=self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm) # #pylab.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) # self.wavePlt.plot(self.n_times, 100.0*(D[:,self.phasex[i], self.phasey[i]]/Dm)) # #pylab.hold('on') # self.plotlist.append(pg.image(wvfms, title="Waveforms")) # print "it worked" # pylab.title('Waveforms') # print "plotmaps Block 4" if mode == 2: #pylab.subplot(2,3,6) for i in range(0, self.nPhases): #pylab.plot(self.DF[1:,80, 80]) spectrum = np.abs(self.DF)**2 self.fftPlt.plot(spectrum[1:,80,80]) #pyqtgraph.intColor(index, hues=17, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255, **kargs) #self.fftPlt.plot(self.DF[1:,80,80]) ## causing errors and i'm not sure what the desired thing is, Exception: Can not plot complex data types. #pass #pylab.hold('on') # self.plotlist.append(pg.image(wvfms, title="Waveforms")) print "waveform plotting worked" # pylab.title('Waveforms') print "plotmaps Block 4" # if mode == 2: # #pylab.subplot(2,3,6) # for i in range(0, self.nPhases): # #pylab.plot(self.DF[1:,80, 80]) # spectrum = np.abs(self.DF)**2 # self.fftPlt.plot(spectrum[1:,80,80]) # #pyqtgraph.intColor(index, hues=17, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255, **kargs) # #self.fftPlt.plot(self.DF[1:,80,80]) ## causing errors and i'm not sure what the desired thing is, Exception: Can not plot complex data types. # #pass # #pylab.hold('on') # #pylab.title('FFTs') # print "plotmaps Block 5" # print "plotting complete" return
""" Display a plot and an image with minimal setup. pg.plot() and pg.image() are indended to be used from an interactive prompt to allow easy data inspection (but note that PySide unfortunately does not call the Qt event loop while the interactive prompt is running, in this case it is necessary to call QApplication.exec_() to make the windows appear). """ import PySide import numpy as np import pyqtgraph as pg arr_i = np.arange(400 * 400).reshape(400, 400) pg.image(arr_i, title="Simplest possible image example") ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
#!/usr/bin/python import numpy as np import pyqtgraph as pg import sys #from IPython import embed data1_path = sys.argv[1] data2_path = sys.argv[2] data1 = np.load(data1_path) data2 = np.load(data2_path) quotient = data1 / data2 pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') imv = pg.image(quotient, title = data1_path+"/"+data2_path) imv.ui.normBtn.hide() ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_() #embed() # to call ipython
import pyqtgraph as pg def func(): time.sleep(2) img[100:1000,100:1000] = 0 #shit.setImage(qim.ndarray) shit.updateImage() QtGui.qApp.processEvents() # update print("image changed, try minimizing and then maximazing") t = threading.Thread(target=func) win_main = QtGui.QMainWindow() img = loadcv(path) qim = np2qi(img) uimain = thiswin(qim) uimain.show() axes = None if img.ndim == 3: if img.shape[2] <= 4: axes = {'t': None, 'x': 2, 'y': 1, 'c': 0} else: axes = {'t': 2, 'x': 1, 'y': 0, 'c': None} if axes: print("sending with axes") shit = pg.image(img) else: shit = pg.image(img) t.start() sys.exit(app.exec_())
xd = xd[w] yd = yd[w] data = data[w] xi,yi = np.array(np.meshgrid(xbins,ybins,indexing='ij')) zi = xi*0 zi[xd,yd] = data return zi prefix = "data/ISCCP.DX.0.GOE-7.1991.01.01." times = np.arange(0,22,3)*100 xbins = np.arange(501) ybins = np.arange(501) zi = np.zeros((len(times),501,501)) for i in np.arange(len(times)): print "Time # {}".format(times[i]) filename = "{:s}{:04d}.AES".format(prefix,times[i]) stdat = pydx.dxread(filename) irads = np.array([o.irad for o in stdat.dxs1s]) zi[i,:,:] = pos2Grid(stdat.x,stdat.y,irads,xbins=xbins,ybins=ybins) zi = zi[:,:,::-1] #3d image plots as time series, use scroll bar to cycle through images pg.image(zi) #1 day average of cloud cover zavg = np.average(zi,axis=0) pg.image(zavg)
# draw photon positions from PSFsigma deviation photonPosition = particlePosition + PhotonDeviations[ startFrameEmission:cc] # throw out photons that are outside the ROI photonPosition = photonPosition[photonPosition[:, 0] > 0] photonPosition = photonPosition[photonPosition[:, 1] > 0] photonPosition = photonPosition[photonPosition[:, 0] < sz[1]] photonPosition = photonPosition[photonPosition[:, 1] < sz[2]] frameCoordinates = [ np.mean(photonPosition[:, 0]), np.mean(photonPosition[:, 1]), tt, len(photonPosition) ] # put photon averages into the simulated tracks and localization structures SimLocalizations.append(frameCoordinates) SimTracks[-1].append(frameCoordinates) # paint the motorPhotons movie pixelPosition = photonPosition.astype(int) for py, px in pixelPosition: motorPhotons[tt, py, px] += 1 # create poisson-like realization of the background bgRealization = prng.poisson(bg) finalImage = WhiteNoiseSigma * prng.randn(sz[0], sz[1], sz[2]) + bgRealization + motorPhotons # sum motor photons with a poisson-realization of the background movie pg.image(finalImage) if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
import pyqtgraph as pg from tomoCam import gpuGridrec num_slice = 50 im_size = 512 #2560 #A n X n X n volume sino_center = im_size / 2 #1280 num_angles = 512 #1024 gpu_device = 2 oversamp_factor = 1.5 num_iter = 150 p = 1.2 sigma = .1 obj = tomopy.shepp3d((num_slice, im_size, im_size)) # Generate an object. theta = tomopy.angles(num_angles) # Generate uniformly spaced tilt angles. pg.image(obj) pg.QtGui.QApplication.exec_() ### Comparing to tomopy tomo = tomopy.project(obj, theta) proj_dim = tomo.shape[2] tomo = tomo[:, :, proj_dim / 2 - im_size / 2:proj_dim / 2 + im_size / 2] pg.image(tomo) pg.QtGui.QApplication.exec_() ################## GPU MBIR ###################### input_params = {} input_params['gpu_device'] = gpu_device input_params['oversamp_factor'] = oversamp_factor input_params['num_iter'] = num_iter input_params['fbp_filter_param'] = 0.5 t = time.time() rec_gridrec = gpuGridrec(tomo, theta, sino_center, input_params)