OSCR

Large vision model framework for automated C. elegans analysis: From static morphometry to dynamic neural activity.

Code ↔ Paper

13 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 13 matches
  1. [1] § Materials and methods › Droplet swimming recording and analysis › Automated quantitative analysis of swimming behavior. ↔ droplet_swimming/4_shape_analysis.py, lines 525–619 · score 0.91 · power spectral density, Temporal frequencies, dominant frequencies, worm length, Welch, PSD
  2. [2] § Materials and methods › Droplet swimming recording and analysis › Automated quantitative analysis of swimming behavior. ↔ singleworm_tracking/3_shape_analysis.py, lines 804–943 · score 0.89 · power spectral density, dominant frequencies, worm length, Welch, PSD, Wave
  3. [3] § Materials and methods › Static images acquisition and analysis › Automated multi-worm morphological feature extraction from images. ↔ multiworm_feature_extraction/0_cutout_classifier.py, lines 18–49 · score 0.80 · random resized crops, horizontal flips, augmentation, PyTorch, validation, cutouts
  4. [4] § Materials and methods › Static images acquisition and analysis › Automated multi-worm morphological feature extraction from images. ↔ multiworm_feature_extraction/2_extract_wormcutouts.py, lines 35–45 · score 0.79 · pred_iou_thresh, stability_score_thresh, automatic mask, mask generation, CUDA, predictions
  5. [5] § Materials and methods › Calcium imaging in semi-restricted worms › Automated segmentation of axonal compartments and head bending extraction. ↔ singleworm_tracking/2_autoprompted_segmentation.py, lines 1–32 · score 0.75 · Hiera Large, prompt pool, video predictor, Full frame, prompt frames, checkpoint
  6. [6] § Materials and methods › Crawling recording and analysis › Automated single worm high-definition tracking. ↔ singleworm_tracking/4_path_analysis.py, lines 418–498 · score 0.73 · velocity vectors, Worm movement, movement classification, bouts, orientation, stationary
  7. [7] § Materials and methods › Droplet swimming recording and analysis › Automated quantitative analysis of swimming behavior. ↔ singleworm_tracking/2_autoprompted_segmentation.py, lines 1–32 · score 0.71 · sam2_hiera_large.pt, generic prompt frame, high definition, checkpoint, CUDA, cropped
  8. [8] § Materials and methods › Static images acquisition and analysis › Runtime benchmarking. ↔ multiworm_feature_extraction/2_extract_wormcutouts.py, lines 321–389 · score 0.70 · medial axis, connected component, pruned, perimeter, contour, width
  9. [9] § Materials and methods › Crawling recording and analysis › Automated single worm high-definition tracking. ↔ singleworm_tracking/3_shape_analysis.py, lines 529–659 · score 0.69 · recent history, Error correction, cumulative, sudden, Endpoint, tail
  10. [10] § Materials and methods › Calcium imaging in semi-restricted worms › Automated segmentation of axonal compartments and head bending extraction. ↔ RIA_calcium_imaging/2_crop_RIAregion.py, lines 1–24 · score 0.68 · RIA region, Hiera Large, video predictor, checkpoint, crop, SAM2
  11. [11] § Materials and methods › Static images acquisition and analysis › Automated multi-worm morphological feature extraction from images. ↔ multiworm_feature_extraction/2_extract_wormcutouts.py, lines 321–389 · score 0.66 · medial axis, worm mask, longest, perimeter, graph, contour
  12. [12] § Materials and methods › Droplet swimming recording and analysis › Automated quantitative analysis of swimming behavior. ↔ droplet_swimming/2_fframe_segmentation.py, lines 1–27 · score 0.62 · sam2_hiera_large.pt, generic prompt frame, checkpoint, CUDA, Model, swimming
  13. [13] § Materials and methods › Static images acquisition and analysis › Automated multi-worm morphological feature extraction from images. ↔ multiworm_feature_extraction/2_extract_wormcutouts.py, lines 233–311 · score 0.59 · overlapping worm masks, Connected components, largest, classified

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 501 lines · 20 KB · MIT · 4 matches

  1. """
  2. This script uses the SAM model to segment the entire image.
  3. The resulting cutouts are classified as either 'worm_any' or 'not worm' by a fine-tuned classifier. "Worm_any" also includes partial worms.
  4. Metrics are extracted from the final worms and saved to a CSV file.
  5. """
  6. import torch
  7. import torch.nn as nn
  8. import torchvision
  9. from torchvision import transforms
  10. import sys
  11. import numpy as np
  12. import matplotlib.pyplot as plt
  13. import cv2
  14. from PIL import Image
  15. import skimage
  16. from skimage.measure import label
  17. from scipy.ndimage import convolve
  18. import glob
  19. import os
  20. import pickle
  21. from skimage.measure import label
  22. from scipy.ndimage import convolve
  23. import shutil
  24. sys.path.append("PATH_TO_CLONED_SAM2_REPO/segment-anything-2")
  25. from sam2.build_sam import build_sam2
  26. from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
  27. torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
  28. if torch.cuda.get_device_properties(0).major >= 8:
  29. # turn on tfloat32 for Ampere GPUs
  30. torch.backends.cuda.matmul.allow_tf32 = True
  31. torch.backends.cudnn.allow_tf32 = True
  32. #Setup the SAM model
  33. checkpoint = "./segment-anything-2/checkpoints/sam2_hiera_large.pt" #Checkpoint for the SAM model
  34. model_cfg = "sam2_hiera_l.yaml" #Configuration file for the SAM model
  35. sam2 = build_sam2(model_cfg, checkpoint, device ='cuda', apply_postprocessing=False)
  36. mask_generator = SAM2AutomaticMaskGenerator(sam2)
  37. mask_generator_2 = SAM2AutomaticMaskGenerator(
  38. model=sam2,
  39. pred_iou_thresh=0.85,
  40. stability_score_thresh=0.85,
  41. stability_score_offset=0.85
  42. )
  43. #Setup the worm classifier
  44. classifdevice = torch.device("cuda:0")
  45. classif_weights = torchvision.models.ViT_H_14_Weights.IMAGENET1K_SWAG_E2E_V1
  46. worm_noworm_classif_model = torchvision.models.vit_h_14(weights=classif_weights)
  47. num_ftrs = worm_noworm_classif_model.heads.head.in_features
  48. worm_noworm_classif_model.heads.head = nn.Linear(num_ftrs, 2)
  49. worm_noworm_classif_model = worm_noworm_classif_model.to(classifdevice)
  50. worm_noworm_classif_model.load_state_dict(torch.load('PATH_TO_WORM_NOWORM_CLASSIFIER_WITH_PERFECT_WEIGHTS.pth', map_location=classifdevice)) #https://huggingface.co/lillyguisnet/celegans-classifier-vit-h-14-finetuned
  51. worm_noworm_classif_model.eval()
  52. class_names = ["notworm", "worm_any"]
  53. data_transforms = {
  54. 'val': transforms.Compose([
  55. transforms.Resize(518),
  56. transforms.CenterCrop(518),
  57. transforms.ToTensor(),
  58. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  59. ]),
  60. }
  61. def show_anns(anns, borders=True):
  62. if len(anns) == 0:
  63. return
  64. sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
  65. ax = plt.gca()
  66. ax.set_autoscale_on(False)
  67. img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4))
  68. img[:,:,3] = 0
  69. for ann in sorted_anns:
  70. m = ann['segmentation']
  71. color_mask = np.concatenate([np.random.random(3), [0.5]])
  72. img[m] = color_mask
  73. if borders:
  74. contours, _ = cv2.findContours(m.astype(np.uint8),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  75. # Try to smooth contours
  76. contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]
  77. cv2.drawContours(img, contours, -1, (0,0,1,0.4), thickness=1)
  78. ax.imshow(img)
  79. def is_on_edge(x, y, w, h, img_width, img_height):
  80. # Check left edge
  81. if x <= 0:
  82. return True
  83. # Check top edge
  84. if y <= 0:
  85. return True
  86. # Check right edge
  87. if (x + w) >= img_width - 1:
  88. return True
  89. # Check bottom edge
  90. if (y + h) >= img_height - 1:
  91. return True
  92. return False
  93. def get_valid_imaging_area(image, margin=5, max_iterations=100):
  94. """
  95. Find the actual microscope field of view in the image.
  96. """
  97. # Convert to grayscale if not already
  98. if len(image.shape) == 3:
  99. gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
  100. else:
  101. gray = image
  102. _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  103. # Find contours
  104. contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  105. if not contours:
  106. print("Warning: No valid imaging area found")
  107. return np.ones_like(gray, dtype=bool), False
  108. # Find the largest contour that's not the entire image
  109. valid_contours = [cnt for cnt in contours
  110. if 0.1 < cv2.contourArea(cnt) / (gray.shape[0] * gray.shape[1]) < 0.99]
  111. if not valid_contours:
  112. print("Warning: No valid contours found within acceptable size range")
  113. return np.ones_like(gray, dtype=bool), False
  114. largest_contour = max(valid_contours, key=cv2.contourArea)
  115. # Create mask of valid area
  116. valid_area_mask = np.zeros_like(gray, dtype=np.uint8)
  117. cv2.drawContours(valid_area_mask, [largest_contour], -1, 255, -1)
  118. # Erode the mask by margin pixels with iteration limit
  119. if margin > 0:
  120. kernel = np.ones((3, 3), np.uint8) # Using smaller kernel for more controlled erosion
  121. eroded_mask = valid_area_mask.copy()
  122. for _ in range(min(margin, max_iterations)):
  123. temp_mask = cv2.erode(eroded_mask, kernel)
  124. if np.sum(temp_mask) < 1000:
  125. break
  126. eroded_mask = temp_mask
  127. valid_area_mask = eroded_mask
  128. return valid_area_mask > 0, True
  129. def get_nonedge_masks(img_path):
  130. image = cv2.imread(img_path)
  131. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  132. img_height, img_width = image.shape[:2]
  133. # Generate masks
  134. masks2 = mask_generator_2.generate(image)
  135. valid_area, success = get_valid_imaging_area(image)
  136. nonedge_masks = []
  137. if success:
  138. # Use valid area method
  139. for mask in masks2:
  140. segmentation = mask['segmentation']
  141. if np.all(segmentation * valid_area == segmentation):
  142. nonedge_masks.append(segmentation)
  143. else:
  144. # Fall back to simple edge detection
  145. print(f"Falling back to simple edge detection for {img_path}")
  146. for mask in masks2:
  147. segmentation = mask['segmentation']
  148. coords = np.where(segmentation)
  149. y1, x1 = np.min(coords[0]), np.min(coords[1])
  150. y2, x2 = np.max(coords[0]), np.max(coords[1])
  151. h, w = (y2 - y1 + 1), (x2 - x1 + 1)
  152. if not is_on_edge(x1, y1, w, h, img_width, img_height):
  153. nonedge_masks.append(segmentation)
  154. return image, img_height, img_width, nonedge_masks
  155. def save_mask_cutouts(image, nonedge_masks, output_dir='PATH_TO_TEMP_CUTOUTS_DIR'):
  156. """
  157. Save cutouts of the masks from the image to the specified directory.
  158. Refreshes the output directory each time.
  159. """
  160. # Refresh temp directory
  161. if os.path.exists(output_dir):
  162. shutil.rmtree(output_dir)
  163. os.makedirs(output_dir, exist_ok=True)
  164. print(f"Saving {len(nonedge_masks)} non-edge cutouts to")
  165. for i, mask in enumerate(nonedge_masks):
  166. # Get bounding box coordinates of the mask
  167. coords = np.where(mask)
  168. y1, x1 = np.min(coords[0]), np.min(coords[1])
  169. y2, x2 = np.max(coords[0]), np.max(coords[1])
  170. # Create a 3D mask by repeating the 2D mask for each color channel
  171. mask_3d = np.repeat(mask[:, :, np.newaxis], 3, axis=2)
  172. # Apply mask to original image
  173. cutout = image * mask_3d
  174. # Crop to bounding box
  175. cutout = cutout[y1:y2+1, x1:x2+1]
  176. # Save the cutout as jpg
  177. cutout_path = os.path.join(output_dir, f'{i}.jpg')
  178. cv2.imwrite(cutout_path, cv2.cvtColor(cutout, cv2.COLOR_RGB2BGR))
  179. def classify_cutouts(nonedge_masks, cutouts_dir='PATH_TO_TEMP_CUTOUTS_DIR'):
  180. """
  181. Classify each cutout image as either 'worm' or 'not worm' using the pre-trained classifier.
  182. """
  183. classifications = []
  184. for i in range(len(nonedge_masks)):
  185. cutout_path = os.path.join(cutouts_dir, f'{i}.jpg')
  186. imgg = Image.open(cutout_path)
  187. imgg = data_transforms['val'](imgg)
  188. imgg = imgg.unsqueeze(0)
  189. imgg = imgg.to(classifdevice)
  190. outputs = worm_noworm_classif_model(imgg)
  191. _, preds = torch.max(outputs, 1)
  192. classifications.append(class_names[preds])
  193. return classifications
  194. def merge_and_clean_worm_masks(classifications, nonedge_masks, overlap_threshold=0.95, min_area=25):
  195. """
  196. Merge overlapping worm masks and clean the results by removing small regions and keeping only the largest connected component.
  197. Also checks for and removes masks with holes.
  198. """
  199. worm_masks = []
  200. for i, classification in enumerate(classifications):
  201. if classification == "worm_any":
  202. worm_masks.append(nonedge_masks[i])
  203. if worm_masks:
  204. # Initialize list to track which masks have been merged
  205. merged_masks = []
  206. final_masks = []
  207. # Compare each mask with every other mask
  208. for i in range(len(worm_masks)):
  209. if i in merged_masks:
  210. continue
  211. current_mask = worm_masks[i]
  212. current_area = np.sum(current_mask)
  213. merged = False
  214. for j in range(i + 1, len(worm_masks)):
  215. if j in merged_masks:
  216. continue
  217. other_mask = worm_masks[j]
  218. # Calculate overlap
  219. overlap = np.sum(current_mask & other_mask)
  220. overlap_ratio = overlap / min(current_area, np.sum(other_mask))
  221. # If overlap is more than threshold, merge the masks
  222. if overlap_ratio > overlap_threshold:
  223. current_mask = current_mask | other_mask
  224. current_area = np.sum(current_mask)
  225. merged_masks.append(j)
  226. merged = True
  227. final_masks.append(current_mask)
  228. # Clean final masks - remove regions smaller than min_area pixels and handle discontinuous segments
  229. worm_masks = []
  230. for i, mask in enumerate(final_masks):
  231. if np.sum(mask) >= min_area:
  232. # Check for holes using contour hierarchy
  233. contours, hierarchy = cv2.findContours((mask * 255).astype(np.uint8),
  234. cv2.RETR_TREE,
  235. cv2.CHAIN_APPROX_SIMPLE)
  236. has_holes = False
  237. if hierarchy is not None:
  238. hierarchy = hierarchy[0] # Get the first dimension
  239. for h in hierarchy:
  240. if h[3] >= 0: # If has parent, it's a hole
  241. has_holes = True
  242. print(f"Skipping mask {i} due to holes in the mask")
  243. break
  244. if not has_holes:
  245. # Find connected components in the mask
  246. num_labels, labels = cv2.connectedComponents(mask.astype(np.uint8))
  247. if num_labels > 2: # More than one segment (label 0 is background)
  248. # Get sizes of each segment
  249. unique_labels, label_counts = np.unique(labels[labels != 0], return_counts=True)
  250. # Keep only the largest segment
  251. largest_label = unique_labels[np.argmax(label_counts)]
  252. mask = (labels == largest_label).astype(np.uint8)
  253. worm_masks.append(mask)
  254. num_distinct_worms = len(worm_masks)
  255. print(f"Number of distinct worm regions: {num_distinct_worms}")
  256. else:
  257. num_distinct_worms = 0
  258. return worm_masks, num_distinct_worms
  259. def filter_worms(allworms_metrics, threshold):
  260. filtered_metrics = []
  261. for worm in allworms_metrics:
  262. if worm['area'] > threshold * np.mean([worm['area'] for worm in allworms_metrics]):
  263. filtered_metrics.append(worm)
  264. return filtered_metrics
  265. def extract_worm_metrics(worm_masks, img_path, img_height, img_width, threshold=0.75):
  266. """
  267. Extract metrics for each worm mask including area, perimeter, medial axis measurements, etc.
  268. """
  269. # Get image ID (filename without extension)
  270. img_id = os.path.splitext(os.path.basename(img_path))[0]
  271. allworms_metrics = []
  272. for i, npmask in enumerate(worm_masks):
  273. print(f"Processing worm {i}")
  274. num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats((npmask * 255).astype(np.uint8), connectivity=8)
  275. largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])
  276. largest_component_mask = (labels == largest_label).astype(np.uint8)
  277. area = np.sum(largest_component_mask)
  278. contours, hierarchy = cv2.findContours((largest_component_mask*255).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  279. perimeter = cv2.arcLength(contours[0], True)
  280. # Get medial axis and distance transform
  281. medial_axis, distance = skimage.morphology.medial_axis(largest_component_mask > 0, return_distance=True)
  282. structuring_element = np.array([[1, 1, 1], [1, 10, 1], [1, 1, 1]], dtype=np.uint8)
  283. neighbours = convolve(medial_axis.astype(np.uint8), structuring_element, mode='constant', cval=0)
  284. end_points = np.where(neighbours == 11, 1, 0)
  285. branch_points = np.where(neighbours > 12, 1, 0)
  286. labeled_branches = label(branch_points, connectivity=2)
  287. branch_indices = np.argwhere(labeled_branches > 0)
  288. end_indices = np.argwhere(end_points > 0)
  289. indices = np.concatenate((branch_indices, end_indices), axis=0)
  290. # Find longest path through medial axis
  291. paths = []
  292. for start in range(len(indices)):
  293. for end in range(len(indices)):
  294. startid = tuple(indices[start])
  295. endid = tuple(indices[end])
  296. route, weight = skimage.graph.route_through_array(np.invert(medial_axis), startid, endid)
  297. length = len(route)
  298. paths.append([startid, endid, length, route, weight])
  299. longest_length = max(paths, key=lambda x: x[2])
  300. pruned_mediala = np.zeros((img_height, img_width), dtype=np.uint8)
  301. for coord in range(len(longest_length[3])):
  302. pruned_mediala[longest_length[3][coord]] = 1
  303. # Get measurements along medial axis
  304. medial_axis_distances_sorted = [distance[pt[0], pt[1]] for pt in longest_length[3]]
  305. medialaxis_length_list = 0 + np.arange(0, len(medial_axis_distances_sorted))
  306. pruned_medialaxis_length = np.sum(pruned_mediala)
  307. mean_wormwidth = np.mean(medial_axis_distances_sorted)
  308. mid_length = medial_axis_distances_sorted[int(len(medial_axis_distances_sorted)/2)]
  309. worm_metrics = {
  310. "img_id": img_id,
  311. "worm_id": i,
  312. "area": area,
  313. "perimeter": perimeter,
  314. "medial_axis_distances_sorted": medial_axis_distances_sorted,
  315. "medialaxis_length_list": np.ndarray.tolist(medialaxis_length_list),
  316. "pruned_medialaxis_length": pruned_medialaxis_length,
  317. "mean_wormwidth": mean_wormwidth,
  318. "mid_length_width": mid_length,
  319. "mask": largest_component_mask
  320. }
  321. allworms_metrics.append(worm_metrics)
  322. return filter_worms(allworms_metrics, threshold = threshold)
  323. def save_worms(allworms_metrics, original_image=None, cutouts_dir='PATH_TO_FINAL_CUTOUTS_DIR',
  324. metrics_dir='PATH_TO_FINAL_METRICS_DIR'):
  325. """
  326. Filter worms by area and save the filtered cutouts and metrics.
  327. """
  328. if not allworms_metrics:
  329. print("No worm metrics provided")
  330. return []
  331. img_id = allworms_metrics[0]["img_id"]
  332. # Save cutouts of filtered worms for visualization
  333. for i, worm in enumerate(allworms_metrics):
  334. cutout_path = os.path.join(cutouts_dir, f'{img_id}_worm_{i}.png')
  335. cutout_name = f'{img_id}_worm_{i}' # The name that will appear on the image
  336. if original_image is not None:
  337. overlay = original_image.copy()
  338. overlay[worm["mask"] > 0] = [0, 255, 0] # Green color
  339. alpha = 0.4 # Back to original 40% transparency
  340. blended = cv2.addWeighted(original_image, 1 - alpha, overlay, alpha, 0)
  341. font = cv2.FONT_HERSHEY_SIMPLEX
  342. cv2.putText(blended, cutout_name, (10, 30), font, 1, (255, 255, 255), 2)
  343. cv2.imwrite(cutout_path, cv2.cvtColor(blended, cv2.COLOR_RGB2BGR))
  344. else:
  345. # Fall back to saving just the mask if original image not provided
  346. cv2.imwrite(cutout_path, (worm["mask"] * 255).astype(np.uint8))
  347. # Save metrics as pickle using img_id as filename
  348. metrics_path = os.path.join(metrics_dir, f'{img_id}.pkl')
  349. with open(metrics_path, 'wb') as f:
  350. pickle.dump(allworms_metrics, f)
  351. print(f"Saved filtered metrics to {metrics_path}")
  352. return allworms_metrics
  353. def process_folder(input_folder, temp_cutouts_dir='PATH_TO_TEMP_CUTOUTS_DIR',
  354. final_cutouts_dir='PATH_TO_FINAL_CUTOUTS_DIR',
  355. metrics_dir='PATH_TO_FINAL_METRICS_DIR',
  356. noworms_file='PATH_TO_NOWORMS_FILE.csv'):
  357. """
  358. Process all images in a folder through the complete worm analysis pipeline.
  359. """
  360. # Create/check noworms CSV file
  361. if not os.path.exists(noworms_file):
  362. with open(noworms_file, 'w') as f:
  363. f.write('image_path\n')
  364. # Create/check final cutouts directory
  365. if not os.path.exists(final_cutouts_dir):
  366. os.makedirs(final_cutouts_dir)
  367. # Create/check metrics directory
  368. if not os.path.exists(metrics_dir):
  369. os.makedirs(metrics_dir)
  370. # Get list of image files
  371. image_files = glob.glob(os.path.join(input_folder, '*.jpg'))
  372. # Process each image
  373. for img_path in image_files:
  374. print(f"\nProcessing {img_path}")
  375. try:
  376. # Extract masks
  377. image, img_height, img_width, nonedge_masks = get_nonedge_masks(img_path)
  378. if len(nonedge_masks) == 0:
  379. print(f"No valid masks found in {img_path}")
  380. print(f"Number of worms in image: 0")
  381. with open(noworms_file, 'a') as f:
  382. f.write(f'{img_path}\n')
  383. continue
  384. save_mask_cutouts(image, nonedge_masks, temp_cutouts_dir)
  385. classifications = classify_cutouts(nonedge_masks, temp_cutouts_dir)
  386. worm_masks, num_distinct_worms = merge_and_clean_worm_masks(
  387. classifications, nonedge_masks, temp_cutouts_dir)
  388. if num_distinct_worms == 0:
  389. print(f"No worms detected in {img_path}")
  390. print(f"Number of worms in image: 0")
  391. with open(noworms_file, 'a') as f:
  392. f.write(f'{img_path}\n')
  393. continue
  394. worm_metrics = extract_worm_metrics(worm_masks, img_path, img_height, img_width)
  395. print(f"Final number of worms in image: {len(worm_metrics)}")
  396. save_worms(worm_metrics, original_image=image, cutouts_dir=final_cutouts_dir, metrics_dir=metrics_dir)
  397. except Exception as e:
  398. print(f"Error processing {img_path}: {str(e)}")
  399. print(f"Number of worms in image: 0")
  400. continue
  401. print(f"\nAnalysis complete. Processed {len(image_files)} images.")
  402. print(f"Results saved to {metrics_dir}")
  403. input_folder = 'PATH_TO_INPUT_FOLDER'
  404. process_folder(input_folder)

2_extract_wormcutouts.py at commit 92d4d38, under MIT · at the source

Overview

  1. Department of Biology, McGill University, Montreal, Quebec, Canada
Institutions: McGill University (Canada)
Journal: PLoS computational biology, volume 22, issue 7, article e1013441
Dates: received 15 August 2025; accepted 26 June 2026; published online 22 July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pcbi.1013441 · PMID 42485426 · PMCID PMC13492816 · OpenAlex W7170066936
Open access: gold, a free copy (OpenAlex)
Status: code verified
Methods: Spectral & time-frequency, Connectivity, Graphs, fMRI & imaging, Single-unit activity, calcium imaging, Smoothing, state filtering, decompositions, Machine learning
MeSH: Caenorhabditis elegans*, Image Processing, Computer-Assisted*, Algorithms, Animals, Computational Biology, Neurons, Software (* major topic)
Journal subjects: Biology and Life Sciences, Physiology, Biological Locomotion, Swimming, Research and Analysis Methods, Imaging Techniques, Neuroimaging, Calcium Imaging, Neuroscience, Animal Studies, Experimental Organism Systems, Model Organisms, Caenorhabditis Elegans, Animal Models, Organisms, Eukaryota, Animals, Invertebrates, Nematoda, Caenorhabditis, Zoology, Fluorescence Imaging, Crawling, Developmental Biology, Morphogenesis, Morphogenic Segmentation, Psychology, Behavior, Animal Behavior, Social Sciences, Image Analysis
Topic: Genetics, Aging, and Longevity in Model Organisms (Aging, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Funding: National Science and Engineering Research Council (RGPIN/05117-2014); Canadian Institutes of Health Research (PJT-155980); Canadian Foundation for Innovation (32581); Canada Research Chairs Program (950-231541); Fonds de recherche du Québec ‐ Nature et technologies (300853)
Citations: not cited yet (Europe PMC); 66 references in the paper

Abstract

Quantitative phenotyping of Caenorhabditis elegans is essential across numerous fields, yet data extraction remains a significant analytical bottleneck. Traditional segmentation methods based on pixel-intensity thresholding are highly sensitive to variations in imaging conditions and often fail in the presence of noise, overlaps, or uneven illumination. These failures necessitate meticulous experimental setups, expensive hardware, or extensive manual curation, which reduces throughput and introduces bias. Here, we introduce TWARDIS (Tools for Worm Automated Recognition & Dynamic Imaging System), a modular, Python-based analysis suite that leverages large foundation vision models, specifically the Segment Anything Models (SAM and SAM2) and a fine-tuned vision transformer classifier, to overcome some of these limitations. We demonstrate the versatility of an AI compound system approach across diverse modalities. For static morphological analysis, TWARDIS successfully resolved overlapping worms in noisy images without human intervention, showing a 0.999 correlation with manual segmentation. In behavioral assays (swimming and crawling), the pipeline enabled high-definition postural analysis even in low-resolution, wide-field recordings where the worm occupied only ~0.25% of the field of view, accurately resolving complex postures without frame rejection. Finally, when applied to calcium imaging of semi-restricted animals, TWARDIS provided precise, frame-by-frame segmentation of neural compartments, reducing the artificial signal flattening common in traditional region-of-interest-based approaches and enabling the extraction of biologically accurate, absolute head positions. The system’s hardware-scalable architecture and modular design ensure both current accessibility and future improvements without restructuring. By automating some of the most time-consuming aspects of image analysis, TWARDIS removes many critical bottlenecks and tradeoffs in C. elegans research, enabling researchers to focus on biological questions rather than technical image processing challenges.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 13 matches between paragraphs and lines of code.

lillyguisnet/TWARDISv0.1

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 92d4d382bf0e41b408cbc3389ea22f196537a56f, 17 May 2026
Languages: Python (17)
Size: 26 files, 17 scripts
Software Heritage: not archived
Found in: the text, “Hardware and code”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (15 files), OpenCV (12 files), Matplotlib (10 files), Pillow (9 files), PyTorch (8 files), SciPy (8 files), h5py (6 files), scikit-image (4 files), NetworkX (2 files), pandas (2 files), tifffile (2 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
19 files

huggingface.co/lillyguisnet/celegans-classifier-vit-h-14-finetuned

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 111e51be4ea7bd042252a11ab632839cb156b001, 24 March 2025
Size: 4 files, 0 scripts
Software Heritage: not archived
Found in: the text, “Hardware and code”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 17 scripts, each with its path and the digest of its content;
  • 13 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability

All relevant data and code are within the paper, its Supporting Information files, and on GitHub at https://github.com/lillyguisnet/TWARDISv0.1. The fine-tuned worm classifier model is available on HuggingFace at https://huggingface.co/lillyguisnet/celegans-classifier-vit-h-14-finetuned.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 7 MeSH terms, 5 funders, 46 references.

Cite

This paper

Guisnet, A., & Hendricks, M. (2026). Large vision model framework for automated C. elegans analysis: From static morphometry to dynamic neural activity. PLoS computational biology, 22(7), e1013441. https://doi.org/10.1371/journal.pcbi.1013441

BibTeX

@article{guisnet2026large,
author = {Guisnet, Aurélie and Hendricks, Michael},
title = {{Large vision model framework for automated C. elegans analysis: From static morphometry to dynamic neural activity}},
journal = {PLoS computational biology},
year = {2026},
month = jul,
volume = {22},
number = {7},
pages = {e1013441},
publisher = {PLOS},
issn = {1553-734X},
doi = {10.1371/journal.pcbi.1013441},
url = {https://doi.org/10.1371/journal.pcbi.1013441},
pmid = {42485426},
pmcid = {PMC13492816}
}

RIS

TY - JOUR
AU - Guisnet, Aurélie
AU - Hendricks, Michael
TI - Large vision model framework for automated C. elegans analysis: From static morphometry to dynamic neural activity
T2 - PLoS computational biology
J2 - PLoS Comput Biol
PY - 2026
DA - 2026/07/22
VL - 22
IS - 7
SP - e1013441
SN - 1553-734X
PB - PLOS
DO - 10.1371/journal.pcbi.1013441
UR - https://doi.org/10.1371/journal.pcbi.1013441
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pcbi.1013441",
"type": "article-journal",
"title": "Large vision model framework for automated C. elegans analysis: From static morphometry to dynamic neural activity",
"container-title": "PLoS computational biology",
"author": [
{
"family": "Guisnet",
"given": "Aurélie"
},
{
"family": "Hendricks",
"given": "Michael"
}
],
"container-title-short": "PLoS Comput Biol",
"volume": "22",
"issue": "7",
"page": "e1013441",
"DOI": "10.1371/journal.pcbi.1013441",
"PMID": "42485426",
"PMCID": "PMC13492816",
"ISSN": "1553-734X",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pcbi.1013441",
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
22
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41467-026-72709-w [code]
An epifluorescence microscope design for naturalistic behavior and cellular activity in freely moving Caenorhabditis elegans.
Journal: Nature communications
In common: tifffile, OpenCV, scikit-image, 7 other tools, C. elegans, 3 references, 2 authors
[2] doi:10.1038/s41467-026-72710-3 [code]
A modular multi-color fluorescence microscope for simultaneous tracking of cellular activity and behavior.
Journal: Nature communications
In common: tifffile, OpenCV, scikit-image, 5 other tools, C. elegans, optical imaging (calcium, voltage, 2-photon), 3 references
[3] doi:10.1038/s41598-026-57519-w [code]
Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL.
Journal: Scientific reports
In common: tifffile, NetworkX, OpenCV, 8 other tools, methods / tools, 1 reference
[4] doi:10.1371/journal.pcbi.1014571 [code]
SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.
Journal: PLoS computational biology
In common: tifffile, NetworkX, OpenCV, 7 other tools, 2 references
[5] doi:10.1016/j.isci.2026.116206 [code]
Gut distension evokes rapid neural dynamics in vagal and hindbrain populations of larval zebrafish.
Journal: iScience
In common: tifffile, NetworkX, OpenCV, 7 other tools, optical imaging (calcium, voltage, 2-photon), 1 reference
[6] doi:10.1364/boe.600665 [code]
NeuroSeg-MF: robust neuron segmentation in two-photon Ca&lt;sup&gt;2+&lt;/sup&gt; imaging using multi-feature fusion and detection-guided SAM.
Journal: Biomedical optics express
In common: tifffile, OpenCV, Pillow, 5 other tools, optical imaging (calcium, voltage, 2-photon), methods / tools, 2 references
[7] doi:10.1364/boe.605322 [code]
Generalized plaque digitization framework for multi-dimensional mesoscopic images.
Journal: Biomedical optics express
In common: tifffile, OpenCV, scikit-image, 7 other tools, 1 reference
[8] doi:10.1016/j.patter.2026.101538 [code]
A multi-modal foundation model for brain disease diagnosis and medical imaging.
Journal: Patterns (New York, N.Y.)
In common: tifffile, OpenCV, scikit-image, 7 other tools, 1 reference
[9] doi:10.7554/elife.110074 [code]
Disentangling cephalopod chromatophores motor units with computer vision.
Journal: eLife
In common: NetworkX, OpenCV, scikit-image, 6 other tools, 2 references
[10] doi:10.1371/journal.pcbi.1013499 [code]
VesiclePy: A machine learning vesicle analysis toolbox for volume electron microscopy.
Journal: PLoS computational biology
In common: OpenCV, scikit-image, h5py, 6 other tools, methods / tools, 2 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.