<jupyter_start><jupyter_text>CropArray example ---  Notebook summary - Load a microscope image o video- Tracking spots on the image and generate a pandas dataframe with the spots locations- Creating a croparray with the image and dataframe- Visualization with Napari----  Importing libraries----<jupyter_code># To manipulate arrays
import numpy as np 
from skimage.io import imread
import matplotlib.pyplot as plt 
import seaborn as sns; sns.set()  
import pathlib # for working with windows paths
import sys
import cv2
current_dir = pathlib.Path().absolute()
croparray_dir = current_dir.parents[0].joinpath('croparray')
sys.path.append(str(croparray_dir))
import crop_array_tools as ca
# %matplotlib inline 
#plt.style.use('dark_background')
plt.rcParams.update({
    "lines.color": "white",
    "patch.edgecolor": "white",
    "text.color": "black",
    "axes.facecolor": "white",
    "axes.edgecolor": "lightgray",
    "axes.labelcolor": "white",
    "xtick.color": "white",
    "ytick.color": "white",
    "grid.color": "None",
    "figure.facecolor": "black",
    "figure.edgecolor": "black",
    "savefig.facecolor": "black",
    "savefig.edgecolor": "black"})<jupyter_output><empty_output><jupyter_text>Parameters for quantification----<jupyter_code># parameters
particle_diameter= 25  # Spot diameter : y,x size of the spot      
tracking_channel = 0          # Channel  used for tracking
min_trajectory_length = 20    # Minimal number of frames to be consider as a trajectory
max_distance_movement = 30 #particle_diameter*2
# Visualization. Static image taking a given time point. Plotting the maximum projection in Z for a given channel.
selected_channel = 0<jupyter_output><empty_output><jupyter_text>Loading data----<jupyter_code># Video directory
img_file_path = current_dir.parents[0].joinpath('database','shadow_scope','834630658_shadow_scope1-cleantwirler-2.mp4')  
# Reading a MP4 file
frames = []
cap = cv2.VideoCapture(str(img_file_path))
ret = True
while ret:
    ret, img = cap.read() # read one frame from the 'capture' object; img is (H, W, C)
    if ret:
        frames.append(img)
img = np.stack(frames, axis=0) # dimensions (T, H, W, C)  

print("original image shape = ", img.shape)
print("Image range:  (", np.min(img), ',' , np.max(img) ,')' )
# Converting the video to Croparray format
img_croparray = np.expand_dims(img,axis=0) # expanding to include fov
img_croparray = np.expand_dims(img_croparray,axis=2) # expanding to  z
img_croparray.shape # dimensions MUST be (fov, f , z, y, x, ch)
img_croparray.shape
print("croparray format shape [fov, f , z, y, x, ch] = ", img_croparray.shape)
# plotting original image
# Just examining one of the images
selected_time = 100
num_channels = 3
fig, ax = plt.subplots(nrows=1, ncols=num_channels,figsize=(20,10))
for i in range(0,num_channels):
    ax[i].imshow(np.max(img_croparray[0,selected_time,:,:,:,i] ,axis=0),cmap='Greys_r' )
    ax[i].grid(False)
    ax[i].set_title('Channel_'+str(i))<jupyter_output><empty_output><jupyter_text>Spot detection and tracking----<jupyter_code>img_2D = np.amax(img_croparray[0,:,:,:,:,tracking_channel],axis=1)   #(fov, f , z, y, x, ch)
img_2D.shape # ( f, y, x)
from scipy.ndimage import gaussian_filter
list_filtered_img = [gaussian_filter(img_2D[i,...], sigma=5) for i in range(0,img_2D.shape[0])]
img_2D_filtered = np.asarray(list_filtered_img)
# plotting original image
# Just examining one of the images
selected_time = 100
num_channels = 3
fig, ax = plt.subplots(nrows=1, ncols=num_channels,figsize=(20,10))
for i in range(0,num_channels):
    ax[i].imshow(img_2D_filtered[selected_time,...],cmap='Greys_r' )
    ax[i].grid(False)
    ax[i].set_title('Channel_'+str(i))
spots_df = ca.tracking_spots(img_2D_filtered,particle_diameter=particle_diameter,max_distance_movement=max_distance_movement,
                            min_trajectory_length=min_trajectory_length, num_iterations = 100,show_plots=True)
my_ca = ca.create_crop_array(img_croparray,spots_df,xy_pad=particle_diameter//2)
my_ca.coords
# Plot one of the crops over time to test
best_z = ca.best_z_proj(my_ca, ref_ch=0, disk_r=3, roll_n=3)
#best_z.where(my_ca.id==5).mean('n').sel(fov=0).plot.imshow(col='t',rgb='ch',col_wrap=10,robust=True,xticks=[],yticks=[],size=1.5)
# Create best-z projection using channel 1 (translation) as a reference. taking bestz +/- 1 here (roll_n = 3)
best_z = ca.best_z_proj(my_ca, ref_ch=1, disk_r=3, roll_n=3)
best_z = my_ca.int.sel(fov=0).max('z')
best_z.coords
# view the action of montage
my_ca_montage= ca.montage(best_z, row = 't', col = 'n')
print(my_ca_montage.dims)
print(my_ca_montage.coords)
montage_val  = my_ca_montage.sel(ch=0).values
plt.figure(figsize=(10,20))
plt.imshow(montage_val)
plt.xlabel('n', size=10)
plt.ylabel('t', size=10)
plt.xticks([])
plt.yticks([])
plt.show()
raise
# Napari 
%gui qt5 
import napari
from napari.utils import nbscreenshot
viewer = napari.Viewer()
# view the action of montage [rows= time, columns = spot number]
viewer.add_image(my_ca_montage.sel(ch=1), colormap = 'green', name = 'green', blending = 'additive', contrast_limits=[0,my_ca_montage.sel(ch=1).data.max()])
viewer.add_image(my_ca_montage.sel(ch=0), colormap = 'red', name = 'red', blending='additive', contrast_limits=[0,my_ca_montage.sel(ch=0).data.max()])
viewer.add_image(my_ca_montage.sel(ch=2), colormap = 'blue', name = 'blue', blending='additive', contrast_limits=[0,my_ca_montage.sel(ch=2).data.max()])
nbscreenshot(viewer)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1440291704649043, 'fraction_numerical': 0.018596171376481313, 'mean_word_length': 5.625603864734299, 'pattern_counts': {'":': 13, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '611646', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2127, 'n_tokens_neox': 2035, 'n_words': 440, 'path': 'notebooks/ToolDevelopment_shadowscope.ipynb', 'repo_name': 'Colorado-State-University-Stasevich-Lab/croparray', 'size': '5485'}