class CZI: def __init__(self, path): self.filename = path self.czi = CziFile(path) def getPixelArray(self): im = self.czi.asarray() print('Image Width: {}'.format(im.shape[-1])) print('Image Height: {}'.format(im.shape[-2])) return im[0, 0, 0, ] def cvtStandardImgFormat(self, savePath, fmt, compression=False): im_arr = self.getPixelArray() if fmt.endswith('jpg') and im_arr[0] > 65535 and im_arr[1] > 65535: print('Too Large size for JPEG-2000 format...') return elif fmt.endswith('png') and im_arr[0] > 10000 and im_arr[1] > 10000: print('Too Large size for PNG format...') return fname = os.path.basename(self.filename) sname = os.path.splitext(fname)[-1] im = Image.new_from_array(im_arr) if fmt.endswith('tiff'): if compression: im.write_to_file(savePath + '/' + sname + '.' + fmt, compression='lzw') else: im.write_to_file(savePath + '/' + sname + '.' + fmt, compression='lzw') else: im.write_to_file(savePath + '/' + sname + '.' + fmt)
def read_czi_image(czi_file, channel_names=None): from czifile import CziFile czi_img = CziFile(czi_file) czi_channels = np.transpose(czi_img.asarray()[0, :, 0, :, :, :, 0], (0, 2, 3, 1)) voxelsize = {} for s in czi_img.segments(): if s.SID == "ZISRAWMETADATA": metadata = s.data().split('\n') for i, row in enumerate(metadata): if "Distance Id" in row: s = metadata[i + 1] voxelsize[row.split('"')[1]] = np.around( float(s[s.find('>') + 1:s.find('>') + s[s.find('>'):].find('<')]) * 1e6, decimals=3) voxelsize = tuple([voxelsize[dim] for dim in ['X', 'Y', 'Z']]) n_channels = czi_channels.shape[0] print czi_file.split('/')[-1], " : ", n_channels, " Channels ", voxelsize if n_channels > 1: if channel_names is None: channel_names = ["CH" + str(i) for i in range(n_channels)] img = {} for i_channel, channel_name in enumerate(channel_names): img[channel_name] = SpatialImage(czi_channels[i_channel], voxelsize=voxelsize) else: img = SpatialImage(czi_channels[0], voxelsize=voxelsize) return img
#import matplotlib as plt from matplotlib import pylab as pl import urllib.request import os #fn='/home/pwatkins/Downloads/0.08 lead_continuous 150-50-50-03.czi' #fn = '/data/pwatkins/kara/sample_alignment_data_from_Kara_20180125/2017/training-zebrafish-4-sections/' +\ # 'zebrafish_20171013_10-15-10/003_Region3.czi' url = 'https://keeper.mpdl.mpg.de/f/ec98ecaff5674dfea904/?dl=1' fn = 'face.czi' urllib.request.urlretrieve(url, fn) czi = CziFile(fn) #print(czi.metadata, dir(czi.metadata)) iimg = czi.asarray() print(iimg.shape) os.remove(fn) #shape = np.array(iimg.shape[3:5]) #img = np.zeros(shape//10 + 1,dtype=iimg.dtype) # #for scene in range(iimg.shape[1]): # cimg = np.squeeze(iimg[0,scene,0,:,:,0])[0::10,0::10] # sel = (cimg > 0) # img[sel] = cimg[sel] img = np.squeeze(iimg) interp_string = 'nearest'