diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000000000000000000000000000000000000..8c200211a49e196e8900718050d145a8c75e418c --- /dev/null +++ b/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2024, Gaëlle LETORT +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100755 index 0000000000000000000000000000000000000000..f3155af7064c0db0b5b9b8e2aa0d4b2f02f092ce --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include LICENSE +include README.md + +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 56c4307a4d4c8cc7547e9fc37dbd9ba60070ce11..65273e95ae68a05de5beb1e63239c77b962ac6da --- a/README.md +++ b/README.md @@ -1,93 +1,42 @@ # napari-3dtimereg +[](https://gitlab.pasteur.fr/gletort/multireg/blob/main/LICENSE) +[](https://pypi.org/project/multireg) +[](https://python.org) +[](https://napari-hub.org/plugins/multireg) +Temporal registration of 3D movies on one channel based on itk-elastix, and transpose alignement to the other channels. -## Getting started -To make it easy for you to get started with GitLab, here's a list of recommended next steps. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.pasteur.fr/gletort/napari-3dtimereg.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.pasteur.fr/gletort/napari-3dtimereg/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. +---------------------------------- +## Installation -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +* You can install the plugin directly in `Napari` by going to `Plugins>Install/Uninstall plugins` and search for `napari-3dtimereg` -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +* Or you can install `napari-3dtimereg` via [pip]: -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + pip install napari-3dtimereg -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. ## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +You can launch `3dtimerg` in napari by going to `Plugins>3dTimeReg: calculate and apply registration`. -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. -## Contributing -State if you are open to contributions and what your requirements are for accepting them. -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +## License +Distributed under the terms of the [BSD-3] license, +"multireg" is free and open source software -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +## Issues -## License -For open source projects, say how it is licensed. +If you encounter any problems, please [file an issue] along with a detailed description. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +[napari]: https://github.com/napari/napari +[@napari]: https://github.com/napari +[BSD-3]: http://opensource.org/licenses/BSD-3-Clause +[tox]: https://tox.readthedocs.io/en/latest/ +[pip]: https://pypi.org/project/pip/ +[PyPI]: https://pypi.org/ diff --git a/pyproject.toml b/pyproject.toml new file mode 100755 index 0000000000000000000000000000000000000000..d4d0e272b5950d2827ffb3afb1f3577d244b6091 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,54 @@ +[build-system] +requires = ["setuptools>=42.0.0", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 79 +target-version = ['py38', 'py39', 'py310'] + + +[tool.ruff] +line-length = 79 +select = [ + "E", "F", "W", #flake8 + "UP", # pyupgrade + "I", # isort + "BLE", # flake8-blind-exception + "B", # flake8-bugbear + "A", # flake8-builtins + "C4", # flake8-comprehensions + "ISC", # flake8-implicit-str-concat + "G", # flake8-logging-format + "PIE", # flake8-pie + "SIM", # flake8-simplify +] +ignore = [ + "E501", # line too long. let black handle this + "UP006", "UP007", # type annotation. As using magicgui require runtime type annotation then we disable this. + "SIM117", # flake8-simplify - some of merged with statements are not looking great with black, reanble after drop python 3.9 +] + +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".mypy_cache", + ".pants.d", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + "__pypackages__", + "_build", + "buck-out", + "build", + "dist", + "node_modules", + "venv", + "*vendored*", + "*_vendor*", +] + +target-version = "py38" +fix = true diff --git a/setup.cfg b/setup.cfg new file mode 100755 index 0000000000000000000000000000000000000000..bf88afb5a6a6ad9898e31b356f786a3544369da6 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,62 @@ +[metadata] +name = napari-3dtimereg +version = 0.0.1 +description = Registration of 3D movies applied to all channels +long_description = file: README.md +long_description_content_type = text/markdown + +author = Gaëlle Letort +author_email = gaelle.letort@pasteur.fr +url = https://gitlab.pasteur.fr/gletort/napari-3dtimereg + +license = BSD-3-Clause +license_files = LICENSE +classifiers = + Framework :: napari + Intended Audience :: Developers + License :: OSI Approved :: BSD License + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Topic :: Scientific/Engineering :: Image Processing + +project_urls = + Bug Tracker = https://gitlab.pasteur.fr/gletort/napari-3dtimereg/issues + Documentation = https://gitlab.pasteur.fr/gletort/napari-3dtimereg#README.md + Source Code = https://gitlab.pasteur.fr/gletort/napari-3dtimereg + +[options] +packages = find: +install_requires = + numpy + napari + magicgui + qtpy + tifffile + imaris_ims_file_reader + czifile + itk == 5.3.0 + itk-registration + itk-elastix + +python_requires = >=3.8 +include_package_data = True +package_dir = + =src + +# add your package requirements here + +[options.packages.find] +where = src + +[options.entry_points] +napari.manifest = + napari-3dtimereg = napari_3dtimereg:napari.yaml + + +[options.package_data] +* = *.yaml diff --git a/setup.py b/setup.py new file mode 100755 index 0000000000000000000000000000000000000000..8bf1ba938af9b4993f625db4fc6e708be9f3f3b7 --- /dev/null +++ b/setup.py @@ -0,0 +1,2 @@ +from setuptools import setup +setup() diff --git a/src/napari_3dtimereg/Utils.py b/src/napari_3dtimereg/Utils.py new file mode 100755 index 0000000000000000000000000000000000000000..d173b891d499973560ec6123d46c0a2766012885 --- /dev/null +++ b/src/napari_3dtimereg/Utils.py @@ -0,0 +1,230 @@ +import numpy as np +import os + +def colormapname( i ): + colorsmaps = ["red", "green", "blue", "yellow", "cyan", "gray"] + return colorsmaps[i] + +def openims(imagepath, verbose=True): + """ Open ims image """ + from imaris_ims_file_reader.ims import ims + img = ims(imagepath, squeeze_output=True) + image = np.array(img[0]) + scaleXY = img.resolution[1] + if img.resolution[2] != scaleXY: + print("Warning, scale is not the same in X and Y, not implemented yet") + scaleZ = img.resolution[0] + if verbose: + print("Initial image shape: "+str(image.shape)) ## Y et X sont inverses, Z, Y, X + nchan = img.Channels + names = [] + try: + if nchan > 0: + for i in range(nchan): + name = img.read_attribute("DataSetInfo/Channel "+str(i), 'DyeName') + names.append(name) + except: + names = [] + img = None + + return (np.squeeze(image), scaleXY, scaleZ, names) + +def writeims(imagepath, img, verbose=True): + ## libraries pb, must install hdf5, ImarisWriter + from PyImarisWriter import PyImarisWriter as pw + imshape = img.shape + image_size = pw.ImageSize(x=imshape[2], y=imshape[1], z=imshape[0], c=1, t=1) + dimension_sequence = pw.DimensionSequence('z', 'y', 'x', 'c', 't') + block_size = image_size + sample_size = pw.ImageSize(x=1, y=1, z=1, c=1, t=1) + output_filename = 'outifle.ims' + + options = pw.Options() + options.mNumberOfThreads = 12 + options.mCompressionAlgorithmType = pw.eCompressionAlgorithmGzipLevel2 + options.mEnableLogProgress = True + + application_name = 'PyImarisWriter' + application_version = '1.0.0' + + #callback_class = MyCallbackClass() + converter = pw.ImageConverter("uint8", image_size, sample_size, dimension_sequence, block_size, + output_filename, options, application_name, application_version, None) + + num_blocks = image_size / block_size + + block_index = pw.ImageSize() + for c in range(num_blocks.c): + block_index.c = c + for t in range(num_blocks.t): + block_index.t = t + for z in range(num_blocks.z): + block_index.z = z + for y in range(num_blocks.y): + block_index.y = y + for x in range(num_blocks.x): + block_index.x = x + if converter.NeedCopyBlock(block_index): + converter.CopyBlock(img, block_index) + + adjust_color_range = True + image_extents = pw.ImageExtents(0, 0, 0, image_size.x, image_size.y, image_size.z) + parameters = pw.Parameters() + parameters.set_value('Image', 'ImageSizeInMB', 2400) + parameters.set_value('Image', 'Info', 'Results Title') + parameters.set_channel_name(0, 'My Channel 1') + time_infos = [datetime.today()] + color_infos = [pw.ColorInfo() for _ in range(image_size.c)] + color_infos[0].set_color_table(configuration.mColor_table) + + converter.Finish(image_extents, parameters, time_infos, color_infos, adjust_color_range) + + converter.Destroy() + print('Wrote file') + +def writeTif(img, imgname, scaleXY, scaleZ, imtype): + import tifffile + ### 2D + if scaleZ < 0: + tifffile.imwrite(imgname, np.array(img, dtype=imtype), imagej=True, resolution=[1./scaleXY, 1./scaleXY], metadata={'unit': 'um', 'axes': 'YX'}) + #### 3D + else: + tifffile.imwrite(imgname, np.array(img, dtype=imtype), imagej=True, resolution=[1./scaleXY, 1./scaleXY], metadata={'spacing': scaleZ, 'unit': 'um', 'axes': 'ZYX'}) + +def get_scale_of(racine, c): + """ read scaling value from xml metadata """ + try: + part = racine.xpath("//Distance [@Id = '%s']" % c) + for neighbor in part[0].iter('Value'): + pixel_in_meters = float(neighbor.text) + except: + pixel_in_meters = -1 + return pixel_in_meters*1000000 + +def openczi(imagepath, scene=0, verbose=True): + """ Open czi image """ + import czifile + from lxml import etree + czi = czifile.CziFile(imagepath) + image = czi.asarray() + if verbose: + print("Initial image shape: "+str(image.shape)) + + if image.ndim >= 8: + image = image[:,scene,:,:,:,:,:,:] ## si contient 2 scenes + + # get scale + root = etree.fromstring(czi.metadata()) + scaleXY = get_scale_of(root, "X") + scaleXYcheck = get_scale_of(root, "Y") + if scaleXY != scaleXYcheck: + print("Warning, scale not the same in X and in Y, not implemented yet") + scaleZ = get_scale_of(root, "Z") + + fluonames = get_fluo_names(root) + return (np.squeeze(image), scaleXY, scaleZ, fluonames) + +def get_filename(): + try: + from tkinter import Tk + from tkFileDialog import askopenfilenames + except: + from tkinter import Tk + from tkinter import filedialog + + Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing + filenames = filedialog.askopenfilenames() # show an "Open" dialog box and return the path to the selected file + return filenames + +def opentif(imagepath, verbose=True): + import tifffile as tif + img = tif.TiffFile(imagepath) + metadata = img.imagej_metadata + names = [] + scaleXY = 1 + scaleZ = 1 + try: + if metadata is not None: + info = img.imagej_metadata["Info"] + for i in range(10): + ind = info.find("channels_channel_"+str(i)+"_dyename") + if ind >= 0: + keep = info[ind:] + indend = keep.find("\n") + names.append(info[ind+28:ind+indend].strip()) + + metadata = (img.imagej_metadata['Info']).splitlines() + scaleXY = float(metadata[-4].split()[2])*1000000 + scaleZ = float(metadata[-2].split()[2])*1000000 + except: + scaleXY = 0.25 + scaleZ = 1 + image = img.asarray() + img.close() + return image, scaleXY, scaleZ, names + +def arrange_dims(image, verbose=True): + ## test if there is a chanel dimension. If yes, put it first in the order + if len(image.shape)>3: + chanpos = np.where(image.shape==np.min(image.shape))[0][0] + if chanpos != 0: + image = image.swapaxes(chanpos, 0) + + ## if there is no chanel dimension, add one to always have one + if image.shape[0]>5: + image = np.expand_dims(image, axis=0) + + if verbose: + print("Image dimensions: "+str(image.shape)) + + return image + +def extract_names(imagepath, subname="results"): + imgname = os.path.splitext(os.path.basename(imagepath))[0] + imgdir = os.path.dirname(imagepath) + resdir = os.path.join(imgdir, subname) + if not os.path.exists(resdir): + os.makedirs(resdir) + return imgname, imgdir, resdir + +def open_image(imagepath, verbose=True): + imagename = os.path.splitext(os.path.basename(imagepath))[0] + ext = os.path.splitext(imagepath)[1] + if ext == ".ims": + return openims(imagepath, verbose) + elif ext == ".czi": + return openczi(imagepath, verbose) + elif (ext == ".tif") or (ext == ".tiff"): + return opentif(imagepath, verbose) + else: + print("Image format not implemented yet") + +def select_slices(image, bestz, scaleZ, zmargin=10, rm_empty=True, verbose=True): + """ Keep only slices around bestz and slices that contain signal """ + + dz = int(zmargin/scaleZ) ## keep 10 microns under and above reference z + limLz = max(bestz-int(dz),0) + limHz = min(bestz+dz, (image[0,:,0,0].size)) + if verbose: + print("Z limits "+str(limLz)+" "+str(limHz)) + + ## Remove slices with nearly nothing + if rm_empty: + simage = np.sum(image, axis=0) + zsimage = np.sum(simage, axis=1) + zsimage = np.sum(zsimage, axis=1) + empty = zsimage<np.mean(zsimage)-1*np.std(zsimage) + while empty[limLz] and limLz<limHz: + limLz += 1 + while empty[limHz-1] and limHz>limLz: + limHz = limHz - 1 + + if verbose: + print("Final Z limits "+str(limLz)+" "+str(limHz)) + + image = image[:,limLz:limHz,:,:] + bestz = bestz-limLz + if verbose: + print('Global reference z: '+str(bestz)) + return image, bestz + diff --git a/src/napari_3dtimereg/__init__.py b/src/napari_3dtimereg/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/src/napari_3dtimereg/__init__.py @@ -0,0 +1 @@ + diff --git a/src/napari_3dtimereg/movieRegistration.py b/src/napari_3dtimereg/movieRegistration.py new file mode 100755 index 0000000000000000000000000000000000000000..29bb0dc39ce92e1c8a37187074a42e1a5f2aaf80 --- /dev/null +++ b/src/napari_3dtimereg/movieRegistration.py @@ -0,0 +1,378 @@ +import napari +import tifffile +from magicgui import magicgui +from napari.utils.notifications import show_info +import itk +import random +import numpy as np +import pathlib +import os, glob +import napari_3dtimereg.Utils as ut +from qtpy.QtWidgets import QFileDialog +from napari.utils.history import get_save_history, update_save_history +from webbrowser import open_new_tab + + +def get_filename(): + dialog = QFileDialog(caption="Choose reference image") + hist = get_save_history() + dialog.setHistory(hist) + dialog.setFileMode(QFileDialog.ExistingFile) + dialog.setDirectory(hist[0]) + if dialog.exec_(): + filename = dialog.selectedFiles() + if filename: + return filename[0] + else: + return None + +def start(): + global viewer, aligndir, imagedir + global refimg, refchanel + global img, resimg + global imagename + global scaleXY, scaleZ + refchanel = 0 + viewer = napari.current_viewer() + viewer.title = "3dTimeReg" + filename = get_filename() + if filename is None: + print("No file selected") + return + refimg, scaleXY, scaleZ, names = ut.open_image(filename, verbose=True) + print(refimg.shape) + imagename, imagedir, aligndir = ut.extract_names( filename, subname="aligned" ) + update_save_history(imagedir) + for chan in range(refimg.shape[2]): + cmap = ut.colormapname(chan) + cview = viewer.add_image( refimg[:,:,chan,:,:], name="Movie_"+"C"+str(chan), blending="additive", colormap = cmap ) + quants = tuple( np.quantile( refimg[:,:,chan,:,:], [0.01, 0.9999]) ) + cview.contrast_limits = quants + cview.gamma = 0.95 + return getChanels() + +def getChanels(): + + @magicgui(call_button="Update", + reference_chanel={"widget_type": "Slider", "min":0, "max": refimg.shape[2]-1}, + ) + def get_chanel( reference_chanel=0 , ): + global refchanel + global img, resimg + viewer.window.remove_dock_widget("all") + refchanel = reference_chanel + for chan in range(refimg.shape[0]): + layname = "Movie_"+"C"+str(chan) + if chan != refchanel: + if layname in viewer.layers: + viewer.layers.remove(layname) + else: + img = np.copy(refimg[:,:,chan,:,:]) + if layname in viewer.layers: + viewer.layers.remove(layname) + viewer.add_image( img, name=layname, blending="additive", colormap = "red" ) + else: + viewer.layers[layname].colormap = "red" + #ut.writeTif( refimg[chan,], os.path.join(aligndir,imagename+"_C"+str(chan)+".tif"), scaleXY, scaleZ, "uint16" ) + if "Do registration" not in viewer.window._dock_widgets: + resimg = np.copy(img) + resimg[0] = resimg[0] - np.min(resimg[0]) + cview = viewer.add_image( resimg, name="ResMovie", blending="additive", colormap = "red") + quants = tuple( np.quantile( resimg, [0.01, 0.9999]) ) + cview.contrast_limits = quants + do_registration() + + wid = viewer.window.add_dock_widget(get_chanel, name="Choose chanel") + return wid + +def itk_to_layer(img, name, color): + lay = layer_from_image(img) + lay.blending = "additive" + lay.colormap = color + lay.name = name + viewer.add_layer( lay ) + +def do_registration(): + + def calc_registration( time ): + """ Calculate the registration between two consecutive frames """ + global resimg + global results_transform_parameters_aff, results_transform_parameters + if get_paras.first_frame.value == True: + fimage = itk.image_view_from_array((resimg[0])) + else: + fimage = itk.image_view_from_array((resimg[time-1])) + fimage = fimage.astype(itk.F) + mimage = itk.image_view_from_array((resimg[time])) + mimage = mimage.astype(itk.F) + affimage = mimage + + elastix_object = None + + if get_paras.do_rigid.value == True: + parameter_object = None + parameter_object = itk.ParameterObject.New() + parameter_map_rigid = parameter_object.GetDefaultParameterMap('rigid') + parameter_map_rigid['MaximumNumberOfIterations'] = [str(get_paras.iterations.value)] + parameter_map_rigid['MaximumStepLength'] = [str(get_paras.max_step_length.value)] + parameter_map_rigid["NumberOfResolutions"] = [str(get_paras.resolution.value)] + parameter_map_rigid['NumberOfSpatialSamples'] = ['8000'] + parameter_map_rigid['MaximumNumberOfSamplingAttempts'] = ['8'] + parameter_map_rigid['RequiredRatioOfValidSamples'] = ['0.05'] + parameter_map_rigid['CheckNumberOfSamples'] = ['false'] + parameter_map_rigid['FinalGridSpacingInPhysicalUnits'] = [str(get_paras.final_spacing.value)] + parameter_map_rigid['Registration'] = ['MultiMetricMultiResolutionRegistration'] + parameter_map_rigid["AutomaticTransformInitialization"] = ['true'] + parameter_map_rigid["AutomaticTransformInitializationMethod"] = ['CenterOfGravity'] + gridspace = [str(int(get_paras.spacing_one.value)*4)] + resolution = int(get_paras.resolution.value) + if resolution > 1: + gridspace.append(str(int(get_paras.spacing_two.value)*2)) + if resolution > 2: + gridspace.append(str(int(get_paras.spacing_three.value)*2)) + if resolution > 3: + gridspace.append(str(int(get_paras.spacing_four.value)*1)) + if resolution > 4: + gridspace.append(str(int(get_paras.spacing_four.value))) + parameter_map_rigid['GridSpacingSchedule'] = gridspace + original_metric = parameter_map_rigid['Metric'] + parameter_object.AddParameterMap(parameter_map_rigid) + + elastix_object = None + elastix_object = itk.ElastixRegistrationMethod.New(fimage, mimage) + elastix_object.SetParameterObject(parameter_object) + + # Set additional options + elastix_object.SetLogToConsole(get_paras.show_log.value==True) + + # Update filter object (required) + elastix_object.UpdateLargestPossibleRegion() + + # Results of Registration + affimage = elastix_object.GetOutput() + results_transform_parameters_aff = elastix_object.GetTransformParameterObject() + + # Show intermediate layer + if get_paras.show_intermediate_layer.value==True: + resimage = affimage + resclayer = layer_from_image(resimage) + resclayer.blending = "additive" + resclayer.name = "AfterAffineRegistration" + viewer.add_layer( resclayer ) + + # first rigid transformation + if get_paras.do_bspline.value == True: + parameter_object = None + preset = "bspline" + parameter_object = itk.ParameterObject.New() + parameter_map = parameter_object.GetDefaultParameterMap(preset) + parameter_map["NumberOfResolutions"] = [str(get_paras.resolution.value)] + parameter_map["WriteIterationInfo"] = ["false"] + parameter_map['MaximumStepLength'] = [str(get_paras.max_step_length.value)] + parameter_map['NumberOfSpatialSamples'] = ['10000'] + parameter_map['MaximumNumberOfSamplingAttempts'] = ['10'] + parameter_map['RequiredRatioOfValidSamples'] = ['0.05'] + parameter_map['MaximumNumberOfIterations'] = [str(get_paras.iterations.value)] + parameter_map['FinalGridSpacingInPhysicalUnits'] = [str(get_paras.final_spacing.value)] + parameter_map['FinalBSplineInterpolationOrder'] = [str(3)] + parameter_map['BSplineInterpolationOrder'] = [str(3)] + parameter_map['HowToCombineTransform'] = ['Compose'] + gridspace = [str(get_paras.spacing_one.value)] + resolution = int(get_paras.resolution.value) + if resolution > 1: + gridspace.append(str(get_paras.spacing_two.value)) + if resolution > 2: + gridspace.append(str(get_paras.spacing_three.value)) + if resolution > 3: + gridspace.append(str(get_paras.spacing_four.value)) + if resolution > 4: + gridspace.append(str(int(get_paras.spacing_four.value/2))) + parameter_map['GridSpacingSchedule'] = gridspace + parameter_object.AddParameterMap(parameter_map) + + # Load Elastix Image Filter Object + elastix_object = itk.ElastixRegistrationMethod.New(fimage, affimage) + elastix_object.SetParameterObject(parameter_object) + elastix_object.SetLogToConsole(get_paras.show_log.value==True) + + # Update filter object (required) + elastix_object.UpdateLargestPossibleRegion() + + # Results of Registration + result_image = elastix_object.GetOutput() + results_transform_parameters = elastix_object.GetTransformParameterObject() + + data = (itk.array_view_from_image(result_image)) + #data = data - np.min(data) + data[data<0] = 0 + data = np.array(data) + resimg[time] = data + viewer.layers["ResMovie"].refresh() + + ut.writeTif( data, os.path.join(aligndir, imagename+"_C"+str(refchanel)+"_T"+"{:02d}".format(time)+".tif"), scaleXY, scaleZ, "uint16" ) + if time == 1: + ut.writeTif( resimg[0], os.path.join(aligndir, imagename+"_C"+str(refchanel)+"_T"+"{:02d}".format(0)+".tif"), scaleXY, scaleZ, "uint16" ) + + + @magicgui(call_button="Go", + max_step_length={"widget_type":"LiteralEvalLineEdit"}, + resolution={"widget_type":"LiteralEvalLineEdit"}, + iterations={"widget_type":"LiteralEvalLineEdit"}, + final_spacing={"widget_type":"LiteralEvalLineEdit"}, + spacing_one={"widget_type":"LiteralEvalLineEdit"}, + spacing_two={"widget_type":"LiteralEvalLineEdit"}, + spacing_three={"widget_type":"LiteralEvalLineEdit"}, + spacing_four={"widget_type":"LiteralEvalLineEdit"}, + ) + def get_paras( show_log = True, + do_rigid = True, + do_bspline = True, + first_frame = False, + show_advanced_parameters = False, + show_intermediate_layer = False, + resolution=4, + max_step_length = 2, + iterations=850, + final_spacing=100, + spacing_one=8, + spacing_two=4, + spacing_three=2, + spacing_four=1, + ): + + global results_transform_parameters_aff, results_transform_parameters + movlay = viewer.layers["Movie_C"+str(refchanel)] + results_transform_para_aff = None + + for t in range(movlay.data.shape[0]-1): + time = t + 1 + print("Calculate registration for time point "+str(time)) + calc_registration(time) + apply_alignement(time) + + + + def show_advanced(booly): + get_paras.show_intermediate_layer.visible = booly + get_paras.resolution.visible = booly + get_paras.max_step_length.visible = booly + get_paras.iterations.visible = booly + get_paras.final_spacing.visible = booly + get_paras.spacing_one.visible = booly + get_paras.spacing_two.visible = booly + get_paras.spacing_three.visible = booly + get_paras.spacing_four.visible = booly + + show_advanced(False) + get_paras.show_advanced_parameters.changed.connect(show_advanced) + wid = viewer.window.add_dock_widget(get_paras, name="Calculate alignement") + return wid + +def layer_from_image(img): + data = np.array(itk.array_view_from_image(img)) + image_layer = napari.layers.Image(data) + return image_layer + +def apply_alignement(time): + global results_transform_parameters_aff, results_transform_parameters + chanellist = list(range(refimg.shape[2])) + align_chanels = [] + for chan in chanellist: + if chan != refchanel: + align_chanels.append(chan) + + print("Apply alignment to "+str(align_chanels)) + for chan in align_chanels: + img = refimg[time,:,chan,:,:] + res = [] + itkimage = itk.image_view_from_array(img) + itkimage = itkimage.astype(itk.F) + ImageType = itk.Image[itk.F, 3] + if results_transform_parameters_aff is not None: + transformix_filter = itk.TransformixFilter[ImageType].New() + transformix_filter.SetMovingImage(itkimage) + transformix_filter.SetTransformParameterObject(results_transform_parameters_aff) + aff_image = transformix_filter.GetOutput() + else: + aff_image = image + + if results_transform_parameters is not None: + transformix = itk.TransformixFilter[ImageType].New() + transformix.SetMovingImage(aff_image) + transformix.SetTransformParameterObject(results_transform_parameters) + res_image = transformix.GetOutput() + else: + res_image = aff_image + + res = itk.array_from_image(res_image) + res[res<0] = 0 + res = np.array(res) + res = np.uint16(res) + + ut.writeTif( res, os.path.join(aligndir, imagename+"_C"+str(chan)+"_T"+"{:02d}".format(time)+".tif"), scaleXY, scaleZ, "uint16" ) + if time == 1: + ut.writeTif( refimg[0,:,chan,:,:], os.path.join(aligndir, imagename+"_C"+str(chan)+"_T"+"{:02d}".format(0)+".tif"), scaleXY, scaleZ, "uint16" ) + +def finish_image(): + global movimg + remove_widget("Calculate alignement") + remove_layer("movingPoints") + remove_layer("movingImg"+"_C"+str(refchanel)) + #for chan in range(movimg.shape[0]): + # remove_layer("imageAligned"+str(chan)) + remove_layer("alignedMovingImg") + del movimg + remove_widget("Apply alignement") + +def remove_layer(layname): + if layname in viewer.layers: + viewer.layers.remove(layname) + +def remove_widget(widname): + if widname in viewer.window._dock_widgets: + wid = viewer.window._dock_widgets[widname] + wid.setDisabled(True) + del viewer.window._dock_widgets[widname] + wid.destroyOnClose() + +def create_result_image(): + allist = sorted(glob.glob(os.path.join(aligndir, "*_C*.tif"))) + allist = [os.path.basename(ref) for ref in allist] + reflist = sorted(glob.glob(os.path.join(aligndir, "*_C"+str(refchanel)+".tif"))) + reflist = [os.path.basename(ref) for ref in reflist] + filelist = sorted(glob.glob(os.path.join(aligndir, "*_C"+"[!"+str(refchanel)+"].tif"))) + filelist = [os.path.basename(chanfile) for chanfile in filelist] + remove_widget("Do Image") + + @magicgui(call_button = "Create Image", + average_chanels = dict(widget_type="Select", choices=allist), + add_chanels = dict(widget_type="Select", choices=allist), ) + def get_files(average_chanels=reflist, add_chanels=filelist, delete_files=True): + resimg = np.zeros((len(add_chanels)+1,)+refimg.shape[1:]) + for refchan in average_chanels: + img, tscaleXY, tscaleZ, names = ut.open_image(os.path.join(aligndir,refchan), verbose=False) + resimg = resimg + img + if delete_files: + os.remove(os.path.join(aligndir,refchan)) + resimg = resimg/len(average_chanels) + + ind = 1 + for chan in add_chanels: + img, tscaleXY, tscaleZ, names = ut.open_image(os.path.join(aligndir,chan), verbose=False) + resimg[ind,] = img + ind = ind + 1 + if delete_files: + os.remove(os.path.join(aligndir,chan)) + + viewer.add_image(resimg, name="Res", blending="additive") + for lay in viewer.layers: + if lay.name != "Res": + remove_layer(lay) + imgname = os.path.join(aligndir, imagename+".tif") + resimg = np.array(resimg, "uint16") + # move the chanel axis after the Z axis (imageJ format) + resimg = np.moveaxis(resimg, 0, 1) + tifffile.imwrite(imgname, resimg, imagej=True, resolution=[1./scaleXY, 1./scaleXY], metadata={'PhysicalSizeX': scaleXY, 'spacing': scaleZ, 'unit': 'um', 'axes': 'ZCYX'}) + show_info("Image "+imgname+" saved") + + viewer.window.add_dock_widget(get_files, name="Choose chanels") diff --git a/src/napari_3dtimereg/napari.yaml b/src/napari_3dtimereg/napari.yaml new file mode 100755 index 0000000000000000000000000000000000000000..cc2505252a38d37daec70203a2864554c0ae5d61 --- /dev/null +++ b/src/napari_3dtimereg/napari.yaml @@ -0,0 +1,11 @@ +name: napari-3dtimereg +display_name: 3D Movies Registration +contributions: + commands: + - id: napari-3dtimereg.registration + python_name: napari_3dtimereg.movieRegistration:start + title: 3D Movies Registration + widgets: + - command: napari-3dtimereg.registration + autogenerate: false + display_name: Do 3D movie registration