Package: microImage
MicroIMAGEGeneralDescriptionVersion:2.3.1Author:Vivien WALTERContact:walter.vivien@gmail.comMicroIMAGEis a Python 3.x module used to load all common types of images used in microscopy, edit and save them in any desired format.CompatibilityThe module can currently open the following type(s) of image:.TIFF images and stacks.GIF images and animations.PNG, .BMP and .JPG standard imagesDirectories of multiple framesIt can also save image(s) in the following formats:.TIFF images and stacks.GIF images and animations (8-bits only).PNG, .BMP and .JPG standard images.MP4 videoTable of contentsInstallationRequirementsInstallation using the setup.py scriptHow-to use the moduleBasic Input/Output functionsOpening an imageSaving an image on the computerVideo generationImage correction and modificationBackground correctionContrast correctionDisplaying the pixel value distributionCrop the imageGenerate a montageWriting labels on imagesScale barTime stampsUsing the ImageStack classLoading the image in the classNavigate in the frames and display themDuplicate and modify the imageApply a correction on the imageModify the space and time scale of the imageSave the image(s) in a fileInstallationRequirementsThe following modules are required to run MicroImage:Bottleneckffmpeg-pythonMatplotlibNumPypimsPillowsScikit-imageIf you install the module using the setup.py script, you do NOT need to install first the module above.In order to generate video, it is required to haveFFMPEGinstalled on the computer. Instructions on how to install FFMPEG can be found onInternet(e.g.MacOS)Installation using PyPiTo install microImage using a terminal and PyPi, simply use the following commandpipinstallmicroImageInstallation using the setup.py scriptDownload the module folder on the github repoInstallation in aTerminal-basedenvironmentOpen a terminal in the module folder(Opt.) Start your virtualenv if you use oneType and run the command>python3setup.pyinstallInstallation in anAnacondaenvironmentOpen Anaconda and go to your EnvironmentsSelect the environment you want to install the module intoClick on the arrow next to the name of the environment and select Open a TerminalNavigate to the module folderType and run the commandpythonsetup.pyinstallHow-to use the moduleTheexamples/folder provides a .py script as well as a Jupyter notebook to load and display an image using MicroImage.Basic Input/Output functionsOpening an imageTo load an image, simply use theopenImage()function:frommicroImageimportopenImageimageArray=openImage('./path/to/folder/or/image.image_extension')TheimageArrayoutput is a NumPy array of shape(frames, Y pixel, X pixel).
To open a folder containing multiple frames, just type the path to the folder.Saving an image on the computerTo save an array as an image, you can use thesaveImage()function:frommicroImageimportsaveImagesaveImage(imageArray,'./path/to/new/file.tif',bit_depth=16,rescale=True)The function will automatically detect if you are trying to save a single frame or a stack/animation.You can specify the bit depth of the output image (8 or 16 bits, 8 bits only for gif animations) using thebit_depthargument. The function will always try to cover the full bit depth with the given pixel values; this can be prevented with the argumentrescale=False.If an extension is not specified, in the path of the file to create, the default extension .tif will be used. This can be changed by using the argumentdefaultto specify another default format (e.gdefault='.png')Video generationIt is also possible to save the array as a .mp4 video using thesaveVideo()function:frommicroImageimportsaveVideosaveVideo(imageArray,'./path/to/new/file.mp4',fps=25)Havingffmpeginstalled on the computer is required to use this function.All arrays will be converted to 8-bits prior to be saved. The framerate of the video can be selected using thefps=argument.It is possible to select a specific video codec for the output video using thevideo_codec=argument. The default video codec islibx264.Image correction and modificationBackground correctionAssuming the input array is a stack of image (> 1 frame), microImage can be used to remove the static background of the stack using the functionbackgroundCorrection()frommicroImageimportbackgroundCorrectioncorrectedArray=backgroundCorrection(imageArray,signed_bits=True,average='median',correction='division')If the images come from a signed bit array, it should be specified using the argumentsigned_bits.The type ofaverageused can be selected between mean or median, and the type ofcorrectionhas to be picked between division and subtraction, using their respective arguments.Contrast correctionThe contrast of the image contained in the array can be modified with the functioncontrastCorrection()frommicroImageimportcontrastCorrectioncorrectedArray=contrastCorrection(imageArray,min=None,max=None,percentile=10,percentile_min=None,rescale=True)The user can specify either theminandmaxpixel value, or can ask the function to calculate it based on percentiles. The min value is calculated based onpercentile_minand the max based onpercentile(from 100%, so 10 corresponds to 90%). If percentile_min is not given, the value of percentile will be used.The output can be rescaled to the full bit depth withrescale=True. If left False, the scale will be based on the old min and max pixel values.Displaying the pixel value distributionIt is possible to display the pixel value distribution of the image array, along with the position of the min and max values calculated by thecontrastCorrection()function. This can be done with theshowPVD()function.frommicroImageimportshowPVDshowPVD(imageArray,n_bins=10000,min=None,max=None,percentile=10,percentile_min=None,log_scale=None)The function will display the pixel value distribution as an histogram. The number of bins can be controlled by then_bins=argument (default is 1000). The scale of the histogram can be switched to log using thelog_scale=argument. If left to None, both axes will be shown as normal scales. "x" will use log scale for the X-axis, "y" for the Y-axis, and "xy" (or "yx") will use log scale for both axis.All other arguments are similar to the one of the functioncontrastCorrection(), besides therescale=which cannot be used here.Crop the imageThe image can be cropped using thecropImage()functionfrommicroImageimportcropImagecroppedArray=cropImage(imageArray,top_left=(200,200),bottom_right=(800,800))Each limit should be given as (X,Y) coordinates. If left to default,top_leftwill be equal to (0,0) andbottom_rightto (Xmax, Ymax).Generate a montageA stack of images can be turned into a montage of individual frames in a single image. This is done by the functionmakeMontage()frommicroImageimportmakeMontagemontageArray=makeMontage(imageArray,frames=5,column=None,row=None,margin=20,white_margin=False)The argumentsframes=define the frames that has to be added in the montage. If an integer is given, the function will save every N frames of the stack. If a list is given, the list will be used as list of incides of the frame to save.The general shape of the montage can be selected using the argumentscolumn=androw=, respectively the number of columns and rows making the montage table. If any or both of these arguments are set to None, the function will automatically calculate what is required.The argumentsmargin=allows for drawing margin between each pictures in the montage. If different from 0, it will be used as the thickness in pixels. The color of the margin is selected via the argumentwhite_margin=.Writing labels on imagesThe module microImage includes some simple tool to quicky write labels on the imagesScale barIt is possible to add automatically a simple scale bar on the image using theaddBar()functionfrommicroImageimportaddBarmodifiedArray=addBar(imageArray,scale_length=5,thickness=50,padding=20,white_bar=True,space_unit='µm',space_scale=46.21,add_text=True)The scale and space units can be specified using the argumentsspace_scale=andspace_unit=respectively. If None are given, the function will assume a scale in pixel. The length of the bar (in the given space scale and unit) can be selected usingscale_length=. Thethicknessand thepaddingsurrouding the bar car be selected with their eponymous arguments. User can select between white and black bars using thewhite_bar=boolean argument.It is possible to add text on top of the bar with theadd_text=boolean argument. User can select thefont=.ttf file to use (default:Arial.ttf) and the font size with thefont_size=argument. If let empty, the function will automatically the font size to match the scale bar length.Time stampsTo add time stamps on an image stack, one can use the functionaddTime()frommicroImageimportaddTimemodifiedArray=addTime(imageArray,position='top',padding=20,white_text=True,time_unit='s',time_scale=1/200)Position of the stamp can be selected between top and bottom using theposition=argument. The scale and time units can be specified using the argumentstime_scale=andtime_unit=respectively. The color of the text is selected using the argumentwhite_text=.The text options are the same as the one for theaddBar()function.Using the ImageStack classIt is possible to extract the images in an ImageStack object rather than in an array. Using an ImageStack object will reduce the versatility as compared to an array, but make the image processing easier to perform.Loading the image in the classTo load an image and generate an object, we use the functionloadImage()frommicroImageimportloadImageimage=loadImage('./path/to/folder/or/image.image_extension')Additionally, the ImageStack class can be loaded with an array instead of an image file using theloadArray()functionfrommicroImageimportloadArrayimage=loadArray(imageArray,name='test array')It is essential that the imageArray object here is a 3-D array of dimension(number of frame, Y, X)The element returned by each of these functions is an object with the following attributes:NameTypeDescriptionimage.nameStringName of the image stack (usually taken from the path)image.n_framesIntTotal number of frame in the stack (1 if single image)image.size2-D TupleSize of the array in each dimension (Y,X)image.source3-D ArrayArray used to generate the class instance. Is used to reset all corrections. Dimensions are (t,Y,X)image.array3-D ArrayOriginally copy ofimage.source, all modifications and corrections are applied to this array only (except crop). Dimensions are (t,Y,X)image.frameImageFrame objectInstance of the class ImageFrame used to handle single frame images. See belowimage.frame_nbrIntIndex of the current frame being loaded inimage.frameTo display the frames, the ImageStack class is calling another class named ImageFrame. This class has the following attributesNameTypeDescriptionframe.raw2-D ArrayNon-contrast corrected version of the frame being displayed. Used for calculation. Dimensions are (Y,X)frame.corrected2-D ArrayArray containing the frame being displayed, eventually with the selected contrast correction. Dimensions are (Y,X)Navigate in the frames and display themThe frame loaded in the ImageFrame class for image processing can be selected using the command.setFrame()image.setFrame(12)To dislay the frame (using the matplotlib library), just call the.show()command.image.show(show_raw=False,cmap='gray',title=True)The user can select whether the raw or contrast corrected image can be displayed, the color map and if the title should be displayed or not on the image.Duplicate and modify the imageIt is possible to create a copy of the ImageStack object anytime by using the command.duplicate()new_copy=image.duplicate()All previous modification made on the initial object will be pasted into the copy.The image can be cropped to a much smaller size with.crop().image.crop(top_left=(200,200),bottom_right=(800,800))The change will affect all image arrays in the ImageStack object, but also in the ImageFrame one. Check thecropImage functionfor details on the arguments of the function.In the case of a stack of several frames, the stack can be reduced to a subrange of frames with the command.reducedRange()image.reducedRange(first=10,last=20)If not specified, thefirstandlastframe of the new subrange will be calculated respectively as the first and the last frame of theimage.sourcearray.Apply a correction on the imageBackground correction similar to the one of thebackgroundCorrection()function can be applied with the.backgroundCorrection()commandimage.backgroundCorrection(imageArray,signed_bits=True,average='median',correction='division')Contrast correction similar to the one of thecontrastCorrection()function can be applied with the.contrastCorrection()commandimage.contrastCorrection(imageArray,min=None,max=None,percentile=10,percentile_min=None,rescale=True)The effect of the contrastCorrection on the pixel value distribution can be assessed with the.showPVD()command. Check the documentation on theshowPVD()function above for more details.image.showPVD(min=None,max=None,percentile=10,percentile_min=None,n_bins=1000,log_scale='xy')All modifications can be reset anytime using the.reset()command.image.reset()This will cancel any background and contrast correction, but not modifications made by the .crop() and .reducedRange() commands.Modify the space and time scale of the imageSet the scales using thesetScale()functionimage.setScale(time_scale=1/200,time_unit='s',space_scale=46.21,space_unit='µm')Thetime_scale=should be given in unit/frame and thespace_scale=in unit/pixel. Only the called arguments will be modified, the one set to None or not added will be left unchanged.Add a scale bar on the image(s) using thescaleBar()functionimage.scaleBar(frame=0,scale_length=4,add_text=False)The argumentframe=can used to select on which specific frame the scale bar should be added. If set to None, the scale bar will be added on all frames.Refer to the functionaddBar()above for description of other arguments.Add time stamps on an image stack using thetimeStamps()functionimage.timeStamps(white_text=True)Refer to the functionaddTime()above for description of all arguments.Save the image(s) in a fileThe command.saveStack()will save the whole stack saved in the ImageStack instance.image.saveStack('./path/to/new/file.tif',bit_depth=16,rescale=True,save_raw=False)Thesave_rawargument allows the user to select if the corrected or raw array should be save. Check thesaveImage functionfor details on the arguments of the function.To only save the current frame in the ImageFrame instance, the command.saveFrame()can be used.image.saveFrame('./path/to/new/file.tif',bit_depth=16,rescale=True,save_raw=False)To save a montage of a selection of frame, the command.makeMontage()can be usedimage.makeMontage(name='./path/to/montage.tif',frames=[0,2,4,10],bit_depth=16,rescale=True)Refer to the functionmakeMontage()above for description of all montage-related arguments of the command.To save a video file, the command.saveVideo()cam be usedimage.saveVideo(name='./path/to/montage.mp4',fps=25)Refer to the functionsaveVideo()above for description of all video generation arguments of the command.