Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
for ind, coor in enumerate(patch_coors):
ph, pw = coor[0], coor[1]
pred_map[ph:ph+args.patch_len, pw:pw+args.patch_len] += preds[ind]
ttl_samples += inputs.size(0)
prob_pred = np.divide(pred_map, wmap)
slide_pred = (prob_pred > 0.5).astype(np.uint8)
pred_save_path = os.path.join(result_dir, cur_slide + "_" + args.tumor_type + ".tif")
io.imsave(pred_save_path, slide_pred*255)
if args.save_org and args.tumor_type == "viable":
org_w, org_h = wsi_head.level_dimensions[0]
org_pred = transform.resize(prob_pred, (org_h, org_w))
org_pred = (org_pred > 0.5).astype(np.uint8)
org_save_path = os.path.join(org_result_dir, cur_slide[-3:] + ".tif")
imsave(org_save_path, org_pred, compress=9)
time_elapsed = time.time() - since
print('Testing takes {:.0f}m {:.2f}s'.format(time_elapsed // 60, time_elapsed % 60))
def write_multipage_tiff(x,ofn,descr=None,tags=(),verbose=0):
""" uses ZIP compression
writes all frames at once
note: using TiffWriter class, you can
APPEND write TIFF
FRAME BY FRAME
see source code for more detail, search for
class TiffWriter
https://github.com/blink1073/tifffile/blob/master/tifffile.py
"""
if verbose>0: print('write_mulitpage_tiff: description to write: {}'.format(descr))
try:
tifffile.imsave(ofn,x,compress=6,
#photometric='minisblack', #not for color
description=descr,
extratags=tags)
except Exception as e:
print('tifffile had a writing problem with {} {} '.format(ofn,e))
z = 50
dim_x = 400
dim_y = 400
dim_z = 10
out_images = np.zeros((dim_z,1024,1024), dtype=images.dtype)
out_labels = np.zeros((dim_z,1024,1024), dtype=labels.dtype)
out_segs = np.zeros((dim_z,1024,1024), dtype=segs.dtype)
out_images[0:dim_z, y:y+dim_y, x:x+dim_x] = images[z:z+dim_z, y:y+dim_y, x:x+dim_x]
out_labels[0:dim_z, y:y+dim_y, x:x+dim_x] = labels[z:z+dim_z, y:y+dim_y, x:x+dim_x]
out_segs[0:dim_z, y:y+dim_y, x:x+dim_x] = segs[z:z+dim_z, y:y+dim_y, x:x+dim_x]
tif.imsave('cut-train-input.tif', out_images)
tif.imsave('cut-train-labels.tif', out_labels)
tif.imsave('cut-train-segs.tif', out_segs)
# store separate slices
shutil.rmtree('segs',True)
os.mkdir('segs')
for z in range(dim_z):
tif.imsave('segs/'+str(z)+'.tif',out_segs[z].astype(np.uint32))
shutil.rmtree('images',True)
os.mkdir('images')
for z in range(dim_z):
tif.imsave('images/'+str(z)+'.tif',out_images[z])
shutil.rmtree('truth',True)
os.mkdir('truth')
for z in range(dim_z):
def write_tiff_image(filename, image, compress=False):
""" Write image data to TIFF file
:param filename: name of file to write data to
:type filename: str
:param image: image data to write to file
:type image: numpy array
:param compress: whether to compress data. If `True`, lzma compression is used. Default is `False`
:type compress: bool
"""
if compress:
return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks
return tiff.imsave(filename, image)
sendQueueOrPrint(status_queue, 'Writing tiff file...', base_name)
try:
# Requires the installation of freeimage library.
# On mac is trivial using brew (brew install freeimage),
# but i am not sure how to do it on windows
from skimage.io._plugins import freeimage_plugin as fi
# the best way I found to write lzw compression on python
fi.write_multipage(I_worms, tiff_file, fi.IO_FLAGS.TIFF_LZW)
except:
import tifffile # pip intall tifffile
# For some reason gzip compression appears as an inverted image in
# preview (both windows and mac), but it is read correctly in ImageJ
tifffile.imsave(tiff_file, I_worms, compress=4)
sendQueueOrPrint(status_queue, 'Tiff file done.', base_name)
def save_roi_tifs(rois, file_names, directory):
'''Save ROIs as tif files'''
directory = add_pathsep(directory)
for i, roi in enumerate(rois):
roi = roi.max(axis=0)
roi_name = directory + file_names[i] + "_ROI.tif"
tifffile.imsave(roi_name, roi)
def collate():
# We assume that there are two directories, the first with xy correction
# only and the second with xyz correction.
#
# Make 2D images of the drift corrected data.
if False:
for adir in ["test_01/", "test_02/"]:
im = hdf5ToImage.render2DImage(adir + "test.hdf5", sigma = 0.5)
tifffile.imsave(adir + "test_im_2d.tif", im.astype(numpy.float32))
# Make 3D images of the drift corrected data.
if False:
z_edges = numpy.arange(-0.5, 0.55, 0.1)
for adir in ["test_01/", "test_02/"]:
images = hdf5ToImage.render3DImage(adir + "test.hdf5", z_edges, sigma = 0.5)
with tifffile.TiffWriter(adir + "test_im_3d.tif") as tf:
for elt in images:
tf.save(elt.astype(numpy.float32))
# Measure error in drift measurements.
if True:
print("Drift correction RMS error (nanometers):")
for i, elt in enumerate(["drift_xy.txt", "drift_xyz.txt"]):
print(" ", elt)
zmn = [[1.3, 2, 2]]
#zmn = [[1, 0, 4]]
#zmn = []
pf = geo.createFromZernike(1.0, zmn)
z_values = numpy.arange(-z_range, z_range + 0.5 * z_pixel_size, z_pixel_size)
psfs = geo.pfToPSF(pf, z_values)
#xy_size = 2.0*psfs.shape[0]
xy_size = 100
xy_start = int(0.5 * (psfs.shape[1] - xy_size) + 1)
xy_end = int(xy_start + xy_size)
psfs = psfs[:,xy_start:xy_end,xy_start:xy_end]
if True:
tifffile.imsave("kz.tif", numpy.real(geo.kz).astype(numpy.float32))
if False:
tifffile.imsave("pf_abs.tif", numpy.abs(pf).astype(numpy.float32))
tifffile.imsave("pf_angle.tif", (180.0 * numpy.angle(pf)/numpy.pi + 180).astype(numpy.float32))
if False:
with tifffile.TiffWriter(sys.argv[1]) as psf_tif:
temp = (psfs/numpy.max(psfs)).astype(numpy.float32)
psf_tif.save(temp)
if False:
with open("z_offset.txt", "w") as fp:
for i in range(z_values.size):
fp.write("1 {0:.6f}\n".format(1000.0 * z_values[i]))
if False:
# Replace : with -
name = name.replace(':', ' -')
yml_dict = self.get_yml_dict(name, description, authors, test_img, axes, patch_shape=patch_shape)
yml_file = self.logdir / 'model.yaml'
'''default_flow_style must be set to TRUE in order for the output to display arrays as [x,y,z]'''
yaml = YAML(typ='rt')
yaml.default_flow_style = False
with open(yml_file, 'w') as outfile:
yaml.dump(yml_dict, outfile)
input_file = self.logdir / 'testinput.tif'
output_file = self.logdir / 'testoutput.tif'
imsave(input_file, test_img)
imsave(output_file, test_output)
with ZipFile(fname, 'a') as myzip:
myzip.write(yml_file, arcname=os.path.basename(yml_file))
myzip.write(input_file, arcname=os.path.basename(input_file))
myzip.write(output_file, arcname=os.path.basename(output_file))
print("\nModel exported in BioImage ModelZoo format:\n%s" % str(fname.resolve()))