def _get_mcd_acquisition(mcd_acquisition, acquisition='all', verbose=False, filehandle=None): """ A generator the returns the acquisitions :param mcd_acquisition: :abstractparseram acquisition: :param verbose: :return: """ with mcdparser.McdParser(mcd_acquisition, filehandle) as mcd: n_ac = mcd.n_acquisitions if verbose: print('containing %i acquisitions:' % n_ac) ac_ids = mcd.acquisition_ids if verbose: for aid in ac_ids: print('%s \n' % aid) print('Print acquisition: %s' % acquisition) if acquisition == 'all': acquisitions = ac_ids else: acquisitions = [acquisition] for aid in acquisitions: imc_img = mcd.get_imc_acquisition(aid) acquisition = aid yield (acquisition, imc_img)
def load(cls, slide: Slide) -> Slide: slide_path = slide.slide_path with mcdparser.McdParser(slide_path) as mcd: slide_item = mcd.meta.objects['Slide']['0'] file_name = os.path.basename(slide_path) slide.meta = slide_item.properties for panorama_item in slide_item.childs['Panorama'].values(): panorama = Panorama(panorama_item.properties['Description'], panorama_item.properties) slide.addChild(panorama) if 'AcquisitionROI' in panorama_item.childs: for acquisition_roi_item in panorama_item.childs['AcquisitionROI'].values(): roi_points: List[ROIPoint] = list() for roi_point_item in acquisition_roi_item.childs['ROIPoint'].values(): roi_point = ROIPoint(roi_point_item.metaname, roi_point_item.properties) roi_points.append(roi_point) acquisition_roi = AcquisitionROI(acquisition_roi_item.metaname, acquisition_roi_item.properties, roi_points) panorama.add_acquisition_roi(acquisition_roi) for acquisition_item in acquisition_roi_item.childs['Acquisition'].values(): # Dict key should be str! acquisition = Acquisition(acquisition_item.properties['Description'], acquisition_item.properties) acquisition_roi.add_acquisition(acquisition) imc_acquisition = mcd.get_imc_acquisition(acquisition.id) for i in range(imc_acquisition.n_channels): meta = dict() label = imc_acquisition.channel_labels[i] meta['Label'] = label meta['Metal'] = imc_acquisition.channel_metals[i] meta['Mass'] = imc_acquisition.channel_mass[i] img = imc_acquisition.get_img_by_label(label) channel = Channel(label, meta, img) acquisition.add_channel(channel) return slide
def save_mcd_tiff(mcd_filename, acquisition='all', tifftype='ome', compression=0, outname=None, outpath=0,verbose=False): """ :param mcd_filename: :param acquisition: :param tifftype: :param compression: :param outname: :param outpath: :return: """ # parse the arguments args = parser.parse_args() if verbose: print('Load filename %s' %mcd_filename) if outname is None: outname = os.path.split(mcd_filename)[1] outname = outname.replace('.mcd', '') if outpath is None: outpath = os.path.split(mcd_filename)[0] with mcdparser.McdParser(mcd_filename) as mcd: n_ac = mcd.n_acquisitions if verbose: print('containing %i acquisitions:' % n_ac) ac_ids = mcd.acquisition_ids if verbose: for aid in ac_ids: print('%s \n' %aid) print('Print acquisition: %s' %acquisition) if args.acquisition == 'all': acquisitions = ac_ids else: acquisitions = [acquisition] for aid in acquisitions: imc_img = mcd.get_imc_acquisition(aid) cur_outname = outname + '_a' + aid if tifftype == 'ome': cur_outname += '.ome.tiff' else: cur_outname +='.tiff' cur_outname = os.path.join(outpath, cur_outname) if verbose: print('Save %s as %s' %(aid,cur_outname)) iw = imc_img.get_image_writer(cur_outname) iw.save_image(mode=tifftype, compression=compression) if verbose: print('Finished!')
def get_mcd_aquisition(file_name, roi_name): """ Extracts the acquisition specified by the ROI name from a mcd file""" mcd = mcdparser.McdParser(file_name) roi_ids = {mcd.get_acquisition_description(id) : id for id in mcd.acquisition_ids} if roi_name not in roi_ids.keys(): print(f"ROI not present: {roi_name}") print("Available ROIs: " + "\n".join(roi_ids.keys())) sys.exit(1) return mcd.get_imc_acquisition(roi_ids[roi_name])
## CREATE DICTIONARY metal = metal.upper() if metal not in metalDict: metalDict[metal] = [bool(int(x)) for x in [fstack, istack]] fin.close() ## OUTPUT FILE LINKING ROI IDS TO ROI LABELS (IMAGE DESCRIPTION) roi_map = open(os.path.basename(args.INPUT_FILE) + '_ROI_map.csv', "w") ## USE DIFFERENT PARSERS CORRESPONDING TO THE INPUT FILE FORMAT file_type = re.sub(".*\.([^.]+)$", '\\1', args.INPUT_FILE.lower()) ## CONVERT INPUT_FILE TO TIFF AND WRITE RELEVANT TIFF IMAGES if file_type == "mcd": parser = mcdparser.McdParser(args.INPUT_FILE) acids = parser.acquisition_ids else: if file_type == "txt": parser = txtparser.TxtParser(args.INPUT_FILE) elif file_type == "tiff" or file_type == "tif": parser = omeparser.OmetiffParser(args.INPUT_FILE) else: print("{}: Invalid input file type - should be txt, tiff, or mcd!". format(file_type)) sys.exit(1) # THERE IS ONLY ONE ACQUISITION - ROI FOLDER NAMED ACCORDING TO INPUT FILENAME acids = [ re.sub('.txt|.tiff', '', os.path.basename(parser.filename).lower().replace(" ", "_"))
if fstack not in ['0', '1'] or istack not in ['0', '1']: print("{}: Invalid column code - should be 0 or 1!\nLine: '{}'".format( ERROR_STR, line.strip())) sys.exit(1) ## CREATE DICTIONARY metal = metal.upper() if metal not in metalDict: metalDict[metal] = [bool(int(x)) for x in [fstack, istack]] fin.close() ## OUTPUT FILE LINKING ROI IDS TO ROI LABELS (IMAGE DESCRIPTION) roi_map = open(os.path.basename(args.MCD_FILE) + '_ROI_map.csv', "w") ## COMVERT MCD TO TIFF AND WRITE RELEVANT TIFF IMAGES mcd = mcdparser.McdParser(args.MCD_FILE) for acid in mcd.acquisition_ids: imc_ac = mcd.get_imc_acquisition(acid) roi_label = mcd.get_acquisition_description(acid) roi_map.write("roi_%s,%s" % (acid, roi_label) + "\n") for l, m in zip(imc_ac.channel_labels, imc_ac.channel_metals): filename = "%s.tiff" % (l) ## WRITE TO APPROPRIATE DIRECTORY metal = l.split('_')[0].upper() if metal in metalDict: for i, j in enumerate(HEADER[1:]): if metalDict[metal][i]: dirname = "roi_%s/%s" % (acid, j) if not os.path.exists(dirname): os.makedirs(dirname)
if remove_folder: os.removedirs(out_folder) def _write_acquisition(self, ac, out_folder): file_end = '_ac.ome.tiff' if ac.image_description is None: ac_id = ac.image_ID fn = self.meta.get_object(mcdmeta.ACQUISITION, ac_id).metaname else: fn = ac.image_description img_writer = ac.get_image_writer( os.path.join(out_folder, fn + file_end)) img_writer.save_image(mode='ome') def _find_ac_metaname_from_txt_fn(self, ac): raise NotImplementedError if __name__ == '__main__': import imctools.io.mcdparser as mcdp #fn_mcd = '/home/vitoz/temp/txtvsmcd/20170805_p60-63_slide6_ac1_vz.mcd' #fn_mcd = '/mnt/imls-bod/VitoZ/Spheres/20161130_p25_slide2_ac1/20161130_p25_slide2_ac1.mcd' #fn_mcd='/mnt/imls-bod/VitoZ/Spheres/20161005_IS2362_4_site1_ac1/20161005_IS2362_4_site1_ac1.mcd' # an example of not functional mcd but working txt # fn_mcd = /mnt/imls-bod/DanielS/ACD/IMC\ 2.06/Her2_grade3 fn_mcd = '/mnt/imls-bod/VitoZ/Spheres/20161018_OCT1_slide4_ac1/20161018_OCT1_slide4_ac1.mcd' mcd = mcdp.McdParser(fn_mcd) mcd.save_meta_xml('/home/vitoz/temp/') ifw = ImcFolderWriter('/home/vitoz/temp/', mcddata=mcd) ifw.write_imc_folder()