Skip to content
Snippets Groups Projects
Commit d6bb97ff authored by polarbean's avatar polarbean
Browse files

add testing framework

parent b1a73a14
No related branches found
No related tags found
No related merge requests found
Showing
with 308 additions and 182 deletions
from .main import PyNutil
\ No newline at end of file
from .main import PyNutil
......@@ -67,6 +67,7 @@ def transform_to_registration(seg_height, seg_width, reg_height, reg_width):
x_scale = reg_width / seg_width
return y_scale, x_scale
# related to coordinate extraction
def find_matching_pixels(segmentation, id):
"""This function returns the Y and X coordinates of all the pixels in the segmentation that match the id provided."""
......@@ -207,14 +208,14 @@ def folder_to_atlas_space(
[t.join() for t in threads]
# Flatten points_list
points_len = [
len(points) if None not in points else 0 for points in points_list
]
points_len = [len(points) if None not in points else 0 for points in points_list]
centroids_len = [
len(centroids) if None not in centroids else 0 for centroids in centroids_list
]
len(centroids) if None not in centroids else 0 for centroids in centroids_list
]
points_list = [points for points in points_list if None not in points]
centroids_list = [centroids for centroids in centroids_list if None not in centroids]
centroids_list = [
centroids for centroids in centroids_list if None not in centroids
]
if len(points_list) == 0:
points = np.array([])
else:
......@@ -224,7 +225,6 @@ def folder_to_atlas_space(
else:
centroids = np.concatenate(centroids_list)
return (
np.array(points),
np.array(centroids),
......@@ -234,6 +234,7 @@ def folder_to_atlas_space(
segmentations,
)
def load_segmentation(segmentation_path: str):
"""Load a segmentation from a file."""
print(f"working on {segmentation_path}")
......@@ -243,6 +244,7 @@ def load_segmentation(segmentation_path: str):
else:
return cv2.imread(segmentation_path)
def detect_pixel_id(segmentation: np.array):
"""Remove the background from the segmentation and return the pixel id."""
segmentation_no_background = segmentation[~np.all(segmentation == 0, axis=2)]
......@@ -250,7 +252,17 @@ def detect_pixel_id(segmentation: np.array):
print("detected pixel_id: ", pixel_id)
return pixel_id
def get_region_areas(use_flat, atlas_labels, flat_file_atlas, seg_width, seg_height, slice_dict, atlas_volume, triangulation):
def get_region_areas(
use_flat,
atlas_labels,
flat_file_atlas,
seg_width,
seg_height,
slice_dict,
atlas_volume,
triangulation,
):
if use_flat:
region_areas = flat_to_dataframe(
atlas_labels, flat_file_atlas, (seg_width, seg_height)
......@@ -262,17 +274,30 @@ def get_region_areas(use_flat, atlas_labels, flat_file_atlas, seg_width, seg_hei
(seg_width, seg_height),
slice_dict["anchoring"],
atlas_volume,
triangulation
triangulation,
)
return region_areas
def get_transformed_coordinates(non_linear, slice_dict, method, scaled_x, scaled_y, centroids, scaled_centroidsX, scaled_centroidsY, triangulation):
def get_transformed_coordinates(
non_linear,
slice_dict,
method,
scaled_x,
scaled_y,
centroids,
scaled_centroidsX,
scaled_centroidsY,
triangulation,
):
new_x, new_y, centroids_new_x, centroids_new_y = None, None, None, None
if non_linear and "markers" in slice_dict:
if method in ["per_pixel", "all"] and scaled_x is not None:
new_x, new_y = transform_vec(triangulation, scaled_x, scaled_y)
if method in ["per_object", "all"] and centroids is not None:
centroids_new_x, centroids_new_y = transform_vec(triangulation, scaled_centroidsX, scaled_centroidsY)
centroids_new_x, centroids_new_y = transform_vec(
triangulation, scaled_centroidsX, scaled_centroidsY
)
else:
if method in ["per_pixel", "all"]:
new_x, new_y = scaled_x, scaled_y
......@@ -280,6 +305,7 @@ def get_transformed_coordinates(non_linear, slice_dict, method, scaled_x, scaled
centroids_new_x, centroids_new_y = scaled_centroidsX, scaled_centroidsY
return new_x, new_y, centroids_new_x, centroids_new_y
def segmentation_to_atlas_space(
slice_dict,
segmentation_path,
......@@ -305,20 +331,51 @@ def segmentation_to_atlas_space(
triangulation = triangulate(reg_width, reg_height, slice_dict["markers"])
else:
triangulation = None
region_areas = get_region_areas(use_flat, atlas_labels, flat_file_atlas, seg_width, seg_height, slice_dict, atlas_volume, triangulation)
y_scale, x_scale = transform_to_registration(seg_height, seg_width, reg_height, reg_width)
region_areas = get_region_areas(
use_flat,
atlas_labels,
flat_file_atlas,
seg_width,
seg_height,
slice_dict,
atlas_volume,
triangulation,
)
y_scale, x_scale = transform_to_registration(
seg_height, seg_width, reg_height, reg_width
)
centroids, points = None, None
scaled_centroidsX, scaled_centroidsY, scaled_x, scaled_y = None, None, None, None
scaled_centroidsX, scaled_centroidsY, scaled_x, scaled_y = None, None, None, None
if method in ["per_object", "all"]:
centroids, scaled_centroidsX, scaled_centroidsY = get_centroids(segmentation, pixel_id, y_scale, x_scale, object_cutoff)
centroids, scaled_centroidsX, scaled_centroidsY = get_centroids(
segmentation, pixel_id, y_scale, x_scale, object_cutoff
)
if method in ["per_pixel", "all"]:
scaled_y, scaled_x = get_scaled_pixels(segmentation, pixel_id, y_scale, x_scale)
new_x, new_y, centroids_new_x, centroids_new_y = get_transformed_coordinates(non_linear, slice_dict, method, scaled_x, scaled_y, centroids, scaled_centroidsX, scaled_centroidsY, triangulation)
new_x, new_y, centroids_new_x, centroids_new_y = get_transformed_coordinates(
non_linear,
slice_dict,
method,
scaled_x,
scaled_y,
centroids,
scaled_centroidsX,
scaled_centroidsY,
triangulation,
)
if method in ["per_pixel", "all"] and new_x is not None:
points = transform_to_atlas_space(slice_dict["anchoring"], new_y, new_x, reg_height, reg_width)
points = transform_to_atlas_space(
slice_dict["anchoring"], new_y, new_x, reg_height, reg_width
)
if method in ["per_object", "all"] and centroids_new_x is not None:
centroids = transform_to_atlas_space(slice_dict["anchoring"], centroids_new_y, centroids_new_x, reg_height, reg_width)
centroids = transform_to_atlas_space(
slice_dict["anchoring"],
centroids_new_y,
centroids_new_x,
reg_height,
reg_width,
)
points_list[index] = np.array(points if points is not None else [])
centroids_list[index] = np.array(centroids if centroids is not None else [])
region_areas_list[index] = region_areas
......
......@@ -5,6 +5,7 @@ import cv2
from .generate_target_slice import generate_target_slice
from .visualign_deformations import transform_vec
# related to counting and load
def label_points(points, label_volume, scale_factor=1):
"""This function takes a list of points and assigns them to a region based on the region_volume.
......@@ -119,7 +120,6 @@ def pixel_count_per_region(
"""Read flat file, write into an np array, assign label file values, return array"""
def read_flat_file(file):
with open(file, "rb") as f:
b, w, h = struct.unpack(">BII", f.read(9))
......@@ -163,6 +163,7 @@ def rescale_image(image, rescaleXY):
w, h = rescaleXY
return cv2.resize(image, (h, w), interpolation=cv2.INTER_NEAREST)
def assign_labels_to_image(image, labelfile):
w, h = image.shape
allen_id_image = np.zeros((h, w)) # create an empty image array
......@@ -186,7 +187,7 @@ def count_pixels_per_label(image, scale_factor=False):
def warp_image(image, triangulation, rescaleXY):
if rescaleXY is not None:
w,h = rescaleXY
w, h = rescaleXY
else:
h, w = image.shape
reg_h, reg_w = image.shape
......@@ -211,8 +212,14 @@ def warp_image(image, triangulation, rescaleXY):
new_image = image[newY, newX]
return new_image
def flat_to_dataframe(
labelfile, file=None, rescaleXY=None, image_vector=None, volume=None, triangulation=None
labelfile,
file=None,
rescaleXY=None,
image_vector=None,
volume=None,
triangulation=None,
):
if (image_vector is not None) and (volume is not None):
image = generate_target_slice(image_vector, volume)
......
import numpy as np
import math
def generate_target_slice(ouv, atlas):
width = None
height = None
ox, oy, oz, ux, uy, uz, vx, vy, vz = ouv
width = np.floor(math.hypot(ux,uy,uz)).astype(int) + 1
height = np.floor(math.hypot(vx,vy,vz)).astype(int) + 1
width = np.floor(math.hypot(ux, uy, uz)).astype(int) + 1
height = np.floor(math.hypot(vx, vy, vz)).astype(int) + 1
data = np.zeros((width, height), dtype=np.uint32).flatten()
xdim, ydim, zdim = atlas.shape
y_values = np.arange(height)
......@@ -17,10 +18,12 @@ def generate_target_slice(ouv, atlas):
wx = ux * (x_values / width)
wy = uy * (x_values / width)
wz = uz * (x_values / width)
lx = np.floor(hx[:, None] + wx).astype(int)
ly = np.floor(hy[:, None] + wy).astype(int)
lz = np.floor(hz[:, None] + wz).astype(int)
valid_indices = (0 <= lx) & (lx < xdim) & (0 <= ly) & (ly < ydim) & (0 <= lz) & (lz < zdim)
lx = np.floor(hx[:, None] + wx).astype(int)
ly = np.floor(hy[:, None] + wy).astype(int)
lz = np.floor(hz[:, None] + wz).astype(int)
valid_indices = (
(0 <= lx) & (lx < xdim) & (0 <= ly) & (ly < ydim) & (0 <= lz) & (lz < zdim)
)
valid_indices = valid_indices.flatten()
lxf = lx.flatten()
lyf = ly.flatten()
......@@ -28,8 +31,7 @@ def generate_target_slice(ouv, atlas):
valid_lx = lxf[valid_indices]
valid_ly = lyf[valid_indices]
valid_lz = lzf[valid_indices]
atlas_slice = atlas[valid_lx,valid_ly,valid_lz]
atlas_slice = atlas[valid_lx, valid_ly, valid_lz]
data[valid_indices] = atlas_slice
data_im = data.reshape((height, width))
return data_im
......@@ -109,11 +109,17 @@ class PyNutil:
self.colour = colour
self.atlas_name = atlas_name
if (atlas_path or label_path) and atlas_name:
raise ValueError("Please only specify an atlas_path and a label_path or an atlas_name, atlas and label paths are only used for loading custom atlases")
raise ValueError(
"Please only specify an atlas_path and a label_path or an atlas_name, atlas and label paths are only used for loading custom atlases"
)
if atlas_path and label_path:
self.atlas_volume, self.atlas_labels = self.load_custom_atlas(atlas_path, label_path)
self.atlas_volume, self.atlas_labels = self.load_custom_atlas(
atlas_path, label_path
)
else:
self.atlas_volume, self.atlas_labels = self.load_atlas_data(atlas_name=atlas_name)
self.atlas_volume, self.atlas_labels = self.load_atlas_data(
atlas_name=atlas_name
)
###This is just because of the migration to BrainGlobe
def load_atlas_data(self, atlas_name):
......@@ -129,22 +135,23 @@ class PyNutil:
# this could potentially be moved into init
print("loading atlas volume")
atlas = brainglobe_atlasapi.BrainGlobeAtlas(atlas_name=atlas_name)
atlas_structures = {'idx':[i['id'] for i in atlas.structures_list],
'name':[i['name'] for i in atlas.structures_list],
'r':[i['rgb_triplet'][0] for i in atlas.structures_list],
'g':[i['rgb_triplet'][1] for i in atlas.structures_list],
'b':[i['rgb_triplet'][2] for i in atlas.structures_list]
}
atlas_structures['idx'].insert(0,0)
atlas_structures['name'].insert(0,'Clear Label')
atlas_structures['r'].insert(0,0)
atlas_structures['g'].insert(0,0)
atlas_structures['b'].insert(0,0)
atlas_structures = {
"idx": [i["id"] for i in atlas.structures_list],
"name": [i["name"] for i in atlas.structures_list],
"r": [i["rgb_triplet"][0] for i in atlas.structures_list],
"g": [i["rgb_triplet"][1] for i in atlas.structures_list],
"b": [i["rgb_triplet"][2] for i in atlas.structures_list],
}
atlas_structures["idx"].insert(0, 0)
atlas_structures["name"].insert(0, "Clear Label")
atlas_structures["r"].insert(0, 0)
atlas_structures["g"].insert(0, 0)
atlas_structures["b"].insert(0, 0)
atlas_labels = pd.DataFrame(atlas_structures)
if "allen_mouse_" in atlas_name:
if "allen_mouse_" in atlas_name:
print("reorienting allen atlas into quicknii space...")
atlas_volume = np.transpose(atlas.annotation,[2,0,1])[:,::-1,::-1]
atlas_volume = np.transpose(atlas.annotation, [2, 0, 1])[:, ::-1, ::-1]
else:
atlas_volume = atlas.annotation
print("atlas labels loaded ✅")
......
from . import *
\ No newline at end of file
from . import *
......@@ -29,8 +29,6 @@ def load_visualign_json(filename):
"slices": slices,
}
else:
slices = vafile["slices"]
if len(slices) > 1:
......
"""This code was written by Gergely Csucs and Rembrandt Bakker"""
import numpy as np
......
import tkinter
import tkinter
from tkinter import *
from tkinter import ttk
......@@ -10,137 +10,182 @@ from tkinter import colorchooser
from PyNutil import PyNutil
#Basic GUI example
# Basic GUI example
root = Tk()
#root.geometry("300x300")
# root.geometry("300x300")
root.title("PyNutil")
root.wm_iconbitmap("Logo_PyNutil.ico")
#photo = tkinter.PhotoImage(file = 'Logo_PyNutil.ico')
#root.wm_iconphoto(False, photo)
# photo = tkinter.PhotoImage(file = 'Logo_PyNutil.ico')
# root.wm_iconphoto(False, photo)
arguments = {
"reference_atlas":None,
"registration_json":None,
"object_colour":None,
"segmentation_dir":None,
"output_dir": None
"reference_atlas": None,
"registration_json": None,
"object_colour": None,
"segmentation_dir": None,
"output_dir": None,
}
atlas = brainglobe_atlasapi.list_atlases.get_all_atlases_lastversions()
selected_atlas = StringVar(value="Reference Atlas")
directory = ["select","select1", "select2"]
directory = ["select", "select1", "select2"]
selected_directory = StringVar(value="directory")
colour = ["colour","black","red","blue","green"]
colour = ["colour", "black", "red", "blue", "green"]
selected_colour = StringVar(value=colour[0])
def donothing():
filewin = Toplevel(root)
label = Label(filewin, text="Do nothing")
label.pack()
filewin = Toplevel(root)
label = Label(filewin, text="Do nothing")
label.pack()
def about_pynutil():
filewin = Toplevel(root)
label = Label(filewin, text="PyNutil is an application for brain-wide mapping using a reference brain atlas")
label.pack()
filewin = Toplevel(root)
label = Label(
filewin,
text="PyNutil is an application for brain-wide mapping using a reference brain atlas",
)
label.pack()
def open_registration_json():
value = askopenfilename()
arguments["registration_json"] = value
print(arguments["registration_json"])
value = askopenfilename()
arguments["registration_json"] = value
print(arguments["registration_json"])
def choose_colour():
value = colorchooser.askcolor()
arguments["object_colour"] = value
print(list(value[0]))
value = colorchooser.askcolor()
arguments["object_colour"] = value
print(list(value[0]))
def open_segmentation_dir():
value = askdirectory()
arguments["segmentation_dir"] = value
print(arguments["segmentation_dir"])
value = askdirectory()
arguments["segmentation_dir"] = value
print(arguments["segmentation_dir"])
def select_output_dir():
value = askdirectory()
arguments["output_dir"] = value
print(arguments["output_dir"])
value = askdirectory()
arguments["output_dir"] = value
print(arguments["output_dir"])
def start_analysis():
pnt = PyNutil(
segmentation_folder= open_segmentation_dir, #'../tests/test_data/big_caudoputamen_test/',
alignment_json= open_registration_json, #'../tests/test_data/big_caudoputamen.json',
colour= choose_colour, #[0, 0, 0],
atlas_name='allen_mouse_25um'
)
pnt.get_coordinates(object_cutoff=0)
pnt.quantify_coordinates()
pnt.save_analysis("../tests/outputs/test9_PyNutil_bigcaudoputamen_new")
#Creating a menu
root.option_add('*tearOff', FALSE)
#win = Toplevel(root)
#menubar = Menu(win)
pnt = PyNutil(
segmentation_folder=open_segmentation_dir, #'../tests/test_data/big_caudoputamen_test/',
alignment_json=open_registration_json, #'../tests/test_data/big_caudoputamen.json',
colour=choose_colour, # [0, 0, 0],
atlas_name="allen_mouse_25um",
)
pnt.get_coordinates(object_cutoff=0)
pnt.quantify_coordinates()
pnt.save_analysis("../tests/outputs/test9_PyNutil_bigcaudoputamen_new")
# Creating a menu
root.option_add("*tearOff", FALSE)
# win = Toplevel(root)
# menubar = Menu(win)
menubar = Menu(root)
#win['menu'] = menubar
# win['menu'] = menubar
root.config(menu=menubar)
#menubar = Menu(root)
# menubar = Menu(root)
menu_file = Menu(menubar)
menu_help = Menu(menubar)
menubar.add_cascade(menu=menu_file, label='File')
menubar.add_cascade(menu=menu_help, label='Help')
menubar.add_cascade(menu=menu_file, label="File")
menubar.add_cascade(menu=menu_help, label="Help")
menu_file.add_command(label='New', command=donothing)
menu_file.add_command(label='Exit', command=root.quit)
menu_help.add_command(label='About PyNutil', command=about_pynutil)
menu_file.add_command(label="New", command=donothing)
menu_file.add_command(label="Exit", command=root.quit)
menu_help.add_command(label="About PyNutil", command=about_pynutil)
#Creating a content frame"
mainframe = ttk.Frame(root, padding="12 12 12 12") # left top right bottom
# Creating a content frame"
mainframe = ttk.Frame(root, padding="12 12 12 12") # left top right bottom
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1) # column to expand if there is extra space
root.rowconfigure(0, weight=1) # row to expand if there is extra space
root.columnconfigure(0, weight=1) # column to expand if there is extra space
root.rowconfigure(0, weight=1) # row to expand if there is extra space
#Creating a content frame"
bottomframe = ttk.Frame(root, padding="12 12 12 12") # left top right bottom
# Creating a content frame"
bottomframe = ttk.Frame(root, padding="12 12 12 12") # left top right bottom
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1) # column to expand if there is extra space
root.rowconfigure(0, weight=1) # row to expand if there is extra space
root.columnconfigure(0, weight=1) # column to expand if there is extra space
root.rowconfigure(0, weight=1) # row to expand if there is extra space
# Select reference atlas
ttk.Label(mainframe, text="Select reference atlas:", width=25).grid(column=1, row=1, sticky=W)
ttk.OptionMenu(mainframe, selected_atlas, "Reference Atlas", *atlas).grid(column=2, row=1, columnspan=2)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(column=4, row=1, sticky=W)
#Select registration JSON
ttk.Label(mainframe, text="Select registration JSON:", width=25).grid(column=1, row=2, sticky=W)
ttk.Button(mainframe, width=16, text="Browse...", command=open_registration_json).grid(column=2, row=2, sticky=W)
Text(mainframe, height = 1, width =40 ).grid(column=3, row=2, sticky= W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(column=4, row=2, sticky=W)
#Select segmentation folder
ttk.Label(mainframe, text="Select segmentation folder:", width=25).grid(column=1, row=3, sticky=W)
ttk.Button(mainframe, width=16, text="Browse...", command=open_segmentation_dir).grid(column=2, row=3, sticky=W)
Text(mainframe, height = 1, width =40).grid(column=3, row=3, sticky= W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(column=4, row=3, sticky=W)
#Select object colour
ttk.Label(mainframe, text="Select object colour:", width=25).grid(column=1, row=4, sticky=W)
ttk.Button(mainframe, width=16, text="Colour", command=choose_colour).grid(column=2, row=4, sticky=W)
Text(mainframe, height = 1, width =40).grid(column=3, row=4, sticky= W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(column=4, row=4, sticky=W)
#Select output directory
ttk.Label(mainframe, text="Select output directory:", width=25).grid(column=1, row=5, sticky=W)
ttk.Button(mainframe, width=16, text="Browse...", command=select_output_dir).grid(column=2, row=5, sticky=W)
Text(mainframe, height = 1, width =40).grid(column=3, row=5, sticky= W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(column=4, row=5, sticky=W)
#Start analysis
ttk.Label(mainframe, text="Select reference atlas:", width=25).grid(
column=1, row=1, sticky=W
)
ttk.OptionMenu(mainframe, selected_atlas, "Reference Atlas", *atlas).grid(
column=2, row=1, columnspan=2
)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(
column=4, row=1, sticky=W
)
# Select registration JSON
ttk.Label(mainframe, text="Select registration JSON:", width=25).grid(
column=1, row=2, sticky=W
)
ttk.Button(mainframe, width=16, text="Browse...", command=open_registration_json).grid(
column=2, row=2, sticky=W
)
Text(mainframe, height=1, width=40).grid(column=3, row=2, sticky=W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(
column=4, row=2, sticky=W
)
# Select segmentation folder
ttk.Label(mainframe, text="Select segmentation folder:", width=25).grid(
column=1, row=3, sticky=W
)
ttk.Button(mainframe, width=16, text="Browse...", command=open_segmentation_dir).grid(
column=2, row=3, sticky=W
)
Text(mainframe, height=1, width=40).grid(column=3, row=3, sticky=W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(
column=4, row=3, sticky=W
)
# Select object colour
ttk.Label(mainframe, text="Select object colour:", width=25).grid(
column=1, row=4, sticky=W
)
ttk.Button(mainframe, width=16, text="Colour", command=choose_colour).grid(
column=2, row=4, sticky=W
)
Text(mainframe, height=1, width=40).grid(column=3, row=4, sticky=W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(
column=4, row=4, sticky=W
)
# Select output directory
ttk.Label(mainframe, text="Select output directory:", width=25).grid(
column=1, row=5, sticky=W
)
ttk.Button(mainframe, width=16, text="Browse...", command=select_output_dir).grid(
column=2, row=5, sticky=W
)
Text(mainframe, height=1, width=40).grid(column=3, row=5, sticky=W)
ttk.Button(mainframe, text="Help", width=8, command="buttonpressed").grid(
column=4, row=5, sticky=W
)
# Start analysis
ttk.Label(mainframe, text="Start analysis:", width=25).grid(column=1, row=6, sticky=W)
ttk.Button(mainframe, width = 52, text="Run", command="buttonpressed").grid(column= 3, row=6)
ttk.Button(mainframe, text="Docs", width=8, command="buttonpressed").grid(column=4, row=6, sticky=W)
ttk.Button(mainframe, width=52, text="Run", command="buttonpressed").grid(
column=3, row=6
)
ttk.Button(mainframe, text="Docs", width=8, command="buttonpressed").grid(
column=4, row=6, sticky=W
)
# sunken frame around mainframe
"""
......@@ -148,6 +193,6 @@ mainframe['borderwidth'] = 2
mainframe['relief'] = 'sunken'
"""
#button.configure()
# button.configure()
root.mainloop()
......@@ -2,7 +2,10 @@ import os
import sys
import numpy as np
import tifffile as tiff
path_to_file = r"/home/harryc/Downloads/mouse-s23/ext-d000009_PVMouse_81265_Samp1__s023.tif"
path_to_file = (
r"/home/harryc/Downloads/mouse-s23/ext-d000009_PVMouse_81265_Samp1__s023.tif"
)
image_outdir = path_to_file.split(".")[0].split("/")[-1]
if not os.path.exists(image_outdir):
os.makedirs(image_outdir)
......@@ -10,12 +13,12 @@ if not os.path.exists(image_outdir):
img = tiff.imread(path_to_file)
# Get the shape of the image
shape = img.shape
#Get the chunk size
# Get the chunk size
chunk_size = 512
#invert the image if neccessary
# invert the image if neccessary
img = np.invert(img)
#crop the image and save each chunk
# crop the image and save each chunk
for i in range(0, shape[0], chunk_size):
for j in range(0, shape[1], chunk_size):
chunk = img[i:i+chunk_size, j:j+chunk_size]
tiff.imsave("{}/chunk_{}_{}.tif".format(image_outdir,i, j), chunk)
chunk = img[i : i + chunk_size, j : j + chunk_size]
tiff.imsave("{}/chunk_{}_{}.tif".format(image_outdir, i, j), chunk)
......@@ -150,4 +150,4 @@ reformat_WHS_label(
"../annotation_volumes/WHS_Atlas_Rat_Brain_v2.label",
"../annotation_volumes/WHS_v2_colours.csv",
)
reformat_WHS_label("Kim_Unified_Mouse.label","Kim_Unified_Mouse_colours.csv")
\ No newline at end of file
reformat_WHS_label("Kim_Unified_Mouse.label", "Kim_Unified_Mouse_colours.csv")
......@@ -2,45 +2,45 @@ import json
import re
import os
'''
"""
Sharon Yates, 04.04.24.
This is a script for converting WALN and WWRP files from WebAlign and WebWarp to VisuAlign compatible JSON files.
To be used for testing purposes.
'''
"""
def waln_to_json(filename):
with open(filename) as f:
vafile = json.load(f)
if filename.endswith(".waln") or filename.endswith("wwrp"):
slices = vafile["sections"] # define slices as "section" in waln
vafile["slices"] = slices
slices = vafile["sections"] # define slices as "section" in waln
vafile["slices"] = slices
for slice in slices:
if "filename" in slice:
base_name = os.path.basename(slice["filename"]).split('.')[0]
new_filename = base_name + '.png'
base_name = os.path.basename(slice["filename"]).split(".")[0]
new_filename = base_name + ".png"
slice["filename"] = new_filename
slice["nr"] = int(re.search(r"_s(\d+)", slice["filename"]).group(1))
if "ouv" in slice:
slice["anchoring"] = slice["ouv"]
slice["anchoring"] = slice["ouv"]
name = os.path.basename(filename)
va_compat_file = {
"name": name.replace(".waln",".json"),
"target": vafile["atlas"] + '.cutlas',
"name": name.replace(".waln", ".json"),
"target": vafile["atlas"] + ".cutlas",
"target-resolution": [456, 528, 320],
"slices": slices
"slices": slices,
}
# save with .json extension need to see if i can remove this
with open(
filename.replace(".waln", ".json").replace(".wwrp", ".json"), "w"
) as f:
#json.dump(va_compat_file, f, indent=4)
# json.dump(va_compat_file, f, indent=4)
json.dump(va_compat_file, f, indent=4)
else:
pass
waln_to_json("PyNutil_test.waln")
waln_to_json("PyNutil_test.waln")
from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setup(
name="PyNutil",
version='0.1.1',
version="0.1.1",
packages=find_packages(),
license='MIT',
description='a package to translate data between common coordinate templates',
license="MIT",
description="a package to translate data between common coordinate templates",
long_description=long_description,
long_description_content_type='text/markdown',
long_description_content_type="text/markdown",
install_requires=[
'numpy',
'brainglobe-atlasapi',
'pandas',
'requests',
'pynrrd',
'xmltodict',
'opencv-python',
'scikit-image'
]
"numpy",
"brainglobe-atlasapi",
"pandas",
"requests",
"pynrrd",
"xmltodict",
"opencv-python",
"scikit-image",
],
)
to run the tests run
```bash
python -m unittest discover -s tests -v
```
from the root of the repository
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment