Need to load 4D images into python array for cellpose analysis and Npari Display

23 views Asked by At

I'm out of my depth. I'm trying to load tiff stacks of X = 512, Y = 512 Z = 50 (each slice in the tiff stack) and time is each tiff stack in the file directory. When I try some example code or code from Chat GPT (which is gleaned from the few examples online) I get a tiff array that states its shape to be x = 50, y = 512 and z = 512. The call to cellpose fails because I'm asking it to output to four arrays. Here's the source I tried modifying/correcting from chat GTP and running. (yes I know chat GPT is abysmal. I'm comparing it to code examples and trying common sense corrections to no avail. Python isn't the language I know. I was really good with Visual Basic back in the day. If you don't know cellpose and/or napari then just any help with loading the array correctly would be a real boon. Thank you.


import os
import napari
import tifffile as tf
from cellpose import models
from cellpose.models import CellposeModel

# Set the directory path
directory_path = r"C:\Optic Tectum\processed\Optic Tectucm"
models_directory = r"C:\Optic Tectum\processed\models"

# Get a list of all TIFF files in the directory
tiff_files = [f for f in os.listdir(directory_path) if f.endswith('.tif')]

# Load custom Napari model
model_filename = "OT3_20230716_231844"
custom_model_path = os.path.join(models_directory, f"{model_filename}")
custom_model = models.CellposeModel(gpu=False, pretrained_model=custom_model_path)

print(custom_model_path)

# Load and process each TIFF Z stack
for tiff_file in tiff_files:
    # Construct the full file path
    file_path = os.path.join(directory_path, tiff_file)
    
    # Load the TIFF Z stack
    tiff_stack = tf.imread(file_path)
    
    # Check the shape of the stack (X, Y, Z)
    x_size, y_size, z_size = tiff_stack.shape
    print(f"Processing {tiff_file}: X={x_size}, Y={y_size}, Z={z_size}")
    
    # Use napari to visualize the Z stack
    viewer = napari.Viewer()
    viewer.add_image(tiff_stack, name='Z Stack')
    
    # Use custom Napari model for segmentation
    masks, flows, styles, diams = custom_model.eval(tiff_stack, diameter=18, channels=[0, 0])
    
    # Add segmentation results to the napari viewer
    viewer.add_image(masks, name='Segmentation Masks', colormap='red', blending='additive')
    
    # Keep the napari viewer open until you close it
    napari.run()

# Note: Adjust the parameters in the custom Cellpose model initialization according to your needs.

I was expecting 4D napari output with the original image layer, label/masks layer, flows layer and maybe an outlines layer.

0

There are 0 answers