def read_lsm(filename,channel=0): """Read an lsm image :Parameters: - `filename` (str) - name of the file to read - `channel` (int) - optional """ # LSM reader imageFile = lsmreader.Lsmimage(filename) imageFile.open() _info = {} #LSM header _VX = imageFile.header['CZ LSM info']['Voxel Size X'] _VY = imageFile.header['CZ LSM info']['Voxel Size Y'] _VZ = imageFile.header['CZ LSM info']['Voxel Size Z'] _vx = _VX * 10**6 _vy = _VY * 10**6 _vz = _VZ * 10**6 _PIXSIZE = imageFile.header['Image'][0]['Bit / Sample'] _info["TYPE"] = 'unsigned fixed' _info["PIXSIZE"] = str(_PIXSIZE) _info["SCALE"] = 2 _info["CPU"] = 'decm' _info["#GEOMETRY"] = 'CARTESIAN' #LSM datas _data = imageFile.image['data'][channel] im = SpatialImage(_data) im.resolution = _vx,_vy,_vz im.info = _info return im
def display (image, palette_name = "grayscale", title = None , color_index_max = None) : """ """ w = SlideViewer() if not isinstance(image,SpatialImage): image = SpatialImage(image) if image.ndim < 3 : image = image.reshape(image.shape + (1,)) if color_index_max is None : cmax = image.max() else : cmax = color_index_max palette = palette_factory(palette_name,cmax) w.set_palette(palette,palette_name) w.set_image(image) w.set_title(title) w.show() return w
def read_lsm_image(lsm_file, channel_names=None): import lsmreader lsm_img = lsmreader.Lsmimage(lsm_file) lsm_img.open() voxelsize = tuple([ float( np.around(lsm_img.header['CZ LSM info']['Voxel Size ' + dim] * 1000000, decimals=3)) for dim in ['X', 'Y', 'Z'] ]) n_channels = len(lsm_img.image['data']) filename = lsm_file.split('/')[-1] print filename, " : ", 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(lsm_img.image['data'][i_channel], voxelsize=voxelsize) else: img = SpatialImage(lsm_img.image['data'][0], voxelsize=voxelsize) return img
def load (file, mmap_mode=None, is_vectorial=False) : """Load a pickled, ``.npy``, or ``.npz`` binary file. :Parameters: - `file` (file or str) - `mmap_mode` (None, 'r+', 'r', 'w+', 'c') - optional If not None, then memory-map the file, using the given mode (see `numpy.memmap`). The mode has no effect for pickled or zipped files. A memory-mapped array is stored on disk, and not directly loaded into memory. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. - `is_vectorial` (bool) - specifically deal with file as if it was a 2D vectorial (RGB[A]) image so that it returns a 3D RGBA image and conforms to the contract. :Returns Type: |SpatialImage| """ if isinstance(file,str) : file = open(file,'rb') header = file.read(12) if header == "SpatialImage" : nb, = unpack('i',file.read(calcsize('i') ) ) res,info = loads(file.read(nb) ) data = np.load(file,mmap_mode) # if the read data is of shape 2 then # we can be sure it is a scalar 2D image # and we can reshape to a 3D scalar image. if len(data.shape) == 2: print "openalea.image.serial.basics.load: assuming 2D scalar image" data = data.reshape(data.shape+(1,)) if len(res) == 2: res += (1.,) elif len(data.shape) == 3 and not is_vectorial: print "openalea.image.serial.basics.load: assuming 3D scalar image" elif len(data.shape) == 3 and is_vectorial: print "openalea.image.serial.basics.load: interpreting as 2D scalar RGB[A] image" data = data.reshape( data.shape[:2] + (1, data.shape[2]) ) if len(res) == 2: res += (1.,) elif len(data.shape) == 4 and not is_vectorial: print "openalea.image.serial.basics.load: assuming 3D RGB[A] image" else: raise IOError("Unable to identify image shape and encoding") if len(res) == len(data.shape) : vdim = 1 else : vdim = data.shape[-1] return SpatialImage(data,res,vdim,info) else : file.seek(0) return SpatialImage(np.load(file,mmap_mode))
def logicalnot(img): """ """ d = img.dtype vmax = eval(d.name)(sys.maxint) im_target = vmax * ones(img.shape, img.dtype) image = bitwise_xor(img, im_target) if isinstance(img, SpatialImage): return SpatialImage(image, img.resolution) else: return SpatialImage(image)
def color2grey(image): """ Convert a color image into a grey-level image. """ if image.ndim != 4: print "Error : Not a color image" return -1 if not isinstance(image, SpatialImage): image = SpatialImage(image) return (SpatialImage(image[:, :, :, 0], image.resolution), SpatialImage(image[:, :, :, 1], image.resolution), SpatialImage(image[:, :, :, 2], image.resolution))
def point_selection (image, palette_name = "grayscale", color_index_max = None) : if not isinstance(image,SpatialImage): image = SpatialImage(image) w = PointSelection() w.set_image(image) if color_index_max is None : cmax = image.max() else : cmax = color_index_max palette = palette_factory(palette_name,cmax) w.set_palette(palette) w.show() return w
def point_selection(image, palette_name="grayscale", color_index_max=None): if not isinstance(image, SpatialImage): image = SpatialImage(image) w = PointSelection() w.set_image(image) if color_index_max is None: cmax = image.max() else: cmax = color_index_max palette = palette_factory(palette_name, cmax) w.set_palette(palette) w.show() return w
def img_resize(sp_img, sub_factor=2, option=None): """ Down interpolation of image 'sp_img' by a factor 'sub_factor'. For intensity image use 'option="gray"', for segmented images use 'option="label"'. """ vx = sp_img.voxelsize poss_opt = ['gray', 'label'] if option is None: option='label' else: if option not in poss_opt: option='label' extent = img_extent(sp_img) tmp_voxelsize = np.array(sp_img.voxelsize) *sub_factor print tmp_voxelsize new_shape, new_voxelsize = [], [] for ind in range(0,len(sp_img.shape)): new_shape.append(int(np.ceil(extent[ind]/tmp_voxelsize[ind]))) new_voxelsize.append(extent[ind]/new_shape[ind]) identity_trsf = create_trsf(param_str_2='-identity', trsf_type=BalTransformation.RIGID_3D, trsf_unit=BalTransformation.REAL_UNIT) template_img = np.zeros((new_shape[0],new_shape[1],new_shape[2]), dtype=sp_img.dtype) template_img = SpatialImage(template_img, voxelsize=new_voxelsize) if option=='gray': param_str_2 = '-interpolation linear' elif option=='label': param_str_2 = '-interpolation nearest' out_img = apply_trsf(sp_img, identity_trsf,template_img=template_img, param_str_2=param_str_2) return out_img
def nuclei_detection(reference_img, threshold=1000, radius_range=(0.8,1.4), step=0.2, segmentation_centering=False, subsampling=4, microscope_orientation=1): size = np.array(reference_img.shape) voxelsize = microscope_orientation*np.array(reference_img.voxelsize) positions = detect_nuclei(reference_img,threshold=threshold,radius_range=radius_range, step=step) positions = array_dict(positions) positions = array_dict(positions.values(),positions.keys()+2).to_dict() if segmentation_centering: nuclei_img = deepcopy(reference_img) image_coords = tuple(np.transpose((positions.values()/voxelsize).astype(int))) if subsampling>1: #nuclei_img = nd.gaussian_filter(nuclei_img,sigma=subsampling/4.)[::subsampling,::subsampling,::subsampling] nuclei_img = nd.gaussian_filter1d(nd.gaussian_filter1d(nuclei_img,sigma=subsampling/8.,axis=0),sigma=subsampling/8.,axis=1)[::subsampling,::subsampling,:] nuclei_img = SpatialImage(nuclei_img,voxelsize=(subsampling*reference_img.voxelsize[0],subsampling*reference_img.voxelsize[1],reference_img.voxelsize[2])) image_coords = tuple(np.transpose((positions.values()/(microscope_orientation*np.array(nuclei_img.voxelsize))).astype(int))) intensity_min = np.percentile(nuclei_img[image_coords],0)-1 segmented_img = nuclei_active_region_segmentation(nuclei_img, positions, display=False, omega_energies=dict(intensity=subsampling,gradient=1.5,smoothness=10000.0*np.power(subsampling,1.5)), intensity_min=intensity_min) positions = nuclei_positions_from_segmented_image(segmented_img) positions = array_dict(positions) positions = array_dict(positions.values()*microscope_orientation,positions.keys()).to_dict() return positions
def apply_palette(data, palette): if data.dtype == bool: data = data * 1 img = palette[data] if isinstance(data, SpatialImage): img = SpatialImage(img, img.resolution, palette.shape[1], img.info) return img,
def read_tiff_image(tiff_file, channel_names=None): from tifffile import TiffFile tiff_img = TiffFile(tiff_file) tiff_channels = tiff_img.asarray() n_channels = 1 if tiff_channels.ndim == 3 else tiff_channels.shape[1] 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( np.transpose(tiff_channels[:, i_channel], (1, 2, 0))) else: img = SpatialImage(np.transpose(tiff_channels, (1, 2, 0))) return img
def scale_shift_intensities(image, dtype=None, maxIn=None, maxOut=255): if dtype is None: dtype = uint8 if maxIn is None: maxIn = image.max() scale = maxOut / (float(maxIn)) return SpatialImage(dtype(image * scale), image.resolution)
def imread (filename, dimension=3) : """Reads an image file completely into memory. It uses the file extension to determine how to read the file. It first tries some specific readers for volume images (Inrimages, TIFFs, LSMs, NPY) or falls back on PIL readers for common formats if installed. In all cases the returned image is 3D (2D is upgraded to single slice 3D). If it has colour or is a vector field it is even 4D. :Parameters: - `filename` (str) :Returns Type: |SpatialImage| """ filename = expusr(filename) if not exists(filename) : raise IOError("The requested file do not exist: %s" % filename) root, ext = splitext(filename) ext = ext.lower() if ext == ".gz": root, ext = splitext(root) ext = ext.lower() if ext == ".inr": return read_inrimage(filename) elif ext == ".lsm": return read_lsm(filename) elif ext in [".tif", ".tiff"]: return read_tif(filename) elif ext in [".npz", ".npy"]: return load(filename) else: # -- We use the normal numpy reader. It returns 2D images. # If len(shape) == 2 : scalar image. # If len(shape) == 3 and shape[2] == 3 : rgb image # If len(shape) == 3 and shape[3] == 4 : rgba image. # Return a SpatialImage please! -- # Use the array protocol to convert a PIL image to an array. # Don't use pylab'es PIL_to_array conversion as it flips images vertically. im_array = np.array(Image.open(filename)) shape = im_array.shape if len(shape)==2: newShape = (shape[0], shape[1], 1, 1) elif len(shape) == 3: newShape = (shape[0], shape[1], 1, shape[2]) else: raise IOError("unhandled image shape : %s, %s"%(filename, str(shape))) #newarr = np.zeros(newShape, dtype=im_array.dtype, order="C") #newarr[:,:,0] = im_array[:,:] vdim = 1 if( len(shape) < 3 ) else shape[2] return SpatialImage(im_array.reshape(newShape), None, vdim)
def flatten(img_list, alpha=False): """Concatenate all images into a single image Use alpha to blend images one on top of each other .. warning:: all images must have the same nD shape and an alpha channel (except maybe for the first one) If alpha is True, the resulting image will use the max of all alpha channels as an alpha channel. .. warning:: if the first image is a |SpatialImage|, the resulting image will also be a |SpatialImage| but no test is made to ensure consistency in the resolution of the layers :Parameters: - `img_list` (list of NxM(xP)x4 array of uint8) - `alpha` (bool) - the resulting image will have an alpha channel or not :Returns Type: NxM(xP)x3(4) array of uint8 """ bg = img_list[0] R = bg[..., 0] G = bg[..., 1] B = bg[..., 2] if bg.shape[-1] == 4: alpha_list = [bg[..., 3]] else: alpha_list = [] for lay in img_list[1:]: A = lay[..., 3] alpha_list.append(A) A = A / 255. iA = 1. - A R = R * iA + lay[..., 0] * A G = G * iA + lay[..., 1] * A B = B * iA + lay[..., 2] * A if alpha: A = array(alpha_list).max(axis=0) ret = rollaxis(array([R, G, B, A], bg.dtype), 0, len(bg.shape)) else: ret = rollaxis(array([R, G, B], bg.dtype), 0, len(bg.shape)) if isinstance(bg, SpatialImage): return SpatialImage(ret, bg.resolution, 4, bg.info) else: return ret
def grey2color(r, g, b): """ convert a grey-level image into a color image. """ if (r.shape != g.shape) or (r.shape != b.shape): print "Error : r,g,b have not the same shape" return -1 xdim, ydim, zdim = r.shape if not isinstance(r, SpatialImage): r = SpatialImage(r) if not isinstance(g, SpatialImage): g = SpatialImage(g) if not isinstance(b, SpatialImage): b = SpatialImage(b) color = SpatialImage(zeros(xdim, ydim, zdim, 3), r.resolution) color[:, :, :, 0] = r color[:, :, :, 1] = g color[:, :, :, 2] = b return color
def _reconstruct_pixmaps(self, axis=2): pal = self.palette() data = self.image() #rotation tr = QTransform() tr.rotate(self._transform) #construct pixmaps pix = [] # Manage also colored images. if len(data.shape) == 4 and data.shape[-1] in (3, 4): if data.dtype != uint8: raise Exception( "Only uint8 RGB[A] images supported, got %s instead" % str(data.dtype)) pal = None for z in xrange(data.shape[axis]): if axis == 0: dat = data[z, :, :] elif axis == 1: dat = data[:, z, :] else: dat = data[:, :, z] if pal is not None: dat = pal[dat] if isinstance(data, SpatialImage): dat = SpatialImage(dat) #img = QImage(dat, # data.shape[0], # data.shape[1], # QImage.Format_ARGB32) dat = to_pix(dat) pix.append(dat.transformed(tr)) self._pixmaps = pix self._current_slice = min(max(self._current_slice, 0), len(pix) - 1)
def _reconstruct_pixmaps (self, axis=2) : pal = self.palette() data = self.image() #rotation tr = QTransform() tr.rotate(self._transform) #construct pixmaps pix = [] # Manage also colored images. if len(data.shape) == 4 and data.shape[-1] in (3,4): if data.dtype != uint8: raise Exception("Only uint8 RGB[A] images supported, got %s instead"%str(data.dtype)) pal = None for z in xrange(data.shape[axis]) : if axis == 0 : dat = data[z,:,:] elif axis == 1 : dat = data[:,z,:] else : dat = data[:,:,z] if pal is not None: dat = pal[dat] if isinstance(data, SpatialImage): dat=SpatialImage(dat) #img = QImage(dat, # data.shape[0], # data.shape[1], # QImage.Format_ARGB32) dat = to_pix (dat) pix.append(dat.transformed(tr) ) self._pixmaps = pix self._current_slice = min(max(self._current_slice,0),len(pix) - 1)
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
def deformation_field(image, points1, points2, sigma, dtype=np.float64): """ """ vectors = points2 - points1 points1 = np.round(points1) del points2 #points2 = np.round(points2) label = skiz(image, points1, vectors) img_vectors = component_gaussian_filter(label, sigma=sigma) del label # create an image with only the vectors at the points otherelse 0 img_vect0 = np.zeros(shape=image.shape + (3, ), dtype=dtype) for i, (x, y, z) in enumerate(points1): img_vect0[x, y, z] = vectors[i] img_vect0 = component_gaussian_filter(img_vect0, sigma=sigma, in_place=True) # create an image with only 1 at the points and fit it. img_pt1 = np.zeros(shape=image.shape, dtype=dtype) for x, y, z in points1: img_pt1[x, y, z] = 1 img_pt1 = filters.gaussian_filter(img_pt1, sigma=sigma) # Normalization img_vect0[:, :, :, 0] /= img_pt1 img_vect0[:, :, :, 1] /= img_pt1 img_vect0[:, :, :, 2] /= img_pt1 zero_mask = img_pt1 < 1e-6 del img_pt1 masked_vectors = img_vectors[zero_mask] img_vect0[zero_mask] = masked_vectors del masked_vectors, zero_mask img_vect0 = component_gaussian_filter(img_vect0, sigma=sigma, in_place=True) return SpatialImage(img_vect0, image.resolution, vdim=3)
def test_generate_write_read(): """Tests if a scalar and a vector image are written and read back correctly. Can't test if they are compatible with other Inrimage tools here, use ZViewer!""" # create a checkerboard that fades to black in depth cb = checkerboard(vs=(0.5,0.5,0.2)) coeffs = attenuation(numpy.linspace(0,1, cb.shape[2])).reshape(1,1,cb.shape[2]) cb = SpatialImage(cb*coeffs, voxelsize=cb.voxelsize, dtype=cb.dtype) f = "test_inri_0.inr.gz" write_inrimage(f, cb) read_cb = read_inrimage(f) numpy.testing.assert_array_equal(cb, read_cb) os.remove(f) # create a random vector field ff = "test_inri_0_tr.inr.gz" field = random_vector_field_like(cb, 4.0,20) write_inrimage(ff, field) read_field = read_inrimage(ff) numpy.testing.assert_array_equal(field, read_field) os.remove(ff)
def example_nuclei_image(n_points=100, size=50, voxelsize=(0.25, 0.25, 0.5), nuclei_radius=1.5, return_points=False): size = [size / v for v in voxelsize] img = np.zeros(tuple(size)) center = (np.array(size) * np.array(voxelsize) / 2.) points = {} for i in xrange(n_points): points[i] = center + np.random.rand(3) point_target_distance = np.power(n_points, 1 / 3.) * nuclei_radius * 1.5 sigma_deformation = nuclei_radius / 5. omega_forces = dict(distance=1, repulsion=1) points = point_position_optimization(points, omega_forces, point_target_distance, sigma_deformation, force_centering=True, center=center) x, y, z = np.ogrid[0:size[0] * voxelsize[0]:voxelsize[0], 0:size[1] * voxelsize[1]:voxelsize[1], 0:size[2] * voxelsize[2]:voxelsize[2]] img = (255. * nuclei_density_function( points, nuclei_radius, 2. / nuclei_radius)(x, y, z)).astype(np.uint16) _return = (SpatialImage(img, voxelsize=voxelsize), ) if return_points: _return += (points, ) if len(_return) == 1: return _return[0] return _return
def cube_image(size=50): img = np.ones((size, size, size), np.uint8) points = {} points[11] = np.array([1, 0, 0], float) * size points[12] = np.array([0, 1, 0], float) * size points[31] = np.array([0, 0, 1], float) * size points[59] = np.array([1, 1, 1], float) * size points = array_dict(points) center = np.array([[size / 2, size / 2, size / 2]], float) coords = np.transpose(np.mgrid[0:size, 0:size, 0:size], (1, 2, 3, 0)).reshape((np.power(size, 3), 3)) labels = points.keys()[vq(coords, points.values())[0]] ext_coords = coords[vq(coords, center)[1] > size / 2.] img[tuple(np.transpose(coords))] = labels #img[tuple(np.transpose(ext_coords))] = 1 img = SpatialImage(img, voxelsize=(1, 1, 1)) return img
def to_image(data, axis=2): # Manage also colored images. if len(data.shape) == 4 and data.shape[-1] in (3, 4): if data.dtype != np.uint8: raise Exception("Only uint8 RGB[A] images supported, got %s instead" % str(data.dtype)) pal = None for z in xrange(data.shape[axis]): if axis == 0: dat = data[z, :,:] elif axis == 1: dat = data[:, z, :] else: dat = data[:, :, z] if pal is not None: dat = pal[dat] if isinstance(data, SpatialImage): dat = SpatialImage(dat) #img = QImage(dat, # data.shape[0], # data.shape[1], # QImage.Format_ARGB32) return to_img(dat)
def seed_image_from_points(size, voxelsize, positions, point_radius=1.0, background_label=1): """ Generate a SpatialImage of a given shape with labelled spherical regions around points """ seed_img = background_label * np.ones(tuple(size), np.uint16) size = np.array(size) voxelsize = np.array(voxelsize) for p in positions.keys(): image_neighborhood = np.array(np.ceil(point_radius / voxelsize), int) neighborhood_coords = np.mgrid[ -image_neighborhood[0]:image_neighborhood[0] + 1, -image_neighborhood[1]:image_neighborhood[1] + 1, -image_neighborhood[2]:image_neighborhood[2] + 1] neighborhood_coords = np.concatenate( np.concatenate(np.transpose(neighborhood_coords, (1, 2, 3, 0)))) + np.array( positions[p] / voxelsize, int) neighborhood_coords = np.minimum( np.maximum(neighborhood_coords, np.array([0, 0, 0])), size - 1) neighborhood_coords = array_unique(neighborhood_coords) neighborhood_distance = np.linalg.norm( neighborhood_coords * voxelsize - positions[p], axis=1) neighborhood_coords = neighborhood_coords[ neighborhood_distance <= point_radius] neighborhood_coords = tuple(np.transpose(neighborhood_coords)) seed_img[neighborhood_coords] = p return SpatialImage(seed_img, voxelsize=list(voxelsize))
def spatial_image_analysis_to_spatial_image(input_sia, property_name=None, labels=None): """ """ sia = deepcopy(input_sia) img_labels = sia.labels() if labels is not None: labels_to_remove = set(img_labels) - set(list(labels)) sia.remove_labels_from_image(labels_to_remove) img_labels = sia.labels() segmented_img = deepcopy(sia.image) background = sia.background() print background if property_name == 'volume': img_volumes = sia.volume(img_labels) if isinstance(img_volumes, np.ndarray) or isinstance( img_volumes, list): img_volumes = array_dict(img_volumes, keys=img_labels) elif isinstance(img_volumes, dict): img_volumes = array_dict(img_volumes) property_img = SpatialImage(img_volumes.values(segmented_img).astype( np.uint16), resolution=segmented_img.resolution) property_img[segmented_img == background] = background else: property_img = segmented_img return property_img
nomenclature_names = dict(zip(nomenclature_data['Name'],nomenclature_data['Nomenclature Name'])) reference_name = 'TagBFP' channel_names = ['DIIV','PIN1','PI','TagBFP','CLV3'] signal_names = channel_names image_filename = microscopy_dirname+"/RAW/"+filename image_dict = read_czi_image(image_filename,channel_names=channel_names) no_organ_filename = microscopy_dirname+"/TIF-No-organs/"+filename[:-4]+"-No-organs.tif" if os.path.exists(no_organ_filename): no_organ_dict = read_tiff_image(no_organ_filename,channel_names=channel_names) image_mask = (image_dict[reference_name] == no_organ_dict[reference_name]) voxelsize = image_dict[reference_name].voxelsize img_file = image_dirname+"/"+nomenclature_names[filename]+"/"+nomenclature_names[filename]+"_mask.inr.gz" imsave(img_file,SpatialImage((255*image_mask).astype(np.uint8),voxelsize=voxelsize)) png_filename = microscopy_dirname+"/max_projection_intensity&masks/"+filename[:-4]+"_CH2_iso_MIP6000.png" mask_png_filename = microscopy_dirname+"/max_projection_intensity&masks/"+filename[:-4]+"_CH2_iso_MIP6000mask.png" if os.path.exists(mask_png_filename): png_img = imread_2d(png_filename) mask_png_img = imread_2d(mask_png_filename) mask_png_img = (mask_png_img == png_img)&(png_img != 0) image_mask = np.tile(mask_png_img[:,:,np.newaxis],(1,1,image_dict[reference_name].shape[2])) img_file = image_dirname+"/"+nomenclature_names[filename]+"/"+nomenclature_names[filename]+"_projection_mask.inr.gz" imsave(img_file,SpatialImage((255*image_mask).astype(np.uint8),voxelsize=voxelsize))
def resampling(img, transformation, order=1, output_shape=None, output_voxels=None, mode='constant', cval=0.0, prefilter=True): """ It resamples a 2-D or 3-D image using a 4*4 transformation matrix or a deformation field . The value of a point in the result image is determined by spline interpolation of the requested order. :Parameters: - `img` - `transformation` (array) - Matrix 4x4 or deformation field - `order` (int) - optional order corresponds to the degree of a polynomial used to the spline interpolation By default, order = 1 (linear interpolation) - `output_shape` (tuple) - optional The output shape can optionally be given. By default, it is equal to the input shape - `output_type` (tuple) - optional The output data type can optionally be given. By default, it is equal to the input data type - `output_voxels` (tuple) - optional The output voxels size can optionally be given. By default, it is equal to the input voxels size - `mode` (string) - optional Points outside the boundaries of the input are filled according to the given mode ("constant", "nearest", "reflect" or "wrap") By default, the given mode is "constant" - `prefilter` (boolean) - optional The parameter prefilter determines if the input is pre-filtered before interpolation (necessary for spline interpolation of order > 1) If False it is assumed that the input is already filtered :Returns Type: image resampled by the transformation """ if transformation.shape != (4, 4): print('using of a field deformation') _tx = transformation[:, :, :, 0] _ty = transformation[:, :, :, 1] _tz = transformation[:, :, :, 2] _data = geometric_transform(img, _apply_field, extra_arguments=(_tx, _ty, _tz), order=order) _data = SpatialImage(_data, img.resolution) transformation = np.identity(4) else: if not isinstance(img, SpatialImage): _data = SpatialImage(img) else: _data = img #extraction of the Rotation and Translation matrix (R,t) _R = transformation[0:3, 0:3] _t = transformation[0:3, 3] #extraction of voxel size of image vx, vy, vz = _data.resolution #creating of output if output_voxels is None: output_voxels = vx, vy, vz vox, voy, voz = output_voxels #scaling matrix #_output_scaling = np.diag([vox,voy,voz]) #_input_scaling = np.diag([1. / vx, 1. / vy, 1. / vz]) #change of basis #R = np.dot(_input_scaling, np.dot(_R, _output_scaling) ) #t = np.dot(_input_scaling, _t) _output = affine_transform(_data, _R, offset=list(_t), order=order, output_shape=output_shape, mode=mode, cval=cval, prefilter=prefilter) output = SpatialImage(_output, output_voxels) return output
reference_name = 'TagBFP' channel_names = ['DIIV', 'PIN1', 'PI', 'TagBFP', 'CLV3'] compute_ratios = [n in ['DIIV'] for n in channel_names] microscope_orientation = -1 image_filename = microscopy_dirname + "/RAW/" + filename image_dict = read_czi_image(image_filename, channel_names=channel_names) no_organ_filename = microscopy_dirname + "/TIF-No-organs/" + filename[:-4] + "-No-organs.tif" if os.path.exists(no_organ_filename): no_organ_dict = read_tiff_image(no_organ_filename, channel_names=channel_names) voxelsize = image_dict[reference_name].voxelsize for channel in channel_names: image_dict[channel] = SpatialImage(no_organ_dict[channel], voxelsize=voxelsize) reference_img = image_dict[reference_name] world.add(reference_img, 'nuclei_image', colormap='invert_grey', voxelsize=microscope_orientation * np.array(image_dict[reference_name].voxelsize)) world['nuclei_image']['intensity_range'] = (2000, 20000) if 'PI' in channel_names: pi_img = image_dict['PI'] world.add(pi_img, 'membrane_image', colormap='Reds', voxelsize=microscope_orientation *
def imread(filename, channel_names=None): javabridge.start_vm(class_path=bioformats.JARS) reader = bioformats.get_image_reader(path=filename, key=0) n_series = reader.rdr.getSeriesCount() metadata_xml = bioformats.get_omexml_metadata( path=filename).encode('utf-8') img_metadata = bioformats.OMEXML(metadata_xml) bit_dtypes = {} bit_dtypes[8] = np.uint8 bit_dtypes[16] = np.uint16 img_series = {} for s in range(n_series)[:1]: reader.rdr.setSeries(s) img = np.array([[ reader.read(c=None, z=z, t=t) for z in xrange(reader.rdr.getSizeZ()) ] for t in xrange(reader.rdr.getSizeT())]) if reader.rdr.getSizeC() == 1: img = img[:, :, :, :, np.newaxis] # img = np.transpose(img,(0,4,2,3,1)) img = np.transpose(img, (1, 4, 3, 2, 0)) series_name = img_metadata.image(s).Name vx = get_float_attr(img_metadata.image(s).Pixels.node, "PhysicalSizeX") vy = get_float_attr(img_metadata.image(s).Pixels.node, "PhysicalSizeY") vz = get_float_attr(img_metadata.image(s).Pixels.node, "PhysicalSizeZ") vx = 1 if vx is None else vx vy = 1 if vy is None else vy vz = 1 if vz is None else vz print(vx, vy, vz) bits = get_int_attr( img_metadata.image(s).Pixels.node, "SignificantBits") if img.shape[0] > 1: for t in xrange(img.shape[0]): img_series[series_name + "_T" + str(t).zfill(2)] = {} for c in xrange(img.shape[1]): image = SpatialImage(img[t, c], voxelsize=(vx, vy, vz)) if (image.max() <= 1.0): image = image * (np.power(2, bits) - 1) image = image.astype(bit_dtypes[bits]) if channel_names is not None and len( channel_names) == img.shape[1]: channel_id = channel_names[c] else: channel_id = img_metadata.image(s).Pixels.Channel(c).ID if channel_id is None: channel_id = "C" + str(c) img_series[series_name + "_T" + str(t).zfill(2)][channel_id] = image if img.shape[1] == 1: img_series[series_name + "_T" + str(t).zfill(2)] = img_series[ series_name + "_T" + str(t).zfill(2)].values()[0] else: img_series[series_name] = {} for c in xrange(img.shape[1]): image = np.copy(img[0, c]) if (image.max() <= 1.0): image = image * (np.power(2, bits) - 1) image = image.astype(bit_dtypes[bits]) image = SpatialImage(image, voxelsize=(vx, vy, vz)) if channel_names is not None and len( channel_names) == img.shape[1]: channel_id = channel_names[c] else: channel_id = img_metadata.image(s).Pixels.Channel(c).Name if channel_id is None: channel_id = img_metadata.image(s).Pixels.Channel(c).ID if channel_id is None: channel_id = "C" + str(c) img_series[series_name][channel_id] = image if img.shape[1] == 1: img_series[series_name] = img_series[series_name].values()[0] if n_series == 1: return img_series.values()[0] else: return img_series
def read_sequence ( directory, grayscale=True, number_images=None, start=0, increment=1, filename_contains="", voxels_size=None, verbose=True) : """ Convert a sequence of images in a folder as a numpy array. The images must all be the same size and type. They can be in TIFF, .... format. :Parameters: - `grayscale` (bool) - convert the image to grayscale - `number_images` (int) - specify how many images to open - `start` (int) - used to start with the nth image in the folder (default = 0 for the first image) - `increment` (int) - set to "n" to open every "n" image (default = 1 for opening all images) - `filename_contains` (str) - only files whose name contains that string are opened - `voxels_size (tuple) - specify voxels size - `verbose` (bool) - verbose mode """ _images = [] _files = [] if verbose : print "Loading : " for f in os.listdir(directory): if fnmatch.fnmatch(f, '*%s*' %filename_contains): try : im = Image.open(os.path.join(directory, f)) _files.append(f) if grayscale is True : _images.append(ImageOps.grayscale(im)) else: _images.append(im) except : if verbose : print "\t warning : cannot open %s" %f if len(_images) == 0 : if verbose : print "\t no images loaded" return -1 xdim, ydim = _images[0].size if number_images is None : zdim = round(float(len(_images) - start)/ increment) _nmax = len(_images) - start else : zdim = number_images _nmax = number_images * increment if _images[0].mode == 'RGB': nd_image = np.zeros((xdim,ydim,zdim, 3), dtype=np.uint8) nd_image = np.zeros((xdim,ydim,zdim)) j = 0 for i in _images[start:_nmax+start:increment] : if i.size == _images[start].size : nd_image[:,:,j] = i if verbose : print "\t ./%s" %_files[_images.index(i)] j += 1 else : if verbose : print "%s : wrong size - %s expected, %s found" %(_files[_images.index(i)], _images[start].size, i.size) result = nd_image.transpose(1,0,2) if voxels_size is None : return SpatialImage(result) else : return SpatialImage(result, voxels_size)
def read_tif(filename,channel=0): """Read a tif image :Parameters: - `filename` (str) - name of the file to read """ # TIF reader tif = libtiff.TIFF.open(filename) if tif.GetField('ImageDescription'): tif = TIFFfile(filename) arr = tif.get_tiff_array() _data = arr[:].T info_str = tif.get_info() else: i = 1 while not tif.LastDirectory(): i+=1 tif.ReadDirectory() tif.SetDirectory(0) _data = np.zeros((i,)+tif.read_image().shape,dtype=tif.read_image().dtype) for ii,i in enumerate(tif.iter_images()): _data[ii] = i _data = _data.transpose(2, 1, 0) info_str = tif.info() nx, ny, nz = _data.shape # -- prepare metadata dictionnary -- info_dict = dict( filter( lambda x: len(x)==2, (inf.split(':') for inf in info_str.split("\n")) ) ) info_dict.update(dict( filter( lambda x: len(x)==2,(inf.split('=') for inf in info_str.split("\n"))) )) for k,v in info_dict.iteritems(): info_dict[k] = v.strip() info_dict.update({'Filename':filename.split('/')[-1]}) print info_dict # -- getting the voxelsizes from the tiff image: sometimes # there is a BoundingBox attribute, sometimes there are # XResolution, YResolution, ZResolution or spacing. # the object returned by get_tiff_array has a "get_voxel_sizes()" # method but it fails, so here we go. -- if "BoundingBox" in info_dict: bbox = info_dict["BoundingBox"] xm, xM, ym, yM, zm, zM = map(float,bbox.split()) _vx = (xM-xm)/nx _vy = (yM-ym)/ny _vz = (zM-zm)/nz else: # -- When we have [XYZ]Resolution fields, it describes the # number of voxels per real unit. In SpatialImage we want the # voxelsizes, which is the number of real units per voxels. # So we must invert the result. -- if "XResolution" in info_dict: # --resolution is stored in a [(values, precision)] list-of-one-tuple, or # sometimes as a single number -- xres_str = eval(info_dict["XResolution"]) if isinstance(xres_str, list) and isinstance(xres_str[0], tuple): xres_str = xres_str[0] _vx = float(xres_str[0])/xres_str[1] elif isinstance(xres_str, (int, float)): _vx = float(xres_str) else: _vx = 1. _vx = 1./_vx if _vx != 0 else 1. else: _vx = 1.0 # dumb fallback, maybe we will find something smarter later on if "YResolution" in info_dict: # --resolution is stored in a [(values, precision)] list-of-one-tuple, or # sometimes as a single number -- yres_str = eval(info_dict["YResolution"]) if isinstance(yres_str, list) and isinstance(yres_str[0], tuple): yres_str = yres_str[0] _vy = float(yres_str[0])/yres_str[1] elif isinstance(yres_str, (int, float)): _vy = float(yres_str) else: _vy = 1. _vy = 1./_vy if _vy != 0 else 1. else: _vy = 1.0 # dumb fallback, maybe we will find something smarter later on if "ZResolution" in info_dict: # --resolution is stored in a [(values, precision)] list-of-one-tuple, or # sometimes as a single number -- zres_str = eval(info_dict["ZResolution"]) if isinstance(zres_str, list) and isinstance(zres_str[0], tuple): zres_str = zres_str[0] _vz = float(zres_str[0])/zres_str[1] elif isinstance(zres_str, (int, float)): _vz = float(zres_str) else: _vz = 1. _vz = 1./_vz if _vz != 0 else 1. else: if "spacing" in info_dict: _vz = eval(info_dict["spacing"]) else: _vz = 1.0 # dumb fallback, maybe we will find something smarter later on tif.close() # -- dtypes are not really stored in a compatible way (">u2" instead of uint16) # but we can convert those -- dt = np.dtype(_data.dtype.name) # -- Return a SpatialImage please! -- im = SpatialImage(_data, dtype=dt) im.resolution = _vx,_vy,_vz im.info = info_dict return im
self.update_pix() if __name__ == '__main__': from openalea.deploy.shared_data import shared_data from openalea.image.serial.basics import imread import openalea.oalab img_path = shared_data(openalea.oalab, 'icons/Crystal_Clear_app_clock.png') img = imread(img_path) import numpy matrix = numpy.zeros((100, 100, 100), dtype=numpy.uint8) matrix[90:100, :10, :10] = 1 matrix[:10, 90:100, :10] = 2 matrix[:10, :10, 90:100] = 3 img3d = SpatialImage(matrix) instance = QtGui.QApplication.instance() if instance is None: app = QtGui.QApplication([]) else: app = instance slider = ImageStackViewerWidget() slider.setValue(img) slider.show() slider_3d = ImageStackViewerWidget() slider_3d.setValue(img3d) slider_3d.show()