def test_scene_screenshot(name, scale): s = Scene(screenshots_folder="tests/screenshots") s.screenshot(name=name, scale=scale) shutil.rmtree("tests/screenshots") s.render(interactive=False) del s
cun, grn, mos = scene.add_brain_region("CUN", "GRN", "MOs", alpha=0.7) # CUN/GRN probe tip[1] = tip[1] + scene.root.centerOfMass()[2] top[1] = top[1] + scene.root.centerOfMass()[2] top = top[[0, 2, 1]] tip = tip[[0, 2, 1]] scene.add(shapes.Cylinder(pos=[top, tip], c="k", r=50, alpha=1)) # MOs probe mos_center = mos.centerOfMass() + np.array([1000, 0, -800]) for x in [-500, -1000, -1500, -2000]: scene.add( Cylinder(mos_center + np.array([x, 0, 0]), scene.root, color="k", radius=50)) camera = { "pos": (-6374, -5444, 26602), "viewup": (0, -1, 0), "clippingRange": (19433, 56931), "focalPoint": (7830, 4296, -5694), "distance": 36602, } scene.render(interactive=False, camera=camera) scene.screenshot(name="probes")
scene.add_brain_region("TH", alpha=0.2, silhouette=True, color=salmon) scene.add_brain_region("VISp", alpha=0.4, silhouette=False, color=[50, 2, 155]) scene.slice("sagittal") # Set up a camera. Can use string, such as "sagittal". # During render runtime, press "c" to print the current camera parameters. camera = { "pos": (8777, 1878, -44032), "viewup": (0, -1, 0), "clippingRange": (24852, 54844), "focalPoint": (7718, 4290, -3507), "distance": 40610, } zoom = 1.5 # If you only want a screenshot and don't want to move the camera # around the scene, set interactive to False. scene.render(interactive=False, camera=camera, zoom=zoom) # Set the scale, which will be used for screenshot resolution. # Any value > 1 increases resolution, the default is in brainrender.settings. # It is easiest integer scales (non-integer can cause crashes). scale = 2 # Take a screenshot - passing no name uses current time # Screenshots can be also created during runtime by pressing "s" scene.screenshot(name="example_brainrender_shot", scale=scale) scene.close()
def test_scene_screenshot(name, scale): s = Scene(screenshots_folder="tests/screenshots") s.screenshot(name=name, scale=scale) shutil.rmtree("tests/screenshots") del s
class App(Scene, UI, CameraControl, AddFromFile, RegionsControl, ActorsControl): actors = {} # stores actors and status camera_orientation = None # used to manually set camera orientation def __init__(self, *args, atlas_name=None, axes=None, **kwargs): """ Initialise the qtpy app and the brainrender scene. Arguments: ---------- atlas_name: str/None. Name of the brainglobe atlas to use axes: bool. If true axes are shown in the brainrender render """ # Initialize parent classes self.scene = Scene(*args, atlas_name=atlas_name, **kwargs) UI.__init__(self, *args, **kwargs) CameraControl.__init__(self) AddFromFile.__init__(self) RegionsControl.__init__(self) ActorsControl.__init__(self) # Setup brainrender plotter self.axes = axes self.atuple = namedtuple("actor", "mesh, is_visible, color, alpha") self.setup_plotter() self._update() self.scene._get_inset() # Setup widgets functionality self.actors_list.itemDoubleClicked.connect( self.actor_list_double_clicked) self.actors_list.clicked.connect(self.actor_list_clicked) buttons_funcs = dict( add_brain_regions=self.open_regions_dialog, add_from_file=self.add_from_file_object, add_cells=self.add_from_file_cells, show_structures_tree=self.toggle_treeview, take_screenshot=self.take_screenshot, reset=self.reset_camera, top=self.move_camera_top, side1=self.move_camera_side1, side2=self.move_camera_side2, front=self.move_camera_front, ) for btn, fun in buttons_funcs.items(): self.buttons[btn].clicked.connect(fun) self.treeView.clicked.connect(self.add_region_from_tree) self.alpha_textbox.textChanged.connect(self.update_actor_properties) self.color_textbox.textChanged.connect(self.update_actor_properties) def take_screenshot(self): self._update() self.scene.plotter.render() # Get savename self.scene.screenshots_folder.mkdir(exist_ok=True) savename = str(self.scene.screenshots_folder / "brainrender_gui") savename += (f'_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}' + ".png") print(f"\nSaving screenshot at {savename}\n") self.scene.screenshot(name=savename) # show success message dialog = ScreenshotModal(self, self.palette) dialog.exec() # ------------------------------ Toggle treeview ----------------------------- # def toggle_treeview(self): """ Method for the show structures tree button. It toggles the visibility of treeView widget and adjusts the button's text accordingly. """ if not self.treeView.isHidden(): self.buttons["show_structures_tree"].setText( "Show structures tree") else: self.buttons["show_structures_tree"].setText( "Hide structures tree") self.treeView.setHidden(not self.treeView.isHidden()) # ------------------------------- Initial setup ------------------------------ # def setup_plotter(self): """ Changes the scene's default plotter with one attached to the qtWidget in the pyqt application. """ # Get embedded plotter new_plotter = Plotter(qtWidget=self.vtkWidget) self.scene.plotter = new_plotter # Get axes if self.axes: self.axes = self._make_axes() # self.scene.add_actor(ax) else: self.axes = None # Fix camera set_camera(self.scene, self.scene.plotter.camera) # ---------------------------------- Update ---------------------------------- # def _update_actors(self): """ All actors that are part of the scene are stored in a dictionary with key as the actor name and value as a 4-tuple with (Mesh, is_visible, color, alpha). `is_visible` is a bool that determines if the actor should be rendered """ for actor in self.scene.actors: if actor is None: continue try: if actor.name not in self.actors.keys(): self.actors[actor.name] = self.atuple( actor, True, actor.mesh.color(), actor.mesh.alpha()) except AttributeError: # the Assembly object representing the axes should be ignore pass def _update(self): """ Updates the scene's Plotter to add/remove meshes """ if self.camera_orientation is not None: # set_camera(self.scene, self.camera_orientation) camera = self.camera_orientation self.camera_orientation = None else: camera = get_camera_params(scene=self.scene) self.scene.render(camera=camera) # Get actors to render self._update_actors() to_render = [act for act in self.actors.values() if act.is_visible] # Set actors look meshes = [act.mesh.c(act.color).alpha(act.alpha) for act in to_render] # Add axes if self.axes is not None: meshes.append(self.axes) # update actors rendered self.scene.plotter.show( *meshes, interactorStyle=0, bg=brainrender.settings.BACKGROUND_COLOR, ) # Fake a button press to force canvas update self.scene.plotter.interactor.MiddleButtonPressEvent() self.scene.plotter.interactor.MiddleButtonReleaseEvent() # Update list widget update_actors_list(self.actors_list, self.actors) return meshes # ----------------------------------- Close ---------------------------------- # def onClose(self): """ Disable the interactor before closing to prevent it from trying to act on a already deleted items """ self.vtkWidget.close()
# add meshes from file files = [ "paper/data/CC_134_2_ch1inj.obj", "paper/data/CC_134_1_ch1inj.obj", ] colors = [ inj1col, inj2col, ] injections = [scene.add(f, color=c) for f, c in zip(files, colors)] scene.add_silhouette(*injections, lw=2) # add brain regions scm = scene.add_brain_region("SCm", alpha=0.4, silhouette=False, color=blue_grey_darker) pag = scene.add_brain_region("PAG", alpha=0.3, silhouette=False, color=blue_grey) # make brain region as wireframe scm.wireframe() pag.wireframe() # render scene.render(camera=cam, zoom=3.5) scene.screenshot(name="injection")
screenshots_folder="paper/screenshots", atlas_name="mpin_zfish_1um", ) scene.root.alpha(0.2) # get neurons data api = MpinMorphologyAPI() neurons_ids = api.get_neurons_by_structure(837) neurons = api.load_neurons(neurons_ids) # create neurons meshes neurons = [ neuron.create_mesh(soma_radius=0.75, neurite_radius=1) for neuron in neurons ][:N] # color neurons parts and add to scene for (neu_dict, neu) in track(neurons, total=N): col = choice((c1, c2)) neuron = scene.add(neu_dict["axon"], alpha=1, color=col) soma = scene.add( Point(neu_dict["soma"].centerOfMass(), color=col, radius=8, alpha=1) ) scene.add_silhouette(soma) # render scene.render(zoom=1.7, camera=cam) scene.screenshot(name="zfish_neurons") scene.close()
cam = { "pos": (-4767, -3533, -31261), "viewup": (0, -1, 0), "clippingRange": (22849, 40012), "focalPoint": (11035, 4324, -6224), "distance": 30632, } # Create a brainrender scene scene = Scene(title="projections from " + region, root=False) # Add brain regions scene.add_brain_region(*regions, alpha=0.6, silhouette=True) scene.add_brain_region("PAG", alpha=0.2, silhouette=False) # Get stramlines data and add streams = get_streamlines_for_region(region) zoom = 2 for n, stream in enumerate(streams): act = scene.add(*make_streamlines(stream, color="salmon", alpha=0.6)) # Render! scene.render(interactive=False, zoom=zoom, camera=cam) scene.screenshot(dest_fld + f"/{region}_streams_{n}") scene.remove(act) zoom = 1 # break
"viewup": (1, -1, -1), "clippingRange": (1773, 4018), "focalPoint": (478, 210, -296), "distance": 2759, } # load cluster data and get cell coordinates cluster_data = h5py.File("paper/data/zfish_rois_clusters.h5", "r") cluster_ids = cluster_data["cluster_ids"][:] roi_coords = cluster_data["coords"][:] # create scene scene = Scene( inset=INSET, screenshots_folder="paper/screenshots", atlas_name="mpin_zfish_1um", ) # add cells colored by cluster colors = [c1, c2, c3] for i, col in enumerate(colors): rois_in_cluster = roi_coords[cluster_ids == i, :] coords = pd.DataFrame(rois_in_cluster, columns=["x", "y", "z"]).values pts = scene.add(Points(coords, colors=col, radius=2, alpha=1)) scene.add_silhouette(pts, lw=1) # render scene.render(camera=cam, zoom=2.5) scene.screenshot(name="zfish_functional_clusters")
# create scene scene = Scene( atlas_name="mpin_zfish_1um", inset=INSET, screenshots_folder="paper/screenshots", ) scene.root.alpha(0.2) # add custom meshes from file, but don't show them (alpha=0) m = scene.add("paper/data/T_AVG_nk1688CGt_GFP.obj", color=gene1_color, alpha=0) m2 = scene.add("paper/data/T_AVG_brn3c_GFP.obj", color=gene2_color, alpha=0) # adjust meshes position for mesh in (m, m2): mesh.mesh.addPos(dp_x=SHIFT) # convert meshes to volumetric data showing gene expression density vol1 = Volume(m.density(), as_surface=True, min_value=20000, cmap="Reds") vol1.lw(1) scene.add(vol1) vol2 = Volume(m2.density(), as_surface=True, min_value=600, cmap="Blues") vol2.lw(1) scene.add(vol2) # render scene.render(camera=cam, zoom=2.5) scene.screenshot(name="zfish_gene_expression")
print("[bold red]Running: ", Path(__file__).name) # camera settings cam = { "pos": (-1122, -389, 1169), "viewup": (0, -1, 0), "clippingRange": (1168, 3686), "focalPoint": (469, 221, -346), "distance": 2280, } # create scene scene = Scene( inset=INSET, screenshots_folder="paper/screenshots", atlas_name="mpin_zfish_1um", ) scene.root._needs_silhouette = SILHOUETTE scene.root._silhouette_kwargs["lw"] = 3 scene.root.alpha(0.2) # add brain regions cb, t = scene.add_brain_region("cerebellum", "tectum", silhouette=SILHOUETTE) cb.c(cbcol) t.c(tcol) # render scene.render(zoom=1.9, camera=cam) scene.screenshot(name="zfish_regions") scene.close()
} # create scene scene = Scene(inset=INSET, screenshots_folder="paper/screenshots") # add silhouette to root and change alpha scene.root._needs_silhouette = True scene.root._silhouette_kwargs["lw"] = 2 scene.root.alpha(0.1) # download gene expression data gene = "Gpr161" geapi = GeneExpressionAPI() expids = geapi.get_gene_experiments(gene) data = geapi.get_gene_data(gene, expids[1]) # createa a Volume actor and add to scene gene_actor = geapi.griddata_to_volume(data, min_quantile=99, cmap="Reds") gene_actor.c(salmon_dark) act = scene.add(gene_actor) # add CA1 as wireframe ca1 = scene.add_brain_region( "CA1", alpha=0.2, color=blue_grey_dark, silhouette=False ) ca1.wireframe() # render scene.render(camera=cam, zoom=3.5) scene.screenshot(name="gene_expression")
screenshots_folder="paper/screenshots", atlas_name="allen_human_500um", ) scene.root._needs_silhouette = True # get the subregions of TemL from atlas hierarchy for main in ("TemL", ): subs = scene.atlas.get_structure_descendants(main) for sub in subs: reg = scene.add_brain_region(sub, silhouette=True, color=br1) # add more brain regions for reg, col in zip( ( "PrCG", "PoCG", ), (br2, br3), ): reg = scene.add_brain_region(reg, silhouette=True, color=col) # render scene scene.render(camera=cam, zoom=1.65) scene.screenshot(name="human_regions") scene.close() # Mirror image im = Image.open("figures/human_regions.png") im_mirror = ImageOps.mirror(im) im_mirror.save("figures/human_regions.png")
scene.root._needs_silhouette = False scene.root.alpha(0.5) # add brain regions pag = scene.add_brain_region("PAG", alpha=0.4, silhouette=False, color=pagcol) scm = scene.add_brain_region("SCm", alpha=0.3, silhouette=False, color=scmcol) # add neuron mesh neuron = scene.add("paper/data/yulins_neuron.stl") neuron.c(neuroncol) # add sphere at soma location soma_pos = [9350.51912036, 2344.33986638, 5311.18297796] point = scene.add(Point(soma_pos, color=neuroncol, radius=25)) scene.add_silhouette(point, lw=1, color="k") scene.add_silhouette(neuron, lw=1, color="k") # slice scene repeatedly to cut out region of interest p = [9700, 1, 800] plane = scene.atlas.get_plane(pos=p, plane="frontal") scene.slice(plane, actors=[scm, pag, scene.root]) p = [11010, 5000, 5705] plane = scene.atlas.get_plane(pos=p, norm=[0, -1, 0]) scene.slice(plane, actors=[scene.root]) # render scene.render(zoom=9, camera=cam) scene.screenshot(name="single_neuron") scene.close()
print("[bold red]Running: ", Path(__file__).name) # define camera parmeters cam = { "pos": (5792, 431, 36893), "viewup": (0, -1, 0), "clippingRange": (39051, 53300), "focalPoint": (5865, 4291, -8254), "distance": 45311, } # make scene scene = Scene(inset=INSET, screenshots_folder="paper/screenshots") scene.add_brain_region("TH", alpha=0.2, silhouette=False, color=thcol) # load cell coordinates and add as a Points actor coords = np.load("paper/data/cell-detect-paper-cells.npy") cells = scene.add(Points(coords, radius=30, colors=salmon)) # add a silhouette around the cells scene.add_silhouette(cells, lw=1) # slice scene with a sagittal plane scene.slice("sagittal") # render and save screenshotq scene.render(interactive=True, camera="sagittal", zoom=2.6) scene.screenshot(name="cellfinder_cells") scene.close()
from rich import print from pathlib import Path from brainrender import Scene sys.path.append("./") from paper.figures import INSET, SILHOUETTE print("[bold red]Running: ", Path(__file__).name) # camera settings cam = { "pos": (-20268, -6818, 14964), "viewup": (0, -1, 0), "clippingRange": (16954, 58963), "focalPoint": (6489, 4329, -5556), "distance": 35514, } # create scene scene = Scene(inset=INSET, screenshots_folder="paper/screenshots") scene.root._needs_silhouette = SILHOUETTE # add brain regions for reg, col in zip(("SCm", "SCs", "ZI"), (scmcol, scscol, zicol)): scene.add_brain_region(reg, color=col, silhouette=SILHOUETTE) # render scene.render(zoom=1.75, camera=cam) scene.screenshot(name="mouse_regions", scale=1)
"clippingRange": (34734, 54273), "focalPoint": (7150, 3510, -5283), "distance": 42972, } # create scene scene = Scene(inset=INSET, screenshots_folder="paper/screenshots") scene.root._needs_silhouette = True scene.root._silhouette_kwargs["lw"] = 1 scene.root.alpha(0.5) # get streamlines data streams = get_streamlines_for_region("MOp") # add Streamlines actors s = scene.add(Streamlines(streams[0], color=streamlinescol, alpha=1)) # add brain regions th = scene.add_brain_region("TH", alpha=0.45, silhouette=False, color=blue_grey) # slice scene scene.slice("horizontal", actors=[scene.root]) # render scene.render(camera=cam, zoom=2) scene.screenshot(name="streamlines") scene.close()