Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
test_tifffile(path, settings.verbose)
return 0
if any(i in path for i in '?*'):
path = glob.glob(path)
if not path:
print('no files match the pattern')
return 0
# TODO: handle image sequences
#if len(path) == 1:
path = path[0]
print("Reading file structure...", end=' ')
start = time.time()
try:
tif = TiffFile(path, multifile=not settings.nomultifile)
except Exception as e:
if settings.debug:
raise
else:
print("\n", e)
sys.exit(0)
print("%.3f ms" % ((time.time()-start) * 1e3))
if tif.is_ome:
settings.norgb = True
images = [(None, tif[0 if settings.page < 0 else settings.page])]
if not settings.noplot:
print("Reading image data... ", end=' ')
notnone = lambda x: next(i for i in x if i is not None)
start = time.time()
:rtype: dict
"""
s = "::: getting 'Bedmap 2' data from DataFactory :::"
print_text(s, DataFactory.color)
global home
direc = home + '/antarctica/bedmap2/'
B = TiffFile(direc + 'bedmap2_bed.tif')
S = TiffFile(direc + 'bedmap2_surface.tif')
H = TiffFile(direc + 'bedmap2_thickness.tif')
mask = TiffFile(direc + 'bedmap2_icemask_grounded_and_shelves.tif')
rock_mask = TiffFile(direc + 'bedmap2_rockmask.tif')
b_uncert = TiffFile(direc + 'bedmap2_grounded_bed_uncertainty.tif')
coverage = TiffFile(direc + 'bedmap2_coverage.tif')
gl04c_WGS84 = TiffFile(direc + 'gl04c_geiod_to_WGS84.tif')
B = B.asarray()
S = S.asarray()
H = H.asarray()
mask = mask.asarray()
rock_mask = rock_mask.asarray()
b_uncert = b_uncert.asarray()
coverage = coverage.asarray()
gl04c_WGS84 = gl04c_WGS84.asarray()
# format the mask for cslvr :
mask[mask == 1] = 2
mask[mask == 0] = 1
mask[mask == 127] = 0
def tiff2png(main, filenames=None):
if filenames is None:
filenames = utils.getFilenames('Load TIFF files',
[('Tiff files', '.tiff'),
('Tif files', '.tif')],
main.recWidget.folderEdit.text())
for filename in filenames:
with tiff.TiffFile(filename) as tt:
arr = tt.asarray()
cmin, cmax = bestLimits(arr)
arr[arr > cmax] = cmax
arr[arr < cmin] = cmin
arr -= arr.min()
arr = arr/arr.max()
arr = imresize(arr, (1000, 1000), 'nearest')
im = Image.fromarray(cm.cubehelix(arr, bytes=True))
im.save(os.path.splitext(filename)[0] + '.png')
def combine_stacks(ch0, ch1, darkavg):
"""Read tifs into two large stacks ...
#TODO: see if we do this sequentially to minimize the amount of RAM required
"""
shp = list(tf.TiffFile(ch0[0]).series[0].shape)
nZ = shp[0]
shp[0] *= len(ch0)
pre = np.zeros(shp, dtype=np.float)
post = np.zeros(shp, dtype=np.float)
for n in range(len(ch0)):
pre[n * nZ : n * nZ + nZ, :, :] = tf.imread(ch0[n]).astype(np.float) - darkavg
post[n * nZ : n * nZ + nZ, :, :] = tf.imread(ch1[n]).astype(np.float) - darkavg
return pre, post
def dims(self) -> str:
if self._dims is None:
# Get a single scenes dimensions in order
with TiffFile(self._file) as tiff:
single_scene_dims = tiff.series[0].pages.axes
# We can sometimes trust the dimension info in the image
if all([d in Dimensions.DefaultOrder for d in single_scene_dims]):
# Add scene dimension only if there are multiple scenes
if len(tiff.series) == 1:
self._dims = single_scene_dims
else:
self._dims = f"{Dimensions.Scene}{single_scene_dims}"
# Sometimes the dimension info is wrong in certain dimensions, so guess
# that dimension
else:
guess = self.guess_dim_order(tiff.series[0].pages.shape)
best_guess = []
for dim_from_meta in single_scene_dims:
if dim_from_meta in Dimensions.DefaultOrder:
else:
kwargs_file['multifile'] = True
kwargs_seq = {}
if 'pattern' in kwargs:
kwargs_seq['pattern'] = kwargs['pattern']
del kwargs['pattern']
if isinstance(files, basestring) and any(i in files for i in '?*'):
files = glob.glob(files)
if not files:
raise ValueError('no files found')
if len(files) == 1:
files = files[0]
if isinstance(files, basestring):
with TiffFile(files, **kwargs_file) as tif:
return tif.asarray(*args, **kwargs)
else:
with TiffSequence(files, **kwargs_seq) as imseq:
return imseq.asarray(*args, **kwargs)
def __init__(self, files, imread=TiffFile, pattern='axes'):
"""Initialize instance from multiple files.
Parameters
----------
files : str, or sequence of str
Glob pattern or sequence of file names.
imread : function or class
Image read function or class with asarray function returning numpy
array from single file.
pattern : str
Regular expression pattern that matches axes names and sequence
indices in file names.
"""
if isinstance(files, basestring):
files = natural_sorted(glob.glob(files))
potts_area = 25
Beta_P = torch.from_numpy(np.array([2.7], dtype=np.float)).to(device).float()
C_prior = 50
ALPHA_MS = 2675 + 25*add_splits
ALPHA_MS2 = 0.0001
LOG_ALPHA_MS2 = -26.2
global TIF
if TIF:
import tifffile
with tifffile.TiffFile(IMAGE1) as tif:
h_tif,w_tif = tif.pages[0].asarray().shape
TIF_C = len(tif.pages)
frame0 = np.zeros((h_tif,w_tif,TIF_C))
meta_data = tif.imagej_metadata
for c in range(len(tif.pages)):
frame0[:,:,c] = tif.pages[c].asarray()
else:
frame0 = np.array(Image.open(IMAGE1).convert('RGB'))
TIF_C = 3
HEIGHT, WIDTH, _ = frame0.shape
dx = np.array([[-1 / 12, 8 / 12, 0, -8 / 12, 1 / 12]])
"""
def openFile(self):
"""
open a file for reading
"""
self.fp = tifffile.TiffFile(self.fn)
self.handle = self.fp.filehandle
self.readHeader()
def get_image_description_SI(fname:str) -> List:
"""Given a tif file acquired with Scanimage it returns a dictionary containing the information in the image description field
Args:
fname: name of the file
Returns:
image_description: information of the image
"""
image_descriptions = []
tf = TiffFile(fname)
for idx, pag in enumerate(tf.pages):
if idx % 1000 == 0:
logging.debug(idx) # progress report to the user
field = pag.tags['image_description'].value
image_descriptions.append(si_parse(field))
return image_descriptions