Skip to content

Instantly share code, notes, and snippets.

@psobolewskiPhD
Last active August 23, 2021 12:23
Show Gist options
  • Save psobolewskiPhD/53eec7440eda501d9edf08a99659f6b0 to your computer and use it in GitHub Desktop.
Save psobolewskiPhD/53eec7440eda501d9edf08a99659f6b0 to your computer and use it in GitHub Desktop.
#%%
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas
from skimage import measure
from skimage import io
import numpy as np
import os
import napari
#%%
# # create image
# x = np.linspace(0, 5, 256)
# y = np.linspace(0, 5, 256)[:, np.newaxis]
# img = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
#%%
# add it to the viewer
imgName = os.path.expanduser("~/Dev/images/Bars-G10-P15-stack.tif")
img = io.imread(imgName)
viewer = napari.view_image(img, name="Image", colormap="viridis")
line = np.array([[11, 13], [111, 113]])
line_prof_layer = viewer.add_shapes(
line, shape_type="line", edge_color="red", name="Line Profile"
)
line_prof_layer.mode = "select"
#%%
def line_profile(image, line_prof_layer):
slice = viewer.layers["Image"]._data_raw
if line_prof_layer.data:
if line_prof_layer.shape_type[-1] == "line":
linescan = measure.profile_line(
slice,
line_prof_layer.data[-1][0],
line_prof_layer.data[-1][1],
mode="reflect",
)
else:
print("no line")
else:
print("No data")
return linescan
#%%
# create mpl figure with subplots
plt.rcParams.update({"font.size": 11})
mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(1, 1, 1)
linescan = line_profile(img, line_prof_layer)
(line,) = ax.plot(linescan)
line.figure.canvas.draw()
#%%
# add the figure to the viewer as a FigureCanvas widget
viewer.window.add_dock_widget(FigureCanvas(mpl_fig), area="bottom")
# connect a callback that updates the line plot when
@line_prof_layer.mouse_drag_callbacks.append
def profile_lines_drag(shapes_layer, event):
linescan = line_profile(img, shapes_layer)
ax.clear()
(line,) = ax.plot(linescan)
line.figure.canvas.draw()
yield
while event.type == "mouse_move":
linescan = line_profile(img, shapes_layer)
ax.clear()
(line,) = ax.plot(linescan)
line.figure.canvas.draw()
# the yield statement allows the mouse UI to keep working while
# this loop is executed repeatedly
yield
#%%
# try to connect to slider
@viewer.dims.events.current_step.connect
def profile_lines_slice(event):
linescan = line_profile(img, line_prof_layer)
ax.clear()
(line,) = ax.plot(linescan)
line.figure.canvas.draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment