Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • first-upload
  • main
2 results

Target

Select target project
  • QIM/tools/3d-shape-analysis-using-persistent-homology
1 result
Select Git revision
  • first-upload
  • main
2 results
Show changes

Commits on Source 2

Showing
with 18493 additions and 76 deletions
This diff is collapsed.
# 3D Shape Analysis using Persistent Homology
This is the official code accompanying our paper **Extracting Mitochondrial Cristae Characteristics from 3D Focused Ion Beam Scanning Electron Microscopy Data**.
## Getting started
## Persistent Homology Toolset
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
The persistent homology toolset provided here can be directly used for the shape analysis of other object types, and is not restricted to the mitochondria and their cristae.
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)!
Open "3D Shape Analysis using Persistent Homology.ipynb" to get started.
## Add your files
If you would like to run our real world example locally on your machine:
- please download the [data](https://erda.dk) ("cristae_volume.npy", "intracristal_volume.npy", and "mito_volume.npy")
- and unzip them into the "/binary_segmentation_masks" subfolder
- [ ] [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://lab.compute.dtu.dk/QIM/tools/3d-shape-analysis-using-persistent-homology.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
## Segmentation Model
- [ ] [Set up project integrations](https://lab.compute.dtu.dk/QIM/tools/3d-shape-analysis-using-persistent-homology/-/settings/integrations)
For completeness, we also included our multiplanar segmentation model for mitochondria and cristae in the "/other/segmentation_model" folder.
## Collaborate with your team
You won't need this part of the code, if your project is not related to mitochondria and cristae, or if you have your own segmentations already.
- [ ] [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/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
If you do decide to use our segmentation code:
- You need to first perform image registration to align the slices in your image volume.
- Place the registered image volume in "/raw_data/test" subfolder as a tiff file.
- Adjust the filename in the loading function in "segmentation_main".
## Test and Deploy
Please note that the raw output needs to be binarized and cleaned up. We do not provide the code for binarization and clean up, because the best procedure is likely to be specific to each image volume and should be simple enough to figure out.
Use the built-in continuous integration in GitLab.
The segmentation can take several days depending on the size of your image volume and your PC's computing power.
- [ ] [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!). Thank you 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.
## 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.
## 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.
## 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.
## 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.
## 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.
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.
## License
For open source projects, say how it is licensed.
## 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.
Our registration of the Lausanne dataset (https://www.epfl.ch/labs/cvlab/data/data-em/) can be downloaded [here](https://erda.dk), and this is the volume which we segmented for analysis.
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Extracting Mitochondrial Cristae Characteristics from 3D Focused Ion Beam Scanning Electron Microscopy Data
Chenhao Wang, Leif Østergaard, Stine Hasselholt, Jon Sporring
https://doi.org/10.1101/2022.11.08.515664
"""
# Imports
import os
import warnings
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
from mpl_toolkits.axes_grid1 import make_axes_locatable
###########################################################################
# folder paths
root_folder = os.getcwd()
###########################################################################
# file management functions
def setpath(path):
'''
changes working directory, creates folder if path doesn't exist
'''
try:
os.chdir(path)
except OSError:
os.makedirs(path)
os.chdir(path)
def all_file_names(folder, file_format = None):
'''
list all image filenames of a given format in a folder,
if file_format == None, returns all files regardless of format.
'''
if file_format is None:
names = os.listdir(folder)
else:
names = os.listdir(folder)
for name in names:
if name[-len(file_format):] != file_format:
names.remove(name)
return names
###########################################################################
# image visualization
def visualize_jet(img, max_val = 0.0000005):
plt.figure(figsize = (15,15))
#plt.imshow(img, cmap='jet')
ax = plt.gca()
im = ax.imshow(img, cmap='jet')
im.set_clim(vmin = 0, vmax=max_val)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
ax.tick_params(labelsize=12)
plt.tick_params(labelsize=15)
def visualize(img):
plt.figure(figsize = (15,15))
plt.imshow(img, cmap='gray')
File added
File added
This diff is collapsed.
This diff is collapsed.
# -*- coding: utf-8 -*-
"""
General Support Functions - version 1.0
@author: Chenhao Wang
@date: June 2021
"""
import os
import cv2
import numpy as np
from tqdm import tqdm
import warnings
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
from mpl_toolkits.axes_grid1 import make_axes_locatable
import skimage.io as skio
###########################################################################
# folder paths
root_folder = os.getcwd()
raw_folder = root_folder + '/raw_data'
raw_folder_train_img = raw_folder + "/train" + "/images"
raw_folder_train_mask = raw_folder + "/train" + "/masks"
raw_folder_valid_img = raw_folder + "/valid" + "/images"
raw_folder_valid_mask = raw_folder + "/valid" + "/masks"
cross_val_train_img_folder = root_folder + "\\x_val" + "\\train\\images"
cross_val_train_mask_folder = root_folder + "\\x_val" + "\\train\\masks"
cross_val_valid_img_folder = root_folder + "\\x_val" + "\\valid\\images"
cross_val_valid_mask_folder = root_folder + "\\x_val" + "\\valid\\masks"
cross_val_valid_img_augmented_folder = raw_folder + "\\x_val" + "\\valid_augmented\\images"
cross_val_valid_mask_augmented_folder = raw_folder + "\\x_val" + "\\valid_augmented\\masks"
cross_val_test_img_folder = root_folder + "\\x_val" + "\\test\\images"
cross_val_test_mask_folder = root_folder + "\\x_val" + "\\test\\prediction"
full_sized_folder = root_folder + "/full_sized_data"
full_sized_folder_train_img = full_sized_folder + "/train" + "/images"
full_sized_folder_train_mask = full_sized_folder + "/train" + "/masks"
full_sized_folder_valid_img = full_sized_folder + "/valid" + "/images"
full_sized_folder_valid_mask = full_sized_folder + "/valid" + "/masks"
cristae_image_folder = root_folder + "/cristae_annotation" + "/images"
cristae_mask_folder = root_folder + "/cristae_annotation" + "/masks"
test_folder = raw_folder + '/test'
results_folder = root_folder + '/results'
###########################################################################
# file management functions
def setpath(path):
'''
changes working directory, creates folder if path doesn't exist
'''
try:
os.chdir(path)
except OSError:
os.makedirs(path)
os.chdir(path)
def all_file_names(folder, file_format = None):
'''
list all image filenames of a given format in a folder,
if file_format == None, returns all files regardless of format.
'''
if file_format is None:
names = os.listdir(folder)
else:
names = os.listdir(folder)
for name in names:
if name[-len(file_format):] != file_format:
names.remove(name)
return names
###########################################################################
# image data loaders
def load_volume_data_slices(folder_path):
"""
loads all the image slices in the specified folder of a single image volume.
"""
setpath(folder_path)
file_names = all_file_names(folder_path)
output_collection = []
for name in tqdm(file_names):
img = cv2.imread(name, cv2.IMREAD_GRAYSCALE)
output_collection.append(img)
output_collection = np.array(output_collection)
return file_names, output_collection
def load_volume_data_slices_color(folder_path):
"""
loads all the image slices in the specified folder of a single image volume.
"""
setpath(folder_path)
file_names = all_file_names(folder_path)
output_collection = []
for name in tqdm(file_names):
img = cv2.imread(name)
output_collection.append(img)
output_collection = np.array(output_collection)
return file_names, output_collection
def load_volume_data_tif_stacks(input_path,
file_name):
"""
loads all the image slices in the specified folder of a single image volume.
"""
setpath(input_path)
img_stack = skio.imread(file_name, plugin="tifffile")
return img_stack
def save_img_as_slices(volume,
output_path,
initial_tag = None):
setpath(output_path)
for i, img_slice in enumerate(tqdm(volume)):
if i < 10:
save_name = "0000" + str(i) + ".png"
elif i < 100:
save_name = "000" + str(i) + ".png"
elif i < 1000:
save_name = "00" + str(i) + ".png"
elif i < 10000:
save_name = "0" + str(i) + ".png"
else:
save_name = str(i) + ".png"
if initial_tag != None:
save_name = initial_tag + save_name
cv2.imwrite(save_name, img_slice)
"""
Image saving function
"""
###########################################################################
# image visualization
def visualize_jet(img, max_val = 0.0000005):
plt.figure(figsize = (15,15))
#plt.imshow(img, cmap='jet')
ax = plt.gca()
im = ax.imshow(img, cmap='jet')
im.set_clim(vmin = 0, vmax=max_val)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
ax.tick_params(labelsize=12)
plt.tick_params(labelsize=15)
def visualize(img):
plt.figure(figsize = (15,15))
plt.imshow(img, cmap='gray')
###########################################################################
# image filtering
def multiple_slice_gaussian_denoise(image_array,
temporal_size = 3,
filter_strength = 0.5):
"""denoise gaussian white noise using Non-local Means Denoising algorithm:
http://www.ipol.im/pub/art/2011/bcm_nlm/
Multiframe version.
"""
image_array_denoised = []
margin = int(temporal_size/2)
for i in tqdm(range(margin, len(image_array) - margin)):
# performs multiple frame denoising
noise_filtered = cv2.fastNlMeansDenoisingMulti(image_array,
imgToDenoiseIndex = i,
temporalWindowSize = temporal_size,
h = filter_strength)
image_array_denoised.append(noise_filtered)
return np.array(image_array_denoised)
def adaptive_thresholding_gaussian(image_volume,
win_size = 41,
c = 2,
max_intensity_value = 255):
output = []
for image in tqdm(image_volume):
threshold = cv2.adaptiveThreshold(image,
max_intensity_value,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,
win_size,
c)
threshold = 1 - threshold/threshold.max()
output.append(threshold)
return np.array(output)
###########################################################################
# image filtering
def cut_images_into_patches_2D(input_path,
mask_path,
output_path,
patch_size,
patch_step_ratio_v = 2,
patch_step_ratio_h = 2):
"""
cuts images into patches:
patch_step_size = patch_size / patch_step_ratio
"""
input_names, input_volume = load_volume_data_slices(input_path)
mask_names, mask_volume = load_volume_data_slices(mask_path)
patch_step_size_v = int((patch_size[0]/patch_step_ratio_v))
patch_step_size_h = int((patch_size[1]/patch_step_ratio_h))
img_slice_shape = input_volume[0].shape
v_starting_coors = np.arange(int((img_slice_shape[0] - patch_size[0])
/patch_step_size_v) + 1)*patch_step_size_v
h_starting_coors = np.arange(int((img_slice_shape[1] - patch_size[1])
/patch_step_size_h) + 1)*patch_step_size_h
setpath(output_path)
for index in tqdm(range(len(input_volume))):
raw_img = input_volume[index]
raw_mask = mask_volume[index]
raw_name = input_names[index]
for i in v_starting_coors:
for j in h_starting_coors:
img_patch = raw_img[i : i + patch_size[0],
j : j + patch_size[1]]
mask_patch = raw_mask[i : i + patch_size[0],
j : j + patch_size[1]]
if np.sum(mask_patch) > 0:
patch_save_name = raw_name.split(".")[0] + "_" + str(i) + "_" + str(j) + "." + raw_name.split(".")[1]
cv2.imwrite(patch_save_name, img_patch)
def cut_images_into_patches_2D_stack(input_path,
mask_path,
img_file_name,
mask_file_name,
output_path,
patch_size,
patch_step_ratio_v = 2,
patch_step_ratio_h = 2,
intial_tag = "train_img_"):
"""
cuts images into patches:
patch_step_size = patch_size / patch_step_ratio
"""
input_volume = load_volume_data_tif_stacks(input_path,
img_file_name)
mask_volume = load_volume_data_tif_stacks(mask_path,
mask_file_name)
patch_step_size_v = int((patch_size[0]/patch_step_ratio_v))
patch_step_size_h = int((patch_size[1]/patch_step_ratio_h))
img_slice_shape = input_volume[0].shape
v_starting_coors = np.arange(int((img_slice_shape[0] - patch_size[0])
/patch_step_size_v) + 1)*patch_step_size_v
h_starting_coors = np.arange(int((img_slice_shape[1] - patch_size[1])
/patch_step_size_h) + 1)*patch_step_size_h
setpath(output_path)
for index in tqdm(range(len(input_volume))):
raw_img = input_volume[index]
raw_mask = mask_volume[index]
for i in v_starting_coors:
for j in h_starting_coors:
img_patch = raw_img[i : i + patch_size[0],
j : j + patch_size[1]]
mask_patch = raw_mask[i : i + patch_size[0],
j : j + patch_size[1]]
if np.sum(mask_patch) > 0:
patch_save_name = intial_tag + str(index) + "_" + str(i) + "_" + str(j) + ".png"
cv2.imwrite(patch_save_name, img_patch)
# -*- coding: utf-8 -*-
"""
@author: CWANG
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from deep_learning_support import *
import skimage.io as skio
# todos
if_segment_mito = True
if_segment_cristae = True
# params
batch_size = 2
epoch = 3000
patch_size = (256, 256, 256, 3)
patch_step_ratio_v = 2
patch_step_ratio_h = 2
model_pretrained_name = "unet_2D_mito.hdf5"
model_save_name = "unet_2D_cristae_multiclass.hdf5"
# multiplanar segmentation todos
overlap_factor_normal = 3
overlap_factor_small = 2
if if_segment_mito == True:
volume_names = all_file_names(test_folder, file_format = None)
setpath(test_folder)
test_volume = skio.imread(volume_names[0], plugin="tifffile")
perform_memory_efficient_multiplanar_segmentation_large(test_volume,
model_pretrained_name,
sub_vol_start_index = 0,
sub_vol_end_index = None,
custom_loss = 'IOU_loss',
overlap_factor = 2,
patch_size = (256, 256, 256, 1),
results_folder = '/mito_subvolume_result')
merge_sub_volumes(test_volume,
patch_size = (256, 256, 256, 1),
input_folder = '/mito_subvolume_result',
results_folder = '/mito_result')
if if_segment_cristae == True:
volume_names = all_file_names(test_folder, file_format = None)
setpath(test_folder)
test_volume = skio.imread(volume_names[0], plugin="tifffile")
perform_memory_efficient_multiplanar_segmentation_large(test_volume,
model_save_name,
sub_vol_start_index = 0,
sub_vol_end_index = None,
custom_loss = 'multiclass_IOU_loss',
overlap_factor = 2,
patch_size = (256, 256, 256, 3),
results_folder = '/cristae_subvolume_result')
merge_sub_volumes(test_volume,
patch_size = (256, 256, 256, 3),
input_folder = '/cristae_subvolume_result',
results_folder = '/cristae_result')
\ No newline at end of file
File added
File added
File added
This diff is collapsed.
# -*- coding: utf-8 -*-
"""
Extracting Mitochondrial Cristae Characteristics from 3D Focused Ion Beam Scanning Electron Microscopy Data
Chenhao Wang, Leif Østergaard, Stine Hasselholt, Jon Sporring
https://doi.org/10.1101/2022.11.08.515664
"""
# Imports
import numpy as np
import matplotlib.pyplot as plt
##################################################
# basic functions
def U_ip1(U):
U_new = np.copy(U)
U_new[:-1] = U[1:]
return U_new
def U_im1(U):
U_new = np.copy(U)
U_new[1:] = U[:-1]
return U_new
def U_jp1(U):
U_new = np.copy(U)
U_new[:, :-1] = U[:, 1:]
return U_new
def U_jm1(U):
U_new = np.copy(U)
U_new[:, 1:] = U[:, :-1]
return U_new
def U_kp1(U):
U_new = np.copy(U)
U_new[:, :, :-1] = U[:, :, 1:]
return U_new
def U_km1(U):
U_new = np.copy(U)
U_new[:, :, 1:] = U[:, :, :-1]
return U_new
##################################################
# Subpixel Morphology
def subpixel_dilation_2D(I,
t,
Lambda):
U = I.astype(np.float32)
max_iter = int(np.ceil(t/Lambda))
Lambda = t/max_iter
for i in range(max_iter):
U = U + Lambda * np.sqrt(np.square(np.clip(U_ip1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_im1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_jp1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_jm1(U) - U, a_min = 0, a_max = None)))
# regularization steps
U[U > 1] = 1
U[U < 0] = 0
# enforces float32
U = U.astype(np.float32)
return U
def subpixel_erosion_2D(I,
t,
Lambda):
U = I.astype(np.float32)
max_iter = int(np.ceil(t/Lambda))
Lambda = t/max_iter
for i in range(max_iter):
U = U - Lambda * np.sqrt(np.square(np.clip(U - U_ip1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_im1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_jp1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_jm1(U), a_min = 0, a_max = None)))
# regularization steps
U[U > 1] = 1
U[U < 0] = 0
# enforces float32
U = U.astype(np.float32)
return U
def subpixel_dilation_3D(I,
t,
Lambda):
U = I.astype(np.float32)
max_iter = int(np.ceil(t/Lambda))
Lambda = t/max_iter
for i in range(max_iter):
U = U + Lambda * np.sqrt(np.square(np.clip(U_ip1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_im1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_jp1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_jm1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_kp1(U) - U, a_min = 0, a_max = None)) +
np.square(np.clip(U_km1(U) - U, a_min = 0, a_max = None)))
# regularization steps
U[U > 1] = 1
U[U < 0] = 0
# enforces float32
U = U.astype(np.float32)
return U
def subpixel_erosion_3D(I,
t,
Lambda):
U = I.astype(np.float32)
max_iter = int(np.ceil(t/Lambda))
Lambda = t/max_iter
for i in range(max_iter):
U = U - Lambda * np.sqrt(np.square(np.clip(U - U_ip1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_im1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_jp1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_jm1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_kp1(U), a_min = 0, a_max = None)) +
np.square(np.clip(U - U_km1(U), a_min = 0, a_max = None)))
# regularization steps
U[U > 1] = 1
U[U < 0] = 0
# enforces float32
U = U.astype(np.float32)
return U