Views
No views yet
1# Install lighter_zoo package
2%pip install lighter_zoo -U -qqNote: you may need to restart the kernel to use updated packages.1# Imports
2import torch
3from lighter_zoo import SegResEncoder
4from monai.transforms import (
5 Compose, LoadImage, EnsureType, Orientation,
6 ScaleIntensityRange, CropForeground
7)
8from monai.inferers import SlidingWindowInferer1# Load pre-trained model
2model = SegResEncoder.from_pretrained(
3 "project-lighter/ct_fm_feature_extractor"
4)
5model.eval()1# Preprocessing pipeline
2preprocess = Compose([
3 LoadImage(ensure_channel_first=True), # Load image and ensure channel dimension
4 EnsureType(), # Ensure correct data type
5 Orientation(axcodes="SPL"), # Standardize orientation
6 # Scale intensity to [0,1] range, clipping outliers
7 ScaleIntensityRange(
8 a_min=-1024, # Min HU value
9 a_max=2048, # Max HU value
10 b_min=0, # Target min
11 b_max=1, # Target max
12 clip=True # Clip values outside range
13 ),
14 CropForeground() # Remove background to reduce computation
15])monai.transforms.croppad.array CropForeground.__init__:allow_smaller: Current default value of argument `allow_smaller=True` has been deprecated since version 1.2. It will be changed to `allow_smaller=False` in version 1.5.1# Input path
2input_path = "/home/suraj/Repositories/lighter-ct-fm/semantic-search-app/assets/scans/s0114.nii.gz"
3
4# Preprocess input
5input_tensor = preprocess(input_path)
6
7# Run inference
8with torch.no_grad():
9 output = model(input_tensor.unsqueeze(0))[-1]
10
11 # Average pooling compressed the feature vector across all patches. If this is not desired, remove this line and
12 # use the output tensor directly which will give you the feature maps in a low-dimensional space.
13 avg_output = torch.nn.functional.adaptive_avg_pool3d(output, 1).squeeze()
14
15print("✅ Feature extraction completed")
16print(f"Output shape: {avg_output.shape}")✅ Feature extraction completed
Output shape: torch.Size([512])1# Plot distribution of features
2import matplotlib.pyplot as plt
3_ = plt.hist(avg_output.cpu().numpy(), bins=100)