def readTif(fname=''): if fname == '': fname = getFilename(filter="All files (*.*);;TIF Files (*.tif)") if not os.path.isfile(fname): raise Exception("No File Selected") tif = tifffile.TIFFfile(fname).asarray().astype(np.float32) img = np.squeeze(tif) return img
def read_tiffstack(path): """ converts a tiff stack (image x y dimensions, individual tiff pages t) into a 3d np array, dimensions are (x,y,t)""" data = tifffile.TIFFfile(path).asarray() data = data.swapaxes( 0, 2) # moves t to last dim. tifffile reads pages as first dim return data
def check(ftype, fname): if ftype in StackedTifImages.ftypes: try: tif = tff.TIFFfile(str(fname)) #try to extract labels names set by imageJ: tif.pages[0].imagej_tags['labels'] return True except (AttributeError, KeyError): #not an imageJ stack return False
def shift(file, shift_x, shift_y): fullname = os.path.join(dirname, file) print "shifting image", fullname tiffimg = tff.TIFFfile(fullname) img = tiffimg.asarray() img = numpy.roll(img, shift_x, axis=1) img = numpy.roll(img, shift_y, axis=2) shiftedname = os.path.join(dirname, "shifted_" + file) tff.imsave(shiftedname, img)
def run(self): if self.filename.endswith(('.tif', '.nd2', '.nih', '.stk')): image = tifffile.TIFFfile(self.filename).asarray().astype( np.float32) image = np.squeeze(np.swapaxes(image, 2, 1)) elif self.filename.endswith(('.jpg', '.png')): image = imread(self.filename).swapaxes(0, 1) elif self.filename.endswith(('.npy', '.npz')): image = np.load(self.filename) if simage.ndim == 2 and image.shape[0] > image.shape[1]: image = self.image.transpose() self.done.emit(image) del image self.terminate()
def open(self, filename): prefs = self.preferences #OPEN tif = tff.TIFFfile(str(filename)) img = tif.asarray() #due to different conventions: img = transpose(img) #crop if prefs.pCrop.value(): r = (prefs.pCropX0.value(), prefs.pCropX1.value(), prefs.pCropY0.value(), prefs.pCropY1.value()) img = img[r[0]:r[1], r[2]:r[3]] #resize if prefs.pResize.value(): img = cv2.resize(img, (prefs.pResizeX.value(), prefs.pResizeY.value())) img = self.toFloat(img) try: #try to extract labels names set by imageJ: labels = tif.pages[0].imagej_tags['labels'] #remove surplus information: for n, l in enumerate(labels): try: i = l.index('\n') if i != -1: labels[n] = l[:i] except ValueError: #no \n in label pass except AttributeError: if img.ndim == 3: #color image labels = [str(r) for r in range(len(img))] else: labels = None tif.close() return img, labels
def ReadBitmapViaTIFFfile(data): import tifffile from cStringIO import StringIO im = tifffile.TIFFfile(StringIO(data)) imdata = im.asarray(squeeze=True) if imdata.dtype == np.uint16: if np.max(imdata) < 4096: imdata = imdata.astype(np.float32) / 4095. else: imdata = imdata.astype(np.float32) / 65535. if imdata.ndim == 3: # check if channels are identical: # if so return only the first # if not, separate the channels into a list if (np.any(imdata[0] != imdata[1]) or np.any(imdata[0] != imdata[2])): imdata = [imdata[0], imdata[1], imdata[2]] else: imdata = imdata[0] return imdata
def beamProfile(ask, folder=None, shape=(512, 512), th=None): stacks, folder = loadStacks(ask, folder) n = len(stacks) profile = np.zeros(shape) norm = 0 for filename in stacks: print(os.path.split(filename)[1]) if filename.endswith('.hdf5'): stack = Stack(filename=filename) meanFrame = stack.imageData.mean(0) stack.close() else: tfile = tiff.TIFFfile(filename) meanFrame = tfile.asarray() tfile.close() # Normalization meanInt = meanFrame.mean() profile += meanFrame / meanInt norm += meanInt norm /= n # 2D fitting of profile try: profileFit = twoDSymmGaussian(profile) popt, epopt = profileFit.popt, profileFit.epopt except RuntimeError as err: print("Fitting error: {0}".format(err)) print("Using sigma = 256.") popt, epopt = [0, 0, 0, 256.0], [0, 0, 0, 0] # We return the profile, normalization value, sigma and its error return profile, norm, (popt[3], epopt[3]), folder
def loadfile(maingui): # remove old figures if there are any try: maingui.tiffFig.traceFig.deleteLater() maingui.tiffFig.responseFig.deleteLater() maingui.roi_table.deleteLater() maingui.rmax_by_sfreq.deleteLater() except Exception: pass settings = maingui.settings #### get conditions from ED #### d = getInfoFromPath(settings.d['filename']) maingui.persistant = dict() maingui.persistant['experimenter_id'] = d['experimenter_id'] maingui.persistant['date'] = d['datestr'] maingui.persistant['mouse_id'] = d['mouse_id'] maingui.persistant['filename'] = d['filename'] if d is False: #if there was an error loading the conditions file maingui.conditions = None else: maingui.conditions = getConditions( experimenter_id=d['experimenter_id'], date=d['datestr'], mouse_id=d['mouse_id'], filename=d['filename']) ### try loading previous results from ED ### ids = [ maingui.persistant['mouse_id'], maingui.persistant['experimenter_id'], maingui.persistant['date'], maingui.persistant['filename'] ] db.config['database'] = 'ed' ans = db.execute( "SELECT data, id FROM analysis2p WHERE mouse_id=%s AND experimenter_id=%s AND date=%s and filename=%s", tuple(ids)) db.config['database'] = 'glams' if len(ans) > 0: old_persistant = pickle.loads(ans[0][0]) maingui.persistant = dict(maingui.persistant.items() + old_persistant.items()) maingui.persistant['id'] = ans[0][1] print('Found persistent data on ED') else: maingui.persistant['id'] = None maingui.persistant = dict(maingui.persistant.items() + dict.fromkeys( ['motionVectors', 'ROIs', 'neuropil_radius', 'alpha']).items()) print( 'Persistent data on ED not found. This file has not been loaded into ceilingfaan before.' ) maingui.statusBar().showMessage('Loading tiff') t = time.time() tif = tifffile.TIFFfile(settings.d['filename']) tiffstack = tif.asarray() tif.close() tiffstack = np.transpose(tiffstack, (0, 2, 1)) maingui.statusBar().showMessage( 'Tiff successfully loaded ({} s)'.format(time.time() - t)) maingui.roi_table = roi_table.make_widget(maingui, show=True) maingui.rmax_by_sfreq = TuningCurveCanvas((536, 33, 446, 300)) maingui.rmax_by_sfreq.show() maingui.stats = StatsWindow.from_geo(maingui, 680, 373, 230, 660) maingui.stats.show() # maingui.rmax_by_sfreq = RMaxBySpatialFrequencyFig() # maingui.rmax_by_sfreq.show() ## maingui.npplot = maingui.neuropil_mask.addPlot() ## maingui.npplot.hideAxis('left') ## maingui.npplot.hideAxis('bottom') ########################################################## # Injected by Hyungtae Kim <*****@*****.**>, in Nov 2014, Feb 2015 # organize a menu to select a specific frequency based on conditions. # def on_tfreq_change(maingui, agroup): checked = agroup.checkedAction() checked_index = agroup.children().index(checked) maingui.tiffFig.temporal_frequency_changed(checked_index) def on_sfreq_change(maingui, agroup): checked = agroup.checkedAction() checked_index = agroup.children().index(checked) maingui.tiffFig.spatial_frequency_changed(checked_index) sf_agroup = maingui.sfreq_action_group sf_handler = partial(on_sfreq_change, maingui, sf_agroup) tf_agroup = maingui.tfreq_action_group tf_handler = partial(on_tfreq_change, maingui, tf_agroup) for action in sf_agroup.children(): sf_agroup.removeAction(action) for action in tf_agroup.children(): tf_agroup.removeAction(action) if maingui.conditions: maingui.sfreq_meta = SpatialFrequencyMeta(maingui.conditions) for index, text in enumerate(map(str, maingui.sfreq_meta.sfrequencies)): if_first = not index action = QAction(text, sf_agroup, checkable=True, checked=if_first) sf_agroup.addAction(action) maingui.sfreq_menu.addAction(action) action.triggered[()].connect(sf_handler) for index, text in enumerate(map(str, maingui.sfreq_meta.tfrequencies)): if_first = not index action = QAction(text, tf_agroup, checkable=True, checked=if_first) tf_agroup.addAction(action) maingui.tfreq_menu.addAction(action) action.triggered[()].connect(tf_handler) else: maingui.sfreq_meta = None channels = [] if settings.d['nChannels'] == 1: channels.append(tiffstack) (mt, my, mx) = shape(channels[0]) tiffstack = np.concatenate( (channels[0][..., np.newaxis], np.zeros((mt, my, mx, 2))), axis=3) #this always assumes the only color is green elif settings.d['nChannels'] == 2: channels.append(tiffstack[0::2]) channels.append(tiffstack[1::2]) (mt, my, mx) = shape(channels[0]) arr1 = channels[0][..., np.newaxis] arr2 = channels[1][..., np.newaxis] arr3 = np.zeros((mt, my, mx, 1)) tiffstack = np.concatenate( (arr1, arr2, arr3), axis=3) #this always assumes the only two colors are red and green elif settings.d['nChannels'] == 3: channels.append(tiffstack[0::3]) channels.append(tiffstack[1::3]) channels.append(tiffstack[2::3]) tiffstack = np.concatenate( (channels[0][..., np.newaxis], channels[1][..., np.newaxis], channels[2][..., np.newaxis]), axis=3 ) #this always assumes the only three colors are red,green, and blue in that order COI = channels[settings.d['channelOfInterest'] - 1] #channel of interest (mt, my, mx) = shape(COI) if settings.d['motionCorrect']: #True or False depending on user settings maingui.statusBar().showMessage('Performing motion correction...') t = time.time() if maingui.persistant['motionVectors'] is None: print 'motion vector not found, get drift !' maingui.persistant['motionVectors'] = getdrift3(COI) print 'driftcorrect...', tiffstack = driftcorrect(tiffstack, maingui.persistant['motionVectors']) print 'done !' maingui.statusBar().showMessage( 'Finished motion correction ({} seconds)'.format(time.time() - t)) else: maingui.statusBar().showMessage('Motion Correction is Off') maingui.persistant['motionVectors'] = None tiffFig = TiffFig( tiffstack, maingui ) # activates the movie display window and the response analysis windows # SPG 072414 writes out motion corrected file to matlab where we can save each channel as a tifstack. replace this with python # code once we figure out which python TIFF writer to use # if settings.d['saveMotionCorrectedTIFF']==True: # # tiffstack.save(settings.d['filename']+'motionCorrected.tif') # # tifffile.imsave(settings.d['filename']+'motionCorrected.tif',tiffstack, compress=6) # matd=dict(); # matd['tiffStack']=tiffstack; # scipy.io.savemat(settings.d['filename']+'motionCorrected.tif',matd); return tiffFig
def loadTiff(filename, frame=0): import tifffile tf = tifffile.TIFFfile(filename) rv = tf[frame].asarray() return rv
# basic handling of tiff 2D and 3D images # import tif and convert to numpy array # then visualize using mayavi2 #import os #import sys from mayavi import mlab #sys.path.append('C:\\dropbox\\My Dropbox\\codes\\python') import tifffile as tff #blobs.tif is a 2D sample image #tiffimg = tff.TIFFfile('D:/examples/blobs.tif') #tiffimg = tff.TIFFfile('D:/examples/g1f.tif') tiffimg = tff.TIFFfile('D:/examples/flybrain3DG.tif') tiffimg2 = tff.TIFFfile('D:/examples/flybrain3DR.tif') imgarray = tiffimg.asarray() imgarray2 = tiffimg2.asarray() sc =mlab.pipeline.scalar_field(imgarray) sc2 =mlab.pipeline.scalar_field(imgarray2) sc.spacing = [2, 1, 1] sc2.spacing = [2, 1, 1] sc.update_image_data = True sc2.update_image_data = True # showing 3D stack image ##imgw = mlab.pipeline.volume(sc) imgw2 = mlab.pipeline.volume(sc2) imgw = mlab.pipeline.volume(sc) # setting color transfer function
# basic handling of tiff 2D and 3D images # import tif and convert to numpy array # then visualize using mayavi2 #import os #import sys from mayavi import mlab #sys.path.append('C:\\dropbox\\My Dropbox\\codes\\python') import tifffile as tff #blobs.tif is a 2D sample image #tiffimg = tff.TIFFfile('D:/examples/blobs.tif') tiffimg = tff.TIFFfile('D:/examples/g1f.tif') #tiffimg = tff.TIFFfile('D:\\examples\\flybrain3DG.tif') #tiffimg = tff.TIFFfile('D:/examples/flybrain3DG.tif') imgarray = tiffimg.asarray() # showing 2D array (blobs) as a 2D plot in mayavi. imgwin = mlab.imshow(imgarray, colormap="gist_earth") # showing 3D stack image #mlab.pipeline.volume(mlab.pipeline.scalar_field(imgarray))
def __init__(self, filename, taskQueue=None, chanNum=0, series=0): self.filename = getFullExistingFilename( filename) #convert relative path to full path self.chanNum = chanNum self.RGB = False #self.data = readTiff.read3DTiff(self.filename) #self.im = Image.open(filename) #self.im.seek(0) #PIL's endedness support is subtly broken - try to fix it #NB this is untested for floating point tiffs #self.endedness = 'LE' #if self.im.ifd.prefix =='MM': # self.endedness = 'BE' #to find the number of images we have to loop over them all #this is obviously not ideal as PIL loads the image data into memory for each #slice and this is going to represent a huge performance penalty for large stacks #should still let them be opened without having all images in memory at once though #self.numSlices = self.im.tell() #try: # while True: # self.numSlices += 1 # self.im.seek(self.numSlices) #except EOFError: # pass print((self.filename)) if local_tifffile: logger.info( 'Using PYMEs built-in, old version of tifffile, better support for ImageJ tiffs can be had with the more recent pip version (`pip install tifffile`)' ) tf = tifffile.TIFFfile(self.filename) else: tf = tifffile.TiffFile(self.filename) self.tf = tf # keep a reference for debugging print(tf.series[series].shape) self.im = tf.series[series].pages axisOrder = 'XYZTC' size_z = len(self.im) size_c, size_t = 1, 1 if tf.is_ome or ((not local_tifffile)): #print('Detected OME TIFF') sh = {'Z': 1, 'T': 1, 'C': 1} _axes = tf.series[series].axes if 'I' in _axes: logger.info('Tiff file does not fully specify axes (axes=%s)' % (_axes.replace('I', '?')[::-1])) if 'Z' not in _axes: logger.info('Assuming unknown axis is Z' ) # TODO - explain how to change axes later _axes = _axes.replace('I', 'Z') elif 'C' not in _axes: logger.info('Assuming unknown axis is C') _axes = _axes.replace('I', 'C') elif 'T' not in _axes: logger.info('Assuming unkown axis is T') _axes = _axes.replace('I', 'T') else: logger.warning( 'Unknown axis with all standard axes defined - data might not read correctly' ) sh.update(dict(zip(_axes, tf.series[0].shape))) logger.debug('sh = %s' % sh) size_c = sh['C'] size_z = sh['Z'] size_t = sh['T'] axisOrder = _axes[::-1] axisOrder = axisOrder + ''.join( [a for a in ['Z', 'T', 'C'] if not a in axisOrder]) logger.debug('raw TIFF axisOrder = %s' % axisOrder) #self.additionalDims = ''.join([a for a in axisOrder[2:] if sh[a] > 1]) elif tf.is_rgb: print( 'WARNING: Detected RGB TIFF - data not likely to be suitable for quantitative analysis' ) size_c = 3 self.RGB = True if len(self.im) > 1: # we can have multi-page RGB TIFF - why????? print( 'WARNING: Multi-page RGB TIFF detected - where did this come from???' ) axisOrder = 'XYCZT' size_z = len(self.im) size_t = 1 XYZTCDataSource.__init__(self, input_order=axisOrder, size_z=size_z, size_t=size_t, size_c=size_c) sl0 = self.getSlice(0) self._dtype = sl0.dtype self._shape = [sl0.shape[0], sl0.shape[1], size_z, size_t, size_c]
def read_3dtiff(path): """ missing docstring """ data = tifffile.TIFFfile(path).asarray() data = data.swapaxes(0, 3) data = data[:, 0, :, :] return data
def __init__(self, filename, taskQueue=None, chanNum=0, series=0): self.filename = getFullExistingFilename( filename) #convert relative path to full path self.chanNum = chanNum self.RGB = False #self.data = readTiff.read3DTiff(self.filename) #self.im = Image.open(filename) #self.im.seek(0) #PIL's endedness support is subtly broken - try to fix it #NB this is untested for floating point tiffs #self.endedness = 'LE' #if self.im.ifd.prefix =='MM': # self.endedness = 'BE' #to find the number of images we have to loop over them all #this is obviously not ideal as PIL loads the image data into memory for each #slice and this is going to represent a huge performance penalty for large stacks #should still let them be opened without having all images in memory at once though #self.numSlices = self.im.tell() #try: # while True: # self.numSlices += 1 # self.im.seek(self.numSlices) #except EOFError: # pass print((self.filename)) if local_tifffile: tf = tifffile.TIFFfile(self.filename) else: tf = tifffile.TiffFile(self.filename) self.tf = tf # keep a reference for debugging print(tf.series[series].shape) self.im = tf.series[series].pages axisOrder = 'XYZTC' size_z = len(self.im) size_c, size_t = 1, 1 if tf.is_ome or (not local_tifffile): print('Detected OME TIFF') sh = {'Z': 1, 'T': 1, 'C': 1} sh.update(dict(zip(tf.series[series].axes, tf.series[0].shape))) print('sh = %s' % sh) size_c = sh['C'] size_z = sh['Z'] size_t = sh['T'] axisOrder = tf.series[series].axes[::-1] axisOrder = axisOrder + ''.join( [a for a in ['Z', 'T', 'C'] if not a in axisOrder]) print('axisOrder = ', axisOrder) #self.additionalDims = ''.join([a for a in axisOrder[2:] if sh[a] > 1]) elif tf.is_rgb: print( 'WARNING: Detected RGB TIFF - data not likely to be suitable for quantitative analysis' ) size_c = 3 self.RGB = True if len(self.im) > 1: # we can have multi-page RGB TIFF - why????? print( 'WARNING: Multi-page RGB TIFF detected - where did this come from???' ) axisOrder = 'XYCZT' size_z = len(self.im) size_t = 1 XYZTCDataSource.__init__(self, input_order=axisOrder, size_z=size_z, size_t=size_t, size_c=size_c) sl0 = self.getSlice(0) self._dtype = sl0.dtype self._shape = [sl0.shape[0], sl0.shape[1], size_z, size_t, size_c]
#!/usr/bin/env python import tifffile import sys import numpil import mrc infile = sys.argv[1] outfile = sys.argv[2] tif = tifffile.TIFFfile(infile) a = tif.asarray() print 'MINMAX', a.min(), a.max() mrc.write(a, outfile)
# basic handling of tiff 2D and 3D images # import tif and convert to numpy array # then visualize using mayavi2 #import os import sys from mayavi import mlab sys.path.append('/Users/miura/pylib') import tifffile as tff #blobs.tif is a 2D sample image #tiffimg = tff.TIFFfile('D:/examples/blobs.tif') #tiffimg = tff.TIFFfile('D:/examples/g1f.tif') tiffimg = tff.TIFFfile('/Users/miura/img/flybrainG.tif') imgarray = tiffimg.asarray() sc = mlab.pipeline.scalar_field(imgarray) sc.spacing = [2, 1, 1] sc.update_image_data = True # showing 3D stack image imgw = mlab.pipeline.volume(sc)
def get_image(file_name): if '.tif' in file_name: im = np.float32(tiff.TIFFfile(file_name).asarray()) else: im = np.float32(imread(file_name)) return im
from mayavi import mlab import sys sys.path.append('C:\\python26\\Scripts') import tifffile as tff import tkFileDialog fn = tkFileDialog.askopenfilename() tiffimg = tff.TIFFfile(fn) imgarray = tiffimg.asarray() sc = mlab.pipeline.scalar_field(imgarray) sc.spacing = [2, 1, 1] sc.update_image_data = True #imgw = mlab.pipeline.iso_surface(sc, contours=[imgarray.min()+0.1*imgarray.ptp(),], opacity=0.3) imgw = mlab.pipeline.iso_surface(sc, contours=[ imgarray.min() + 0.1 * imgarray.ptp(), ], opacity=1.0) mlab.show()